From 65431f4ec624c5df106a1eaffbfab918d35f3d89 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 02:57:30 +1300 Subject: [PATCH 01/13] Preserve complete immutable selector release and World preparation carrier --- .github/workflows/ci.yml | 2 + .../game-design-service/api-contracts.md | 8 +- .../world-management-service/api-contracts.md | 4 + ...ame-authoring-publishing-and-activation.md | 2 +- .../world-runtime-and-movement.md | 2 +- .../game-design/v1/game_design_service.proto | 2 + .../world_published_start_location_read.proto | 60 ++ ...alCreatorPartyPostgresIntegrationTest.java | 5 +- .../WorldDraftTerminalReadGrpcCodec.java | 131 +-- ...uthoredWorldLaunchDescriptorGrpcCodec.java | 12 +- ...thoredWorldReleaseAttestationEvidence.java | 164 +++- .../WorldDraftStartLocationEvidence.java | 286 ++++++ .../WorldPublishedStartLocationClient.java | 151 +++ .../WorldPublishedStartLocationEvidence.java | 556 ++++++++++++ .../WorldPublishedStartLocationGrpcCodec.java | 216 +++++ .../WorldDraftTerminalReadGrpcCodecTest.java | 50 +- ...redWorldLaunchDescriptorGrpcCodecTest.java | 38 + ...edWorldReleaseAttestationSelectorTest.java | 290 ++++++ .../WorldDraftStartLocationEvidenceTest.java | 156 ++++ ...WorldPublishedStartLocationClientTest.java | 155 ++++ ...ldPublishedStartLocationGrpcCodecTest.java | 179 ++++ .../dto/PublishedReleaseBundleDto.java | 52 +- .../entity/PublishedReleaseBundle.java | 1 + .../PublishedReleaseBundleRepository.java | 61 ++ .../PublishedReleaseBundleService.java | 11 + .../CompleteLaunchBindingServiceImpl.java | 73 +- .../impl/LaunchDescriptorServiceImpl.java | 19 +- .../impl/PublishedReleaseBundleContract.java | 116 +++ .../PublishedReleaseBundleServiceImpl.java | 133 ++- .../VersionPublishCommandServiceImpl.java | 46 +- ...ublished_world_start_location_evidence.sql | 235 +++++ ...ishSelectionRepositoryIntegrationTest.java | 10 +- ...leaseCanonicalIdentityIntegrationTest.java | 223 ++++- .../PublishedReleaseBundleRepositoryTest.java | 56 ++ .../CompleteLaunchBindingServiceImplTest.java | 50 + .../impl/LaunchDescriptorServiceImplTest.java | 74 +- ...PublishedReleaseBundleServiceImplTest.java | 187 ++++ .../impl/PublishedWorldSelectorFixtures.java | 406 +++++++++ .../VersionPublishCommandServiceImplTest.java | 255 ++++++ .../WorldPublishedStartLocationMtlsTest.java | 335 +++++++ ...orldCanonicalFrozenTopologyRepository.java | 22 + .../WorldCanonicalInstancePreparation.java | 97 +- ...anonicalInstancePreparationRepository.java | 106 ++- .../WorldCompleteLaunchBindingReceipt.java | 6 + .../WorldDraftStartLocationReceipt.java | 131 +-- ...PublishedStartLocationReadGrpcService.java | 167 ++++ ...WorldPublishedStartLocationRepository.java | 79 ++ .../WorldPublishedStartLocationSource.java | 18 + ...release_start_location_materialization.sql | 218 +++++ ...ncePreparationPostgresIntegrationTest.java | 49 + ...aphApplicationPostgresIntegrationTest.java | 858 +++++++++++++++++- .../WorldDraftStartLocationReceiptTest.java | 47 + ...ishedStartLocationReadGrpcServiceTest.java | 159 ++++ 53 files changed, 6480 insertions(+), 289 deletions(-) create mode 100644 protos/world-management/v1/world_published_start_location_read.proto create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/WorldPublishedStartLocationMtlsTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationReadGrpcService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationSource.java create mode 100644 services/world-management-service/src/main/resources/db/migration/V42__world_release_start_location_materialization.sql create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftStartLocationReceiptTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationReadGrpcServiceTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8312ef70b0..087f843294 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2216,6 +2216,8 @@ jobs: bash dev-tools/validation/inspect-test-results.sh \ --strict \ --require-suite net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#publishedSelectorJoinsExactFrozenCheckpointToOriginalAppliedWithoutWrites()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#permissionUnverifiedGraphAndFrozenHistoryCannotSupplyPublishedSelector()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#freshApplicationRetainsCompleteExactGraphAndOriginalAccountReadbackAndRetriesAfterFreeze()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#explicitEmptyOptionalFamiliesProduceAppliedGraphAndExactTypedStartSelector()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#newAccountBoundGraphRequiresCompleteOriginalDeclaration()' \ diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 4ba8e244a1..e3e4854aa0 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -58,11 +58,15 @@ The complete immutable resolved launch binding consists of this unchanged closed #### Separate complete release-attestation evidence -The closed `game-design-authored-world-release-attestation/v1` evidence carries, in order, `schemaVersion=1`, `targetNamespace`, `descriptorResultDigest`, canonical `canonicalTenantId` and `canonicalVersionId`, `worldSlug`, `authoredWorldSourceOperationId`, `authoredWorldSourceEvidenceDigest`, `launchDescriptorId`, `publishedReleaseBundleRef`, `versionStateEpoch`, `publishWorkflowId`, `commitId`, `participantDigests`, `manifestHash`, `manifestSchemaVersion`, `requiredManifestAssetKeys`, `artifactDigests`, `commandDefinitions`, and `generationConfigRevision`, followed by its derived `evidenceDigest`. The exact nonblank textual `publishWorkflowId` is an opaque owner operation handle, not a UUID or a tenant selector; consumers must not parse a legacy owner key out of it or rewrite an immutable retained workflow identity. The descriptor is transported and independently verified alongside this evidence; its result digest already binds every closed request/result field, including private owner selectors, patch/remap presence and source identity. The attestation's canonical UUIDs do not authorize another owner to reuse those private selectors as local keys. +The closed selector-bearing `game-design-authored-world-release-attestation/v2` evidence carries, in order, `schemaVersion=2`, `targetNamespace`, `descriptorResultDigest`, canonical `canonicalTenantId` and `canonicalVersionId`, `worldSlug`, `authoredWorldSourceOperationId`, `authoredWorldSourceEvidenceDigest`, `launchDescriptorId`, `publishedReleaseBundleRef`, `versionStateEpoch`, `publishWorkflowId`, `commitId`, `participantDigests`, `manifestHash`, `manifestSchemaVersion`, `requiredManifestAssetKeys`, `artifactDigests`, `commandDefinitions`, `generationConfigRevision`, and `worldStartLocationEvidence`, followed by its derived `evidenceDigest`. The exact nonblank textual `publishWorkflowId` is an opaque owner operation handle, not a UUID or a tenant selector; consumers must not parse a legacy owner key out of it or rewrite an immutable retained workflow identity. The descriptor is transported and independently verified alongside this evidence; its result digest already binds every closed request/result field, including private owner selectors, patch/remap presence and source identity. The attestation's canonical UUIDs do not authorize another owner to reuse those private selectors as local keys. + +`worldStartLocationEvidence` is the complete unchanged canonical `world-published-start-location-evidence/v1` value from the [authenticated World selector read](../world-management-service/api-contracts.md#published-authored-start-location-selector): the exact frozen publication request and complete World affected set, original Account binding, original APPLIED bytes and immutable selector receipt. Game Design obtains this actual owner evidence before entering its release-finalization transaction, exact-compares it with the durable selected Draft and every required participant, and retains it with the immutable bundle. The digest appends the field-name/value pair `worldStartLocationEvidence.canonicalBytesBase64` after `generationConfigRevision`; the value is canonical padded base64 of every byte of that closed evidence, not a substituted receipt or aggregate digest. Proto field 22 carries those same canonical bytes and is mandatory for v2. Later launch reads use the committed local bundle inside the owner snapshot; they do not contact World or resolve replacement evidence. Missing authenticated freeze acknowledgement or current authorization leaves creation denied; a synchronized Draft selection digest is not the owner's freeze request digest. + +Retained attestation/v1 preserves its original domain, schema, field order, digest and JSON/wire bytes, with no added null selector field. It cannot be promoted or backfilled into selector-bearing evidence and does not satisfy the selector-to-runtime-room handoff. Descriptor/v1 is unchanged by this separate attestation version. The digest uses that versioned domain followed by field-name/value segments in the listed order, each framed by exact decimal strict-UTF-8 byte length, `:`, and bytes, as in the descriptor contract. Positive counters and schema versions use canonical decimal strings; UUIDs are canonical non-nil text. Source, descriptor, dedicated ability, manifest, artifact and outer evidence digests use `sha256:` plus 64 lowercase hexadecimal digits. Participant `contentDigest` instead preserves its existing owner format of exactly 64 lowercase hexadecimal digits without a prefix; receivers neither prefix that committed value nor accept an alternate representation. Arrays bind the segment pair `.size` and its canonical nonnegative decimal count, then every indexed field in exact retained order; there is no sorting or Unicode normalization during hashing. Object-array labels are `[].`; string-array labels are `[]`. Optional fields append `.present` and `.value`, with lowercase boolean presence and empty absent value, exactly as in the descriptor. Each participant entry binds, in order, `participantKey`, `scopeValue`, `baseVersionId` presence/value, `appliedCommitId`, `contentDigest`, `digestSchemaVersion`, and `abilitySchemaDigest` presence/value. A complete full-Version attestation has exactly the five distinct required owners in canonical order (`WORLD_MANAGEMENT`, `ENTITY_MANAGEMENT`, `GAME_LOGIC`, `AUTOMATION_SCRIPTING`, `GAME_DESIGN_CONTROL_PLANE`), exact descriptor Version scope, no patch base, successful supported-schema evidence and one identical nonblank applied commit. Only Game Logic supplies the nonblank dedicated ability-schema digest. Failed owner results are not successful attestation entries. -Participant schemas remain their owner-specific supported versions: World Management `3` under its [Digest Input Manifest](../world-management-service/runtime-and-data.md#digest-input-manifest), Entity Management `2`, Game Logic `1`, Automation & Scripting `5`, and Game Design control plane `1`. The outer attestation's version `1` does not renumber those schemas. Each artifact entry binds, in order, `usageKey`, `artifactKind`, `immutableObjectKey`, `contentDigest`, `contentType`, and `artifactSchemaVersion`. Required usage keys and artifact entries are unique and retained in unsigned UTF-8 usage-key order; every required key selects exactly one actual-byte artifact entry. Artifact schema `1` retains the existing flat `artifacts/sha256/` object address. A proved empty manifest remains distinct from missing manifest evidence. Every command-definition string and the exact generation revision is retained. Local row IDs, private tenant keys and publication timestamps are owner storage metadata, not alternate canonical identity or authority fields in this separate schema. Neither an aggregate participant digest nor the manifest hash replaces dedicated ability or individual byte evidence. +Participant schemas remain their owner-specific supported versions: World Management `3` under its [Digest Input Manifest](../world-management-service/runtime-and-data.md#digest-input-manifest), Entity Management `2`, Game Logic `1`, Automation & Scripting `5`, and Game Design control plane `1`. The outer attestation's version does not renumber those schemas. Each artifact entry binds, in order, `usageKey`, `artifactKind`, `immutableObjectKey`, `contentDigest`, `contentType`, and `artifactSchemaVersion`. Required usage keys and artifact entries are unique and retained in unsigned UTF-8 usage-key order; every required key selects exactly one actual-byte artifact entry. Artifact schema `1` retains the existing flat `artifacts/sha256/` object address. A proved empty manifest remains distinct from missing manifest evidence. Every command-definition string and the exact generation revision is retained. Local row IDs, private tenant keys and publication timestamps are owner storage metadata, not alternate canonical identity or authority fields in this separate schema. Neither an aggregate participant digest nor the manifest hash replaces dedicated ability or individual byte evidence. `GetCompleteLaunchBinding` takes the exact existing `GetLaunchDescriptorRequest` selector, echoes its separate non-nil read request ID, and returns the independently validated descriptor and separate attestation together or an error without either successful component. It authenticates the exact same-namespace Game Session or World workload before producer access. The consumer authenticates Game Design from the negotiated TLS peer before releasing its request, rejects unknown fields and missing or conflicting components, and verifies the exact request echo and both exhaustive digests. The old descriptor-only read remains explicitly narrower; it cannot be used as a fallback for this method. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index ea9d2de5b3..8c8a3b39b2 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -306,6 +306,10 @@ Game Design carries the unchanged World-owned selector evidence in its immutable The original typed World revision carries exactly one complete fresh-graph declaration, including the exact canonical tenant and Version, the typed start selector, and six explicit nonnegative family counts in order: REGION, ZONE, ROOM, ROOM_EXIT, GENERATION_RULE, WORLD_ENTITY_SPAWN_BINDING. Every count is present, including zero; omitted, duplicate or reordered families are not an empty-family declaration. The original Account-bound input digest covers this declaration and its selector. World verifies the declared counts against both the complete typed input and actual same-Version owner rows under its existing publication fence, verifies the selected ROOM belongs to that graph, and atomically retains the complete declaration and selector with the graph and immutable `APPLIED` result. Exact replay preserves the original evidence; retained history without this evidence is not backfilled or promoted into a start selector. +`ReadWorldPublishedStartLocation` is a distinct read-only World-to-Game Design handoff, not the Account terminal-outcome read. Its complete selection is the exact frozen checkpoint tuple: workload namespace, canonical tenant and Version UUIDs, intake request UUID, publication fence, publication request and digest, Game Design version-state epoch, workflow, selected commit, World content digest/schema, and complete ordered World affected tuples. The response echoes that selection and carries the unchanged original Account binding, committed `APPLIED` result and start-selector receipt. World joins independently committed frozen and application journals before responding; missing or conflicting evidence is non-authorizing. Both endpoints require the exact same-namespace workload peer before releasing or decoding data, and the World receiver rejects authenticated end-user context. Canonical carrier decoding verifies the closed structure, original bindings and digests but does not itself authenticate World or establish current Account authority. + +The retained graph/2 payload preserves World's original UTF-8 owner serialization and is hashed byte-for-byte. Its closed typed graph checks do not impose RFC 8785 property order or rewrite historical bytes. The separate closed application result and selector receipt retain their own canonical representations. A consumer cannot reject or reinterpret genuine stored graph bytes merely because their property order differs from RFC 8785. + The initial generation-free path may use explicitly authored empty optional families only when that complete World owner input and committed readback prove them; missing rows alone do not prove emptiness. Present generation or spawn intent retains its existing preparation gates. This selector neither manufactures an actor nor changes `PRESEEDED_ONLY`: Entity's genuine owner-assigned actor and namespace-qualified ownership proof remain separate. Implementation, executed owner proof and activation limits belong to the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). ## Initial Admission Hold Contract 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 85bbc2dc22..35d4dc8c7a 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The three historical selection fixtures now seed coordinator/selection evidence under the real V43/V44/V45 guards, verify each intended migration at its original boundary, and only then upgrade before calling the current writer. Complete retained coordinator and selection rows are compared across the latest upgrade, with no synthesized Account terminal journal. The corrected Game Design check and boot JAR pass in the combined five-module gate; all 154 Game Design integration definitions skip locally without Docker, so corrected PostgreSQL execution is still required. The [World tracker](./world-runtime-and-movement.md#current-status) records the complete declaration/start-selector component; its authenticated publication read and immutable Game Design release/attestation carrier remain open. No release, creator authorization or activation is claimed. +Exact source `dadb6a813107fde95c73244a874fec2d13fc27f4` [CI37466228981](https://github.com/benhook1013/FireMUD/actions/runs/37466228981) executed nine selection/history PostgreSQL cases: six passed and three failed, with zero skips. Two complete retained coordinator snapshots used plain JDBC map equality despite binary-array values; the third pre-V48 conflict fixture still called the current terminal-journal-dependent writer. The bounded correction preserves all historical columns and original bytes through recursive comparison and uses the existing valid historical journal seeding rather than inventing an Account terminal result. All seven Account-bound terminal and both synchronized-visibility cases passed without skips at that source; the runner's exact base/head parents and head-identical tree were verified. Corrected migration-history execution remains required. The [World tracker](./world-runtime-and-movement.md#current-status) records the original-input start-selector and protected read components. The complete authenticated selector-to-immutable-release/attestation/preparation carrier remains work in progress, not actual publication, creator currentness or activation. Local Docker absence still prevents PostgreSQL execution. At exact published source `d87f9cc2d30e775ea1e0c31f98ddfc64ec28c5ec`, [CI37458361299](https://github.com/benhook1013/FireMUD/actions/runs/37458361299) executes all seven Game Design Account-bound terminal PostgreSQL cases cleanly with zero skips, closing the unresolved service-schema placeholder fixture failure. The wider Game Design job remains red: three older V43/V44/V45 selection-history fixtures invoke the current coordinator against a pre-V48 schema without its terminal journal. Their correction must preserve the actual historical migration boundaries and immutable retained rows rather than weakening production guards or fabricating that journal early. Terminal component execution does not authenticate creator permission, produce the actual release or establish live cross-owner settlement. Corrected migration-history execution remains required. 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 b3e0d087ef..6d282cc6c0 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status -The start-selector correction adds V40's exact immutable release-to-frozen-graph join and V41's original Account-digest-bound complete fresh-graph declaration. All six ordered counts are explicit, including zero; the typed ROOM selector is checked against actual same-Version rows and retained atomically with the graph and APPLIED-v2 result. Shared terminal readback verifies the complete declaration, original operation, graph and canonical receipt; retained declaration-less APPLIED-v1 history remains exact and receives no selector backfill. The corrected combined five-module gate and three service boot JARs pass in 1m05s (164 tasks: 28 executed, 136 up-to-date), with 2,457 clean unit executions across Core, Security, Account, Game Design and World. One Game Design object-store unit case and all 796 integration cases skip locally; the seventeen graph and twelve association PostgreSQL definitions have not executed on this corrected candidate. Formatting, analyzers, schema generation, links, Markdown and Flyway sanity pass. The authenticated Game Design selector read, immutable release/attestation carrier and preparation selector readback remain to be implemented; protected Account currentness, actual release and ACTIVE handoff remain open. This is component proof, not an enabled writer or completed Gameplay dependency. +V40 joins the exact immutable release and frozen graph; V41 retains the original Account-digest-bound complete six-family declaration, typed ROOM selector and APPLIED-v2 result atomically. Declaration-less APPLIED-v1 history stays exact and receives no selector backfill. Exact source `dadb6a813107fde95c73244a874fec2d13fc27f4` [CI37466228981](https://github.com/benhook1013/FireMUD/actions/runs/37466228981) executed seventeen graph PostgreSQL cases: fifteen passed and two failed, with zero skips. The receiver rejected genuine original owner graph bytes because the consumer imposed an incompatible RFC 8785 ordering constraint; the extra-family test correctly denied the write but expected a different diagnostic. Twelve association, seven terminal, two synchronized selector and fourteen frozen-topology cases passed without skips. The tested runner has exact base/head parents and a head-identical source tree. Corrected-source execution remains required. The shared closed receipt representation and dedicated, unregistered Game Design selector-read candidate retain the original Account/APPLIED bytes and independently join the actual frozen checkpoint; they do not authenticate current creator authority or establish a completed release, `PREPARING`, ACTIVE or admission. Immutable Game Design release delivery and preparation-selector proof remain open. Local integration tests skip without Docker; transport doubles and injected peer contexts are not live workload proof. Exact published source `d87f9cc2d30e775ea1e0c31f98ddfc64ec28c5ec` [CI37458361299](https://github.com/benhook1013/FireMUD/actions/runs/37458361299) executes 35 scoped World PostgreSQL cases cleanly with zero skips: twelve original Account-bound graph applications, seven terminal outcomes, two synchronized reads and fourteen frozen-topology cases. Runner merge `4330dec5c6b55287821d602be1d964919e265e1f` has exact base/source parents and source-identical tree `15b546e3b96e63f9eb282fe8301f62e5a62a1a80`. This closes the retained-column fixture failures at that source, not protected creator/currentness or live application, release and ACTIVE delivery. The subsequently prepared exact release/frozen-graph join and original-input-bound start selector need their own corrected-source proof; this historical execution does not validate them. Their synthetic authorization fixtures do not complete any of Gameplay's four live owner handoffs. diff --git a/protos/game-design/v1/game_design_service.proto b/protos/game-design/v1/game_design_service.proto index e697d505d6..5999195ee3 100644 --- a/protos/game-design/v1/game_design_service.proto +++ b/protos/game-design/v1/game_design_service.proto @@ -657,6 +657,8 @@ message AuthoredWorldReleaseAttestationEvidence { repeated string command_definitions = 19; string generation_config_revision = 20; string evidence_digest = 21; + // Closed original World Account/APPLIED/receipt evidence. Absent in schema 1, required in 2. + optional bytes world_start_location_evidence = 22; } message TemplateRemapSet { diff --git a/protos/world-management/v1/world_published_start_location_read.proto b/protos/world-management/v1/world_published_start_location_read.proto new file mode 100644 index 0000000000..571992c5f2 --- /dev/null +++ b/protos/world-management/v1/world_published_start_location_read.proto @@ -0,0 +1,60 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Opt-in authenticated readback of the selector in an exact frozen World publication capture. +service WorldPublishedStartLocationReadService { + rpc ReadWorldPublishedStartLocation(ReadWorldPublishedStartLocationRequest) + returns (ReadWorldPublishedStartLocationResponse); +} + +message WorldPublishedStartLocationAffectedTuple { + string owner = 1; + string aggregate_type = 2; + string aggregate_id = 3; + string scope_type = 4; + string scope_id = 5; + string expected_epoch = 6; +} + +message ReadWorldPublishedStartLocationRequest { + int32 schema_version = 1; + string target_namespace = 2; + string canonical_tenant_id = 3; + string canonical_version_id = 4; + string intake_request_id = 5; + string publication_fence = 6; + string publication_request_id = 7; + string request_digest = 8; + int64 version_state_epoch = 9; + string publish_workflow_id = 10; + string applied_commit_id = 11; + string content_digest = 12; + int32 digest_schema_version = 13; + repeated WorldPublishedStartLocationAffectedTuple world_affected_tuples = 14; +} + +message ReadWorldPublishedStartLocationResponse { + // Exact echo of the complete immutable frozen selection request. + int32 schema_version = 1; + string target_namespace = 2; + string canonical_tenant_id = 3; + string canonical_version_id = 4; + string intake_request_id = 5; + string publication_fence = 6; + string publication_request_id = 7; + string request_digest = 8; + int64 version_state_epoch = 9; + string publish_workflow_id = 10; + string applied_commit_id = 11; + string content_digest = 12; + int32 digest_schema_version = 13; + repeated WorldPublishedStartLocationAffectedTuple world_affected_tuples = 14; + // Exact original World receipt, Account binding, and APPLIED result bytes. + bytes selector_receipt_bytes = 15; + bytes original_account_binding_bytes = 16; + bytes applied_result_bytes = 17; +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyPostgresIntegrationTest.java index f4468ef865..bbd9c15495 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyPostgresIntegrationTest.java @@ -71,7 +71,10 @@ void migrationPreservesExistingAccountAndMembershipAndEnrollsNoParty() throws Ex .intoMap(); db.dsl() .execute( - "INSERT INTO account_tenant_membership (account_id, tenant_id, gameplay_admission_allowed) VALUES (?, 42, FALSE)", + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, 42, FALSE, 'LEGACY_UNVERIFIED', 1, 1, 'LEGACY_UNVERIFIED')", accountKey); Map before = Objects.requireNonNull( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java index cbb8ff5633..a826e79d17 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java @@ -20,6 +20,7 @@ import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; import net.firedevops.firemud.worldmanagement.v1.ReadWorldDraftTerminalOutcomeRequest; import net.firedevops.firemud.worldmanagement.v1.ReadWorldDraftTerminalOutcomeResponse; import net.firedevops.firemud.worldmanagement.v1.WorldDraftTerminalReadStatus; @@ -31,7 +32,6 @@ public final class WorldDraftTerminalReadGrpcCodec { private static final UUID NIL_UUID = new UUID(0L, 0L); private static final String APPLIED_V1 = "world-draft-graph-applied/v1"; private static final String APPLIED_V2 = "world-draft-graph-applied/v2"; - private static final String START_LOCATION_RECEIPT_V1 = "world-draft-start-location-receipt/v1"; private static final java.util.List FRESH_GRAPH_FAMILIES = java.util.List.of( "WORLD_DESIGN_AGGREGATE_TYPE_REGION", @@ -306,6 +306,13 @@ static void requireCommittedResult( operation.expectBytes(request.originalAccountBinding()); operation.requireEnd(); byte[] graph = base64(result, "graphBytesBase64"); + if (v2) { + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(graph)); + } String graphDigest = sha256(graph); exactText(result, "graphDigest", graphDigest); JsonNode graphValue = JSON.readTree(graph); @@ -314,18 +321,6 @@ static void requireCommittedResult( exactText(graphValue, "schemaVersion", "2"); exactText(graphValue, "canonicalTenantId", account.tenantId().toString()); exactText(graphValue, "canonicalVersionId", account.versionId().toString()); - if (v2) { - String graphJson = - StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) - .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) - .decode(ByteBuffer.wrap(graph)) - .toString(); - if (!Arrays.equals(graph, Rfc8785CanonicalJson.canonicalizeUtf8(graphJson))) { - throw new IllegalArgumentException("World v2 graph bytes are not canonical"); - } - } if (!graphValue.get("rows").isArray() || graphValue.get("rows").isEmpty()) throw new IllegalArgumentException("World applied graph is absent"); if (v2) { @@ -575,100 +570,24 @@ private static void validateStartLocationReceipt( WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft, DraftAuthorizationFenceBinding binding) - throws java.io.IOException, NoSuchAlgorithmException { - byte[] receiptBytes = base64(result, "startLocationReceiptBase64"); - String receiptJson = - StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) - .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) - .decode(ByteBuffer.wrap(receiptBytes)) - .toString(); - if (!Arrays.equals(receiptBytes, Rfc8785CanonicalJson.canonicalizeUtf8(receiptJson))) { - throw new IllegalArgumentException("World start-location receipt is not canonical"); - } - JsonNode receipt = JSON.readTree(receiptBytes); - fields( - receipt, - Set.of( - "schema", - "targetNamespace", - "operationId", - "requestId", - "commitId", - "authorizationFenceId", - "accountBindingDigest", - "bindingDigest", - "startLocation", - "graphDigest", - "receiptDigest")); - exactText(receipt, "schema", START_LOCATION_RECEIPT_V1); - exactText(receipt, "targetNamespace", request.targetNamespace()); - exactText(receipt, "operationId", binding.operationId().toString()); - exactText(receipt, "requestId", binding.requestId().toString()); - exactText(receipt, "commitId", binding.commitId().toString()); - exactText(receipt, "authorizationFenceId", binding.fenceId().toString()); - exactText(receipt, "accountBindingDigest", sha256(request.originalAccountBinding())); - exactText(receipt, "bindingDigest", draft.digest()); - exactText(receipt, "graphDigest", graphDigest); - JsonNode selector = receipt.get("startLocation"); - fields(selector, ROOM_TEMPLATE_REF_FIELDS); - exactText(selector, "tenantId", original.tenantId().toString()); - exactText(selector, "versionId", original.versionId().toString()); - exactText(selector, "roomTemplateId", original.roomTemplateId().toString()); - String receiptDigest = text(receipt, "receiptDigest"); - exactText(result, "startLocationReceiptDigest", receiptDigest); - String expectedReceiptDigest = - startLocationReceiptDigest( - request.targetNamespace(), - binding.operationId(), - binding.requestId(), - binding.commitId(), - binding.fenceId(), - sha256(request.originalAccountBinding()), - draft.digest(), - original.tenantId(), - original.versionId(), - original.roomTemplateId(), - graphDigest); - if (!expectedReceiptDigest.equals(receiptDigest)) { - throw new IllegalArgumentException("World start-location receipt digest is invalid"); - } - } - - private static String startLocationReceiptDigest( - String targetNamespace, - UUID operationId, - UUID requestId, - UUID commitId, - UUID fenceId, - String accountBindingDigest, - String bindingDigest, - UUID tenantId, - UUID versionId, - UUID roomTemplateId, - String graphDigest) throws NoSuchAlgorithmException { - java.io.ByteArrayOutputStream framed = new java.io.ByteArrayOutputStream(); - for (String value : - java.util.List.of( - START_LOCATION_RECEIPT_V1, - targetNamespace, - operationId.toString(), - requestId.toString(), - commitId.toString(), - fenceId.toString(), - accountBindingDigest, - bindingDigest, - tenantId.toString(), - versionId.toString(), - roomTemplateId.toString(), - graphDigest)) { - byte[] bytes = value.getBytes(StandardCharsets.UTF_8); - framed.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); - framed.writeBytes(bytes); - } - return sha256(framed.toByteArray()); + var receipt = + WorldDraftStartLocationEvidence.fromStored(base64(result, "startLocationReceiptBase64")); + if (!receipt.targetNamespace().equals(request.targetNamespace()) + || !receipt.operationId().equals(binding.operationId()) + || !receipt.requestId().equals(binding.requestId()) + || !receipt.commitId().equals(binding.commitId()) + || !receipt.authorizationFenceId().equals(binding.fenceId()) + || !receipt.accountBindingDigest().equals(sha256(request.originalAccountBinding())) + || !receipt.bindingDigest().equals(draft.digest()) + || !receipt.startLocation().tenantId().equals(original.tenantId()) + || !receipt.startLocation().versionId().equals(original.versionId()) + || !receipt.startLocation().roomTemplateId().equals(original.roomTemplateId()) + || !receipt.graphDigest().equals(graphDigest)) { + throw new IllegalArgumentException( + "World start-location receipt differs from its original Account-bound graph"); + } + exactText(result, "startLocationReceiptDigest", receipt.receiptDigest()); } private static long positiveLong(JsonNode value, String field) { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java index d41a9903ef..0aa9346ac9 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java @@ -1,10 +1,12 @@ package net.firedevops.firemud.common.gamedesign; +import com.google.protobuf.ByteString; import com.google.protobuf.Message; import java.util.List; import java.util.Objects; import java.util.UUID; import java.util.regex.Pattern; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.v1.GetCompleteLaunchBindingResponse; import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; @@ -203,6 +205,10 @@ public static CompleteLaunchBindingEvidence fromCompleteResponse( .addAllCommandDefinitions(evidence.commandDefinitions()) .setGenerationConfigRevision(evidence.generationConfigRevision()) .setEvidenceDigest(evidence.evidenceDigest()); + if (evidence.worldStartLocationEvidence() != null) { + builder.setWorldStartLocationEvidence( + ByteString.copyFrom(evidence.worldStartLocationEvidence().canonicalBytes())); + } for (AuthoredWorldReleaseAttestationEvidence.Participant participant : evidence.participantDigests()) { ParticipantDigest.Builder participantBuilder = @@ -386,7 +392,11 @@ private static AuthoredWorldReleaseAttestationEvidence decodeReleaseAttestation( artifacts, wire.getCommandDefinitionsList(), wire.getGenerationConfigRevision(), - wire.getEvidenceDigest()); + wire.getEvidenceDigest(), + wire.hasWorldStartLocationEvidence() + ? WorldPublishedStartLocationEvidence.fromStored( + wire.getWorldStartLocationEvidence().toByteArray()) + : null); } catch (IllegalArgumentException exception) { throw new IllegalArgumentException("Release-attestation evidence is invalid", exception); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java index ea1129826a..b58a5b34d1 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.common.gamedesign; +import com.fasterxml.jackson.annotation.JsonInclude; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.nio.CharBuffer; @@ -9,6 +10,7 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; +import java.util.Base64; import java.util.Comparator; import java.util.HexFormat; import java.util.List; @@ -18,6 +20,7 @@ import java.util.regex.Pattern; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; /** Closed immutable full release-attestation evidence for an authored-world launch. */ public record AuthoredWorldReleaseAttestationEvidence( @@ -41,9 +44,14 @@ public record AuthoredWorldReleaseAttestationEvidence( List artifactDigests, List commandDefinitions, String generationConfigRevision, - String evidenceDigest) { + String evidenceDigest, + @JsonInclude(JsonInclude.Include.NON_NULL) + WorldPublishedStartLocationEvidence worldStartLocationEvidence) { public static final int SCHEMA_VERSION = 1; + public static final int SELECTOR_SCHEMA_VERSION = 2; private static final String EVIDENCE_DOMAIN = "game-design-authored-world-release-attestation/v1"; + private static final String SELECTOR_EVIDENCE_DOMAIN = + "game-design-authored-world-release-attestation/v2"; private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); private static final Pattern PARTICIPANT_CONTENT_DIGEST = Pattern.compile("[0-9a-f]{64}"); private static final Pattern CANONICAL_POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); @@ -135,7 +143,7 @@ public record Artifact( } public AuthoredWorldReleaseAttestationEvidence { - if (schemaVersion != SCHEMA_VERSION) { + if (schemaVersion != SCHEMA_VERSION && schemaVersion != SELECTOR_SCHEMA_VERSION) { throw new IllegalArgumentException("Unsupported authored-world release-attestation schema"); } Objects.requireNonNull(targetNamespace, "targetNamespace"); @@ -172,6 +180,145 @@ public record Artifact( } requireText(generationConfigRevision, "generationConfigRevision"); requireDigest(evidenceDigest, "evidenceDigest"); + if ((schemaVersion == SELECTOR_SCHEMA_VERSION) != (worldStartLocationEvidence != null)) { + throw new IllegalArgumentException( + "Only release-attestation/v2 requires World selector evidence"); + } + if (worldStartLocationEvidence != null) { + WorldPublishedStartLocationEvidence.fromStored(worldStartLocationEvidence.canonicalBytes()); + var selected = worldStartLocationEvidence.request(); + var world = participantDigests.getFirst(); + if (!targetNamespace.equals(selected.targetNamespace()) + || !canonicalTenantId.equals(selected.canonicalTenantId()) + || !canonicalVersionId.equals(selected.canonicalVersionId()) + || !publishWorkflowId.equals(selected.publishWorkflowId()) + || !commitId.equals(selected.appliedCommitId()) + || !world.contentDigest().equals(selected.contentDigest()) + || world.digestSchemaVersion() != selected.digestSchemaVersion()) { + throw new IllegalArgumentException( + "World selector differs from the exact attested release checkpoint"); + } + } + } + + /** Original v1 constructor: retained bytes never gain a selector. */ + public AuthoredWorldReleaseAttestationEvidence( + int schemaVersion, + String targetNamespace, + String descriptorResultDigest, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + String launchDescriptorId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String publishWorkflowId, + String commitId, + List participantDigests, + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests, + List commandDefinitions, + String generationConfigRevision, + String evidenceDigest) { + this( + schemaVersion, + targetNamespace, + descriptorResultDigest, + canonicalTenantId, + canonicalVersionId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + launchDescriptorId, + publishedReleaseBundleRef, + versionStateEpoch, + publishWorkflowId, + commitId, + participantDigests, + manifestHash, + manifestSchemaVersion, + requiredManifestAssetKeys, + artifactDigests, + commandDefinitions, + generationConfigRevision, + evidenceDigest, + null); + } + + /** Creates v2 from the exact unchanged World evidence retained in the immutable release. */ + public static AuthoredWorldReleaseAttestationEvidence create( + String targetNamespace, + String descriptorResultDigest, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + String launchDescriptorId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String publishWorkflowId, + String commitId, + List participantDigests, + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests, + List commandDefinitions, + String generationConfigRevision, + WorldPublishedStartLocationEvidence worldStartLocationEvidence) { + Objects.requireNonNull(worldStartLocationEvidence, "worldStartLocationEvidence"); + var provisional = + new AuthoredWorldReleaseAttestationEvidence( + SELECTOR_SCHEMA_VERSION, + targetNamespace, + descriptorResultDigest, + canonicalTenantId, + canonicalVersionId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + launchDescriptorId, + publishedReleaseBundleRef, + versionStateEpoch, + publishWorkflowId, + commitId, + participantDigests, + manifestHash, + manifestSchemaVersion, + requiredManifestAssetKeys, + artifactDigests, + commandDefinitions, + generationConfigRevision, + "sha256:" + "0".repeat(64), + worldStartLocationEvidence); + return new AuthoredWorldReleaseAttestationEvidence( + SELECTOR_SCHEMA_VERSION, + targetNamespace, + descriptorResultDigest, + canonicalTenantId, + canonicalVersionId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + launchDescriptorId, + publishedReleaseBundleRef, + versionStateEpoch, + publishWorkflowId, + commitId, + participantDigests, + manifestHash, + manifestSchemaVersion, + requiredManifestAssetKeys, + artifactDigests, + commandDefinitions, + generationConfigRevision, + computeEvidenceDigest(provisional), + worldStartLocationEvidence); } /** Creates evidence from the complete owner attestation and derives its evidence digest. */ @@ -280,7 +427,7 @@ public void requireValid(AuthoredWorldLaunchDescriptorEvidence descriptor) { } } - /** Computes the digest using the fixed v1 domain and exhaustive field order. */ + /** Computes the digest using the schema-specific domain and exhaustive field order. */ public static String computeEvidenceDigest(AuthoredWorldReleaseAttestationEvidence evidence) { Objects.requireNonNull(evidence, "evidence"); return "sha256:" + HexFormat.of().formatHex(sha256(evidencePreimage(evidence))); @@ -367,7 +514,16 @@ public static byte[] evidencePreimage(AuthoredWorldReleaseAttestationEvidence ev field("commandDefinitions[" + index + "]", evidence.commandDefinitions().get(index))); } fields.add(field("generationConfigRevision", evidence.generationConfigRevision())); - return preimage(EVIDENCE_DOMAIN, fields.toArray(Field[]::new)); + if (evidence.schemaVersion() == SELECTOR_SCHEMA_VERSION) { + fields.add( + field( + "worldStartLocationEvidence.canonicalBytesBase64", + Base64.getEncoder() + .encodeToString(evidence.worldStartLocationEvidence().canonicalBytes()))); + } + return preimage( + evidence.schemaVersion() == SCHEMA_VERSION ? EVIDENCE_DOMAIN : SELECTOR_EVIDENCE_DOMAIN, + fields.toArray(Field[]::new)); } private static void validateParticipants(List participants, String commitId) { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidence.java new file mode 100644 index 0000000000..d3f440a6b6 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidence.java @@ -0,0 +1,286 @@ +package net.firedevops.firemud.common.world; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** Closed, canonical World evidence for the original authored start-location selector. */ +public record WorldDraftStartLocationEvidence( + String targetNamespace, + UUID operationId, + UUID requestId, + UUID commitId, + UUID authorizationFenceId, + String accountBindingDigest, + String bindingDigest, + RoomTemplateRef startLocation, + String graphDigest, + String receiptDigest) { + public static final String SCHEMA = "world-draft-start-location-receipt/v1"; + + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Set FIELDS = + Set.of( + "schema", + "targetNamespace", + "operationId", + "requestId", + "commitId", + "authorizationFenceId", + "accountBindingDigest", + "bindingDigest", + "startLocation", + "graphDigest", + "receiptDigest"); + private static final Set ROOM_TEMPLATE_REF_FIELDS = + Set.of("tenantId", "versionId", "roomTemplateId"); + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + public WorldDraftStartLocationEvidence { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + requireCanonicalNonNilUuid(operationId, "operationId"); + requireCanonicalNonNilUuid(requestId, "requestId"); + requireCanonicalNonNilUuid(commitId, "commitId"); + requireCanonicalNonNilUuid(authorizationFenceId, "authorizationFenceId"); + requireDigest(accountBindingDigest, "accountBindingDigest"); + requireDigest(bindingDigest, "bindingDigest"); + Objects.requireNonNull(startLocation, "startLocation"); + requireDigest(graphDigest, "graphDigest"); + requireDigest(receiptDigest, "receiptDigest"); + if (!receiptDigest.equals( + computeReceiptDigest( + targetNamespace, + operationId, + requestId, + commitId, + authorizationFenceId, + accountBindingDigest, + bindingDigest, + startLocation, + graphDigest))) { + throw new IllegalArgumentException("World start-location receipt digest is invalid"); + } + } + + /** Creates the one canonical representation from the complete original receipt fields. */ + public static WorldDraftStartLocationEvidence create( + String targetNamespace, + UUID operationId, + UUID requestId, + UUID commitId, + UUID authorizationFenceId, + String accountBindingDigest, + String bindingDigest, + RoomTemplateRef startLocation, + String graphDigest) { + return new WorldDraftStartLocationEvidence( + targetNamespace, + operationId, + requestId, + commitId, + authorizationFenceId, + accountBindingDigest, + bindingDigest, + startLocation, + graphDigest, + computeReceiptDigest( + targetNamespace, + operationId, + requestId, + commitId, + authorizationFenceId, + accountBindingDigest, + bindingDigest, + startLocation, + graphDigest)); + } + + /** + * Decodes a complete canonical receipt and verifies its closed fields and digest. This does not + * authenticate the producer or prove the receipt's Account-bound meaning. + */ + public static WorldDraftStartLocationEvidence fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(stored)) + .toString(); + JsonNode value = JSON.readTree(json); + requireFields(value, FIELDS, "World start-location receipt"); + if (!SCHEMA.equals(text(value, "schema"))) { + throw new IllegalArgumentException("Unsupported World start-location receipt schema"); + } + JsonNode selector = value.get("startLocation"); + requireFields(selector, ROOM_TEMPLATE_REF_FIELDS, "World start-location selector"); + var evidence = + new WorldDraftStartLocationEvidence( + text(value, "targetNamespace"), + parseCanonicalNonNilUuid(text(value, "operationId"), "operationId"), + parseCanonicalNonNilUuid(text(value, "requestId"), "requestId"), + parseCanonicalNonNilUuid(text(value, "commitId"), "commitId"), + parseCanonicalNonNilUuid(text(value, "authorizationFenceId"), "authorizationFenceId"), + text(value, "accountBindingDigest"), + text(value, "bindingDigest"), + new RoomTemplateRef( + parseCanonicalNonNilUuid(text(selector, "tenantId"), "selector tenantId"), + parseCanonicalNonNilUuid(text(selector, "versionId"), "selector versionId"), + parseCanonicalNonNilUuid( + text(selector, "roomTemplateId"), "selector roomTemplateId")), + text(value, "graphDigest"), + text(value, "receiptDigest")); + if (!Arrays.equals(stored, evidence.canonicalBytes())) { + throw new IllegalArgumentException("World start-location receipt is not canonical"); + } + return evidence; + } catch (IOException | tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("World start-location receipt is invalid", invalid); + } + } + + /** Returns the exact canonical receipt bytes retained by World. */ + public byte[] canonicalBytes() { + Map selector = new LinkedHashMap<>(); + selector.put("tenantId", startLocation.tenantId().toString()); + selector.put("versionId", startLocation.versionId().toString()); + selector.put("roomTemplateId", startLocation.roomTemplateId().toString()); + Map json = new LinkedHashMap<>(); + json.put("schema", SCHEMA); + json.put("targetNamespace", targetNamespace); + json.put("operationId", operationId.toString()); + json.put("requestId", requestId.toString()); + json.put("commitId", commitId.toString()); + json.put("authorizationFenceId", authorizationFenceId.toString()); + json.put("accountBindingDigest", accountBindingDigest); + json.put("bindingDigest", bindingDigest); + json.put("startLocation", selector); + json.put("graphDigest", graphDigest); + json.put("receiptDigest", receiptDigest); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(json)); + } catch (IOException impossible) { + throw new IllegalStateException("World start-location receipt cannot be encoded", impossible); + } + } + + private static String computeReceiptDigest( + String namespace, + UUID operationId, + UUID requestId, + UUID commitId, + UUID fenceId, + String accountBindingDigest, + String bindingDigest, + RoomTemplateRef selector, + String graphDigest) { + Objects.requireNonNull(namespace, "targetNamespace"); + Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(commitId, "commitId"); + Objects.requireNonNull(fenceId, "authorizationFenceId"); + Objects.requireNonNull(accountBindingDigest, "accountBindingDigest"); + Objects.requireNonNull(bindingDigest, "bindingDigest"); + Objects.requireNonNull(selector, "startLocation"); + Objects.requireNonNull(graphDigest, "graphDigest"); + ByteArrayOutputStream framed = new ByteArrayOutputStream(); + for (String segment : + new String[] { + SCHEMA, + namespace, + operationId.toString(), + requestId.toString(), + commitId.toString(), + fenceId.toString(), + accountBindingDigest, + bindingDigest, + selector.tenantId().toString(), + selector.versionId().toString(), + selector.roomTemplateId().toString(), + graphDigest + }) { + byte[] bytes = segment.getBytes(StandardCharsets.UTF_8); + framed.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); + framed.writeBytes(bytes); + } + try { + return "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(framed.toByteArray())); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 unavailable", impossible); + } + } + + private static void requireCanonicalNonNilUuid(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical 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"); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID", invalid); + } + } + + private static void requireFields(JsonNode value, Set expected, String label) { + if (value == null || !value.isObject()) { + throw new IllegalArgumentException(label + " must be an object"); + } + if (value.size() != expected.size() + || value.properties().stream().anyMatch(entry -> !expected.contains(entry.getKey()))) { + throw new IllegalArgumentException(label + " has missing or unsupported fields"); + } + } + + private static String text(JsonNode value, String field) { + JsonNode child = value.get(field); + if (child == null || !child.isTextual()) { + throw new IllegalArgumentException( + "World start-location receipt field " + field + " is invalid"); + } + return child.textValue(); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationClient.java new file mode 100644 index 0000000000..63565442a3 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationClient.java @@ -0,0 +1,151 @@ +package net.firedevops.firemud.common.world; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedStartLocationReadServiceGrpc; + +/** Explicit mTLS client for the exact World frozen-selection selector readback. */ +public final class WorldPublishedStartLocationClient + extends AbstractReloadingBlockingGrpcClient< + WorldPublishedStartLocationReadServiceGrpc + .WorldPublishedStartLocationReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldPublishedStartLocationClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + WorldPublishedStartLocationClient.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 selector read client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("World selector read client has no gRPC stub"); + } + initialized = true; + } + + /** Reads immutable selector evidence for this complete frozen selection. */ + public WorldPublishedStartLocationEvidence read( + WorldPublishedStartLocationEvidence.Request request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "World selector read request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readWorldPublishedStartLocation( + WorldPublishedStartLocationGrpcCodec.toRequest(request)); + try { + return WorldPublishedStartLocationGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid published selector evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldPublishedStartLocationReadServiceGrpc + .WorldPublishedStartLocationReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldPublishedStartLocationReadServiceGrpc.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 WorldPublishedStartLocationReadServiceGrpc + .WorldPublishedStartLocationReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "World selector read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("World selector read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "World selector read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World selector read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "World selector read " + label + " must be a readable file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World selector read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java new file mode 100644 index 0000000000..2db322fe14 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java @@ -0,0 +1,556 @@ +package net.firedevops.firemud.common.world; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** + * Exact World selector readback for an immutable frozen publication selection. + * + *

This evidence does not establish current Account permission, complete release evidence, + * activation, or admission. Decoding and relation checks do not authenticate the producer. The + * explicit mTLS client is responsible for authenticating World before accepting it. + */ +public record WorldPublishedStartLocationEvidence( + Request request, + byte[] selectorReceiptBytes, + byte[] originalAccountBindingBytes, + byte[] appliedResultBytes) { + public static final String SCHEMA = "world-published-start-location-evidence/v1"; + private static final int APPLIED_INTAKE_REQUEST_ID_FRAME = 13; + + private static final Set EVIDENCE_FIELDS = + Set.of( + "schema", + "request", + "selectorReceiptBytesBase64", + "originalAccountBindingBytesBase64", + "appliedResultBytesBase64"); + private static final Set REQUEST_FIELDS = + Set.of( + "targetNamespace", + "canonicalTenantId", + "canonicalVersionId", + "intakeRequestId", + "publicationFence", + "publicationRequestId", + "requestDigest", + "versionStateEpoch", + "publishWorkflowId", + "appliedCommitId", + "contentDigest", + "digestSchemaVersion", + "worldAffectedTuples"); + private static final Set TUPLE_FIELDS = + Set.of("owner", "aggregateType", "aggregateId", "scopeType", "scopeId", "expectedEpoch"); + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + public WorldPublishedStartLocationEvidence { + Objects.requireNonNull(request, "request"); + selectorReceiptBytes = bytes(selectorReceiptBytes, "selectorReceiptBytes"); + originalAccountBindingBytes = bytes(originalAccountBindingBytes, "originalAccountBindingBytes"); + appliedResultBytes = bytes(appliedResultBytes, "appliedResultBytes"); + requireRelation(request, selectorReceiptBytes, originalAccountBindingBytes, appliedResultBytes); + } + + @Override + public byte[] selectorReceiptBytes() { + return selectorReceiptBytes.clone(); + } + + @Override + public byte[] originalAccountBindingBytes() { + return originalAccountBindingBytes.clone(); + } + + @Override + public byte[] appliedResultBytes() { + return appliedResultBytes.clone(); + } + + @Override + public boolean equals(Object other) { + if (this == other) return true; + if (!(other instanceof WorldPublishedStartLocationEvidence that)) return false; + return request.equals(that.request) + && Arrays.equals(selectorReceiptBytes, that.selectorReceiptBytes) + && Arrays.equals(originalAccountBindingBytes, that.originalAccountBindingBytes) + && Arrays.equals(appliedResultBytes, that.appliedResultBytes); + } + + @Override + public int hashCode() { + int result = Objects.hash(request); + result = 31 * result + Arrays.hashCode(selectorReceiptBytes); + result = 31 * result + Arrays.hashCode(originalAccountBindingBytes); + result = 31 * result + Arrays.hashCode(appliedResultBytes); + return result; + } + + /** Canonical, closed durable representation; this encoding does not authenticate World. */ + public byte[] canonicalBytes() { + Map value = new LinkedHashMap<>(); + value.put("schema", SCHEMA); + value.put("request", requestJson(request)); + value.put( + "selectorReceiptBytesBase64", Base64.getEncoder().encodeToString(selectorReceiptBytes)); + value.put( + "originalAccountBindingBytesBase64", + Base64.getEncoder().encodeToString(originalAccountBindingBytes)); + value.put("appliedResultBytesBase64", Base64.getEncoder().encodeToString(appliedResultBytes)); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException( + "World published selector evidence cannot be encoded", impossible); + } + } + + /** + * Decodes and validates retained bytes, but does not establish authenticated producer provenance. + */ + public static WorldPublishedStartLocationEvidence fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + JsonNode root = JSON.readTree(stored); + requireFields(root, EVIDENCE_FIELDS, "published World selector evidence"); + if (!SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException("Unsupported published World selector evidence schema"); + } + var evidence = + new WorldPublishedStartLocationEvidence( + parseRequest(root.get("request")), + base64(root, "selectorReceiptBytesBase64"), + base64(root, "originalAccountBindingBytesBase64"), + base64(root, "appliedResultBytesBase64")); + if (!Arrays.equals(stored, evidence.canonicalBytes())) { + throw new IllegalArgumentException("Published World selector evidence is not canonical"); + } + return evidence; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("Published World selector evidence is invalid", invalid); + } + } + + private static void requireRelation( + Request request, byte[] receiptBytes, byte[] accountBytes, byte[] appliedBytes) { + var account = DraftAuthorizationFenceBinding.fromStored(accountBytes); + if (!request.canonicalTenantId().equals(account.tenantId()) + || !request.canonicalVersionId().equals(account.versionId()) + || !request.appliedCommitId().equals(account.commitId().toString())) { + throw new IllegalArgumentException( + "Published World selection differs from original Account binding"); + } + + DraftCommitBinding draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + if (!Arrays.equals(draft.canonicalBytes(), account.normalizedInput()) + || !draft.requestId().equals(account.requestId()) + || !draft.commitId().equals(account.commitId()) + || !draft.target().canonicalTenantId().equals(request.canonicalTenantId()) + || !draft.target().canonicalVersionId().equals(request.canonicalVersionId())) { + throw new IllegalArgumentException( + "Published World selection differs from original Draft binding"); + } + List boundTuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .sorted( + Comparator.comparing(OwnedAffectedTuple::owner) + .thenComparing(OwnedAffectedTuple::aggregateType) + .thenComparing(OwnedAffectedTuple::aggregateId) + .thenComparing(OwnedAffectedTuple::scopeType) + .thenComparing(OwnedAffectedTuple::scopeId) + .thenComparing(OwnedAffectedTuple::expectedEpoch)) + .toList(); + if (!request.worldAffectedTuples().equals(boundTuples)) { + throw new IllegalArgumentException( + "Published World selection changed the complete World affected set"); + } + + var terminalRequest = + WorldDraftTerminalReadEvidence.Request.create(request.targetNamespace(), accountBytes); + var terminalReadback = + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + account.operationId(), + account.commitId(), + account.fenceId(), + account.inputDigest(), + accountBytes, + appliedBytes); + var terminalResponse = + WorldDraftTerminalReadGrpcCodec.toResponse( + terminalRequest, java.util.Optional.of(terminalReadback)); + WorldDraftTerminalReadGrpcCodec.fromResponse(terminalRequest, terminalResponse); + + JsonNode applied = readApplied(appliedBytes); + if (!"APPLIED".equals(text(applied, "status"))) { + throw new IllegalArgumentException( + "Published World selector requires the original APPLIED result"); + } + if (!request.intakeRequestId().equals(appliedIntakeRequestId(applied))) { + throw new IllegalArgumentException( + "Published World selection differs from the original APPLIED intake request"); + } + byte[] resultReceipt = base64(applied, "startLocationReceiptBase64"); + if (!Arrays.equals(receiptBytes, resultReceipt)) { + throw new IllegalArgumentException( + "Published World selector differs from original APPLIED receipt"); + } + WorldDraftStartLocationEvidence receipt = + WorldDraftStartLocationEvidence.fromStored(receiptBytes); + if (!receipt.targetNamespace().equals(request.targetNamespace()) + || !receipt.operationId().equals(account.operationId()) + || !receipt.requestId().equals(account.requestId()) + || !receipt.commitId().equals(account.commitId()) + || !receipt.authorizationFenceId().equals(account.fenceId()) + || !receipt.accountBindingDigest().equals(prefixedSha256(accountBytes)) + || !receipt.bindingDigest().equals(draft.digest()) + || !receipt.startLocation().tenantId().equals(request.canonicalTenantId()) + || !receipt.startLocation().versionId().equals(request.canonicalVersionId()) + || !receipt.graphDigest().equals(text(applied, "graphDigest"))) { + throw new IllegalArgumentException( + "Published World selector receipt differs from selected APPLIED commit"); + } + } + + private static JsonNode readApplied(byte[] bytes) { + try { + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(bytes)) + .toString(); + return JSON.readTree(json); + } catch (IOException | tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("World APPLIED result is invalid", invalid); + } + } + + /** Reads the immutable intake identity from the exact operation frame already codec-validated. */ + private static UUID appliedIntakeRequestId(JsonNode applied) { + ByteBuffer operation = ByteBuffer.wrap(base64(applied, "operationBytesBase64")); + String intakeRequestId = null; + for (int frameIndex = 0; frameIndex <= APPLIED_INTAKE_REQUEST_ID_FRAME; frameIndex++) { + if (operation.remaining() < Integer.BYTES) { + throw new IllegalArgumentException("World APPLIED operation frame is truncated"); + } + int frameLength = operation.getInt(); + if (frameLength < 0 || frameLength > operation.remaining()) { + throw new IllegalArgumentException("World APPLIED operation frame has an invalid length"); + } + byte[] frame = new byte[frameLength]; + operation.get(frame); + if (frameIndex == 0 + && !"world-draft-terminal-operation/v1" + .equals(new String(frame, StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("Unsupported World APPLIED operation frame schema"); + } + if (frameIndex == APPLIED_INTAKE_REQUEST_ID_FRAME) { + try { + intakeRequestId = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(frame)) + .toString(); + } catch (java.nio.charset.CharacterCodingException invalid) { + throw new IllegalArgumentException( + "World APPLIED intake request frame is invalid", invalid); + } + } + } + return parseUuid(intakeRequestId, "APPLIED intakeRequestId"); + } + + private static String prefixedSha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 unavailable", impossible); + } + } + + private static Request parseRequest(JsonNode node) { + requireFields(node, REQUEST_FIELDS, "published World selector request"); + JsonNode tuples = node.get("worldAffectedTuples"); + if (tuples == null || !tuples.isArray()) { + throw new IllegalArgumentException("World affected tuple array is required"); + } + List affected = new ArrayList<>(); + for (JsonNode tuple : tuples) { + requireFields(tuple, TUPLE_FIELDS, "World affected tuple"); + affected.add( + new OwnedAffectedTuple( + text(tuple, "owner"), + text(tuple, "aggregateType"), + text(tuple, "aggregateId"), + text(tuple, "scopeType"), + text(tuple, "scopeId"), + text(tuple, "expectedEpoch"))); + } + Request decoded = + new Request( + text(node, "targetNamespace"), + parseUuid(text(node, "canonicalTenantId"), "canonicalTenantId"), + parseUuid(text(node, "canonicalVersionId"), "canonicalVersionId"), + parseUuid(text(node, "intakeRequestId"), "intakeRequestId"), + parseUuid(text(node, "publicationFence"), "publicationFence"), + text(node, "publicationRequestId"), + text(node, "requestDigest"), + positiveLong(text(node, "versionStateEpoch"), "versionStateEpoch"), + text(node, "publishWorkflowId"), + text(node, "appliedCommitId"), + text(node, "contentDigest"), + intValue(node, "digestSchemaVersion"), + affected); + if (!decoded.worldAffectedTuples().equals(affected)) { + throw new IllegalArgumentException("World affected tuples are not in canonical order"); + } + return decoded; + } + + private static Map requestJson(Request request) { + Map value = new LinkedHashMap<>(); + value.put("targetNamespace", request.targetNamespace()); + value.put("canonicalTenantId", request.canonicalTenantId().toString()); + value.put("canonicalVersionId", request.canonicalVersionId().toString()); + value.put("intakeRequestId", request.intakeRequestId().toString()); + value.put("publicationFence", request.publicationFence().toString()); + value.put("publicationRequestId", request.publicationRequestId()); + value.put("requestDigest", request.requestDigest()); + value.put("versionStateEpoch", Long.toString(request.versionStateEpoch())); + value.put("publishWorkflowId", request.publishWorkflowId()); + value.put("appliedCommitId", request.appliedCommitId()); + value.put("contentDigest", request.contentDigest()); + value.put("digestSchemaVersion", request.digestSchemaVersion()); + value.put( + "worldAffectedTuples", + request.worldAffectedTuples().stream() + .map( + tuple -> { + Map item = new LinkedHashMap<>(); + item.put("owner", tuple.owner()); + item.put("aggregateType", tuple.aggregateType()); + item.put("aggregateId", tuple.aggregateId()); + item.put("scopeType", tuple.scopeType()); + item.put("scopeId", tuple.scopeId()); + item.put("expectedEpoch", tuple.expectedEpoch()); + return item; + }) + .toList()); + return value; + } + + private static byte[] base64(JsonNode node, String field) { + try { + return Base64.getDecoder().decode(text(node, field)); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Invalid base64 field " + field, invalid); + } + } + + private static byte[] bytes(byte[] value, String name) { + if (value == null || value.length == 0) { + throw new IllegalArgumentException(name + " is required"); + } + return value.clone(); + } + + private static String text(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual() || value.textValue().isBlank()) { + throw new IllegalArgumentException(field + " is required"); + } + return value.textValue(); + } + + private static long positiveLong(String value, String field) { + if (value == null || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(field + " must be canonical positive decimal"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException(field + " exceeds the supported integer range", invalid); + } + } + + private static int intValue(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) { + throw new IllegalArgumentException(field + " must be an integer"); + } + return value.intValue(); + } + + private static UUID parseUuid(String value, String label) { + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(label + " must be a canonical UUID", invalid); + } + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } + + private static void requireFields(JsonNode object, Set fields, String label) { + if (object == null || !object.isObject()) { + throw new IllegalArgumentException(label + " must be an object"); + } + Set actual = new java.util.HashSet<>(); + object.propertyNames().forEach(actual::add); + if (!actual.equals(fields)) { + throw new IllegalArgumentException(label + " has missing or unsupported fields"); + } + } + + /** Exact transport-neutral immutable selection input. */ + public record Request( + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID intakeRequestId, + UUID publicationFence, + String publicationRequestId, + String requestDigest, + long versionStateEpoch, + String publishWorkflowId, + String appliedCommitId, + String contentDigest, + int digestSchemaVersion, + List worldAffectedTuples) { + public static final int SCHEMA_VERSION = 1; + + public Request { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical World workload namespace is required"); + } + requireUuid(canonicalTenantId, "canonicalTenantId"); + requireUuid(canonicalVersionId, "canonicalVersionId"); + requireUuid(intakeRequestId, "intakeRequestId"); + requireUuid(publicationFence, "publicationFence"); + requireText(publicationRequestId, "publicationRequestId"); + requireSha256(requestDigest, "requestDigest"); + if (versionStateEpoch <= 0) + throw new IllegalArgumentException("versionStateEpoch must be positive"); + requireText(publishWorkflowId, "publishWorkflowId"); + requireText(appliedCommitId, "appliedCommitId"); + requireSha256(contentDigest, "contentDigest"); + if (digestSchemaVersion != 2 && digestSchemaVersion != 3) { + throw new IllegalArgumentException("Unsupported World digest schema version"); + } + Objects.requireNonNull(worldAffectedTuples, "worldAffectedTuples"); + List ordered = new ArrayList<>(worldAffectedTuples); + ordered.sort( + Comparator.comparing(OwnedAffectedTuple::owner) + .thenComparing(OwnedAffectedTuple::aggregateType) + .thenComparing(OwnedAffectedTuple::aggregateId) + .thenComparing(OwnedAffectedTuple::scopeType) + .thenComparing(OwnedAffectedTuple::scopeId) + .thenComparing(OwnedAffectedTuple::expectedEpoch)); + if (ordered.stream().distinct().count() != ordered.size()) { + throw new IllegalArgumentException("duplicate World affected tuple"); + } + worldAffectedTuples = List.copyOf(ordered); + } + + private static void requireUuid(UUID value, String name) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static void requireText(String value, String name) { + if (value == null || value.isBlank()) + throw new IllegalArgumentException(name + " is required"); + } + + private static void requireSha256(String value, String name) { + if (value == null || !value.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be 64 lowercase hexadecimal digits"); + } + } + } + + public record OwnedAffectedTuple( + String owner, + String aggregateType, + String aggregateId, + String scopeType, + String scopeId, + String expectedEpoch) { + public OwnedAffectedTuple { + if (!"WORLD_MANAGEMENT".equals(owner)) { + throw new IllegalArgumentException("Published selector tuples must name WORLD_MANAGEMENT"); + } + requireTupleText(aggregateType, "aggregateType"); + requireTupleText(aggregateId, "aggregateId"); + Objects.requireNonNull(scopeType, "scopeType"); + Objects.requireNonNull(scopeId, "scopeId"); + if (scopeType.isEmpty() != scopeId.isEmpty()) { + throw new IllegalArgumentException("scopeType and scopeId must both be present or absent"); + } + if (expectedEpoch == null + || !expectedEpoch.matches("0|[1-9][0-9]*") + || new java.math.BigInteger(expectedEpoch) + .compareTo(java.math.BigInteger.valueOf(Long.MAX_VALUE)) + > 0) { + throw new IllegalArgumentException("expectedEpoch must be canonical non-negative decimal"); + } + } + + private static void requireTupleText(String value, String name) { + if (value == null || value.isBlank()) + throw new IllegalArgumentException(name + " is required"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodec.java new file mode 100644 index 0000000000..faaa5407b1 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodec.java @@ -0,0 +1,216 @@ +package net.firedevops.firemud.common.world; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Objects; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence.OwnedAffectedTuple; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence.Request; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedStartLocationAffectedTuple; + +/** Closed wire mapping and exact request-echo validation for the World selector read. */ +public final class WorldPublishedStartLocationGrpcCodec { + private WorldPublishedStartLocationGrpcCodec() {} + + public static ReadWorldPublishedStartLocationRequest toRequest(Request request) { + Objects.requireNonNull(request, "request"); + var builder = + ReadWorldPublishedStartLocationRequest.newBuilder() + .setSchemaVersion(Request.SCHEMA_VERSION) + .setTargetNamespace(request.targetNamespace()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setCanonicalVersionId(request.canonicalVersionId().toString()) + .setIntakeRequestId(request.intakeRequestId().toString()) + .setPublicationFence(request.publicationFence().toString()) + .setPublicationRequestId(request.publicationRequestId()) + .setRequestDigest(request.requestDigest()) + .setVersionStateEpoch(request.versionStateEpoch()) + .setPublishWorkflowId(request.publishWorkflowId()) + .setAppliedCommitId(request.appliedCommitId()) + .setContentDigest(request.contentDigest()) + .setDigestSchemaVersion(request.digestSchemaVersion()); + request.worldAffectedTuples().stream() + .map(WorldPublishedStartLocationGrpcCodec::toWireTuple) + .forEach(builder::addWorldAffectedTuples); + return builder.build(); + } + + /** + * Decodes only after the World receiver authenticates its exact same-namespace Game Design peer. + */ + public static Request fromRequest(ReadWorldPublishedStartLocationRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadWorldPublishedStartLocationRequest"); + if (request.getSchemaVersion() != Request.SCHEMA_VERSION) { + throw new IllegalArgumentException( + "Unsupported World published selector read schema version"); + } + return toEvidenceRequest( + request.getTargetNamespace(), + request.getCanonicalTenantId(), + request.getCanonicalVersionId(), + request.getIntakeRequestId(), + request.getPublicationFence(), + request.getPublicationRequestId(), + request.getRequestDigest(), + request.getVersionStateEpoch(), + request.getPublishWorkflowId(), + request.getAppliedCommitId(), + request.getContentDigest(), + request.getDigestSchemaVersion(), + request.getWorldAffectedTuplesList()); + } + + public static ReadWorldPublishedStartLocationResponse toResponse( + Request request, WorldPublishedStartLocationEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(evidence, "evidence"); + if (!request.equals(evidence.request())) { + throw new IllegalArgumentException( + "World selector evidence differs from exact selection request"); + } + var builder = + ReadWorldPublishedStartLocationResponse.newBuilder() + .setSchemaVersion(Request.SCHEMA_VERSION) + .setTargetNamespace(request.targetNamespace()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setCanonicalVersionId(request.canonicalVersionId().toString()) + .setIntakeRequestId(request.intakeRequestId().toString()) + .setPublicationFence(request.publicationFence().toString()) + .setPublicationRequestId(request.publicationRequestId()) + .setRequestDigest(request.requestDigest()) + .setVersionStateEpoch(request.versionStateEpoch()) + .setPublishWorkflowId(request.publishWorkflowId()) + .setAppliedCommitId(request.appliedCommitId()) + .setContentDigest(request.contentDigest()) + .setDigestSchemaVersion(request.digestSchemaVersion()) + .setSelectorReceiptBytes(ByteString.copyFrom(evidence.selectorReceiptBytes())) + .setOriginalAccountBindingBytes( + ByteString.copyFrom(evidence.originalAccountBindingBytes())) + .setAppliedResultBytes(ByteString.copyFrom(evidence.appliedResultBytes())); + request.worldAffectedTuples().stream() + .map(WorldPublishedStartLocationGrpcCodec::toWireTuple) + .forEach(builder::addWorldAffectedTuples); + return builder.build(); + } + + /** Validates the complete echoed capture tuple and all three exact retained World byte values. */ + public static WorldPublishedStartLocationEvidence fromResponse( + Request request, ReadWorldPublishedStartLocationResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadWorldPublishedStartLocationResponse"); + if (response.getSchemaVersion() != Request.SCHEMA_VERSION) { + throw new IllegalArgumentException( + "Unsupported World published selector response schema version"); + } + Request echoed = + toEvidenceRequest( + response.getTargetNamespace(), + response.getCanonicalTenantId(), + response.getCanonicalVersionId(), + response.getIntakeRequestId(), + response.getPublicationFence(), + response.getPublicationRequestId(), + response.getRequestDigest(), + response.getVersionStateEpoch(), + response.getPublishWorkflowId(), + response.getAppliedCommitId(), + response.getContentDigest(), + response.getDigestSchemaVersion(), + response.getWorldAffectedTuplesList()); + if (!request.equals(echoed)) { + throw new IllegalArgumentException( + "World published selector response changed exact selection request"); + } + if (response.getSelectorReceiptBytes().isEmpty() + || response.getOriginalAccountBindingBytes().isEmpty() + || response.getAppliedResultBytes().isEmpty()) { + throw new IllegalArgumentException( + "World published selector response lacks retained evidence bytes"); + } + return new WorldPublishedStartLocationEvidence( + request, + response.getSelectorReceiptBytes().toByteArray(), + response.getOriginalAccountBindingBytes().toByteArray(), + response.getAppliedResultBytes().toByteArray()); + } + + private static Request toEvidenceRequest( + String namespace, + String tenant, + String version, + String intakeRequest, + String publicationFence, + String publicationRequest, + String requestDigest, + long versionStateEpoch, + String workflow, + String appliedCommit, + String contentDigest, + int digestSchema, + java.util.List tuples) { + var affected = + tuples.stream().map(WorldPublishedStartLocationGrpcCodec::fromWireTuple).toList(); + Request decoded = + new Request( + namespace, + canonicalUuid(tenant, "canonicalTenantId"), + canonicalUuid(version, "canonicalVersionId"), + canonicalUuid(intakeRequest, "intakeRequestId"), + canonicalUuid(publicationFence, "publicationFence"), + publicationRequest, + requestDigest, + versionStateEpoch, + workflow, + appliedCommit, + contentDigest, + digestSchema, + affected); + if (!decoded.worldAffectedTuples().equals(affected)) { + throw new IllegalArgumentException("World affected tuples are not in canonical order"); + } + return decoded; + } + + private static WorldPublishedStartLocationAffectedTuple toWireTuple(OwnedAffectedTuple tuple) { + return WorldPublishedStartLocationAffectedTuple.newBuilder() + .setOwner(tuple.owner()) + .setAggregateType(tuple.aggregateType()) + .setAggregateId(tuple.aggregateId()) + .setScopeType(tuple.scopeType()) + .setScopeId(tuple.scopeId()) + .setExpectedEpoch(tuple.expectedEpoch()) + .build(); + } + + private static OwnedAffectedTuple fromWireTuple(WorldPublishedStartLocationAffectedTuple tuple) { + requireNoUnknownFields(tuple, "WorldPublishedStartLocationAffectedTuple"); + return new OwnedAffectedTuple( + tuple.getOwner(), + tuple.getAggregateType(), + tuple.getAggregateId(), + tuple.getScopeType(), + tuple.getScopeId(), + tuple.getExpectedEpoch()); + } + + private static java.util.UUID canonicalUuid(String value, String label) { + try { + java.util.UUID parsed = java.util.UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new java.util.UUID(0L, 0L))) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID", invalid); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java index be6df2b2fe..35bf6e7387 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java @@ -23,7 +23,7 @@ import net.firedevops.firemud.worldmanagement.v1.WorldDraftTerminalReadStatus; import org.junit.jupiter.api.Test; -class WorldDraftTerminalReadGrpcCodecTest { +public class WorldDraftTerminalReadGrpcCodecTest { private static final UUID OPERATION_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); private static final UUID REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); private static final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); @@ -296,6 +296,9 @@ void exactDeclaredV2CarrierRoundTripsWithItsOriginalRoomAndCompleteGraphDeclarat throws Exception { var request = freshGraphRequest(); var committed = committedReadback(request, true); + byte[] graphBytes = + Base64.getDecoder().decode(object(committed.result()).get("graphBytesBase64").textValue()); + assertThat(java.util.Arrays.equals(graphBytes, canonical(JSON.readTree(graphBytes)))).isFalse(); var response = WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(committed)); assertThat(response.getStatus()) @@ -308,6 +311,32 @@ void exactDeclaredV2CarrierRoundTripsWithItsOriginalRoomAndCompleteGraphDeclarat .containsExactly(committed.canonicalBytes()); } + @Test + void v2RejectsMalformedOrDigestSubstitutedOriginalOwnerGraphBytes() throws Exception { + var request = freshGraphRequest(); + var committed = committedReadback(request, true); + var result = object(committed.result()); + result.put("graphDigest", "sha256:" + "0".repeat(64)); + assertResultRejected(request, committed, canonical(result)); + + result = object(committed.result()); + byte[] malformedGraph = Base64.getDecoder().decode(result.get("graphBytesBase64").textValue()); + malformedGraph[0] = (byte) 0xff; + String graphDigest = sha256(malformedGraph); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(malformedGraph)); + result.put("graphDigest", graphDigest); + var draft = + DraftCommitBinding.fromStored( + new String(request.accountBinding().gameDesignBinding(), StandardCharsets.UTF_8), + request.accountBinding().inputDigest()); + var changedReceipt = receipt(request, draft, graphDigest); + byte[] changedReceiptBytes = canonical(changedReceipt); + result.put( + "startLocationReceiptBase64", Base64.getEncoder().encodeToString(changedReceiptBytes)); + result.put("startLocationReceiptDigest", changedReceipt.get("receiptDigest").textValue()); + assertResultRejected(request, committed, canonical(result)); + } + @Test void v2ReceiptRejectsChangedSelectorScopeRequestCommitFenceAndDigests() throws Exception { var request = freshGraphRequest(); @@ -537,6 +566,23 @@ private static byte[] originalBinding() { return accountBinding(draft); } + /** Test-only exact fresh graph request shared with the published selector carrier proof. */ + public static WorldDraftTerminalReadEvidence.Request + freshGraphRequestForStartLocationEvidenceTest() throws Exception { + return freshGraphRequest(); + } + + /** Test-only complete World APPLIED-v2 readback for the exact fresh graph request. */ + public static DraftAuthorizationFenceBinding.OwnerReadback + committedFreshGraphReadbackForStartLocationEvidenceTest( + WorldDraftTerminalReadEvidence.Request request) { + try { + return committedReadback(request, true); + } catch (Exception impossible) { + throw new AssertionError(impossible); + } + } + private static WorldDraftTerminalReadEvidence.Request freshGraphRequest() throws Exception { DraftCommitBinding draft = freshGraphBinding(); return new WorldDraftTerminalReadEvidence.Request( @@ -701,7 +747,7 @@ private static byte[] graphBytes( rows.add(Map.of("mapping", mapping, "content", Map.of())); } root.put("rows", rows); - return canonical(JSON.valueToTree(root)); + return JSON.writeValueAsBytes(root); } private static tools.jackson.databind.node.ObjectNode receipt( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java index af709487e8..fdbd2ad25e 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java @@ -15,6 +15,44 @@ import org.junit.jupiter.api.Test; class AuthoredWorldLaunchDescriptorGrpcCodecTest { + @Test + void v2CompleteReadPreservesWorldEvidenceAndDeniesOmittedMalformedAndSubstitutedBytes() + throws Exception { + var selector = AuthoredWorldReleaseAttestationSelectorTest.selectorEvidence(); + var authored = AuthoredWorldReleaseAttestationSelectorTest.descriptor(selector); + var release = AuthoredWorldReleaseAttestationSelectorTest.release(authored, selector); + var request = completeRequest(authored); + var response = completeResponse(request, authored, release); + assertThat(AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse(request, response)) + .isEqualTo(new CompleteLaunchBindingEvidence(authored, release)); + for (var invalid : + List.of( + response.getReleaseAttestation().toBuilder().clearWorldStartLocationEvidence().build(), + response.getReleaseAttestation().toBuilder().setSchemaVersion(1).build(), + response.getReleaseAttestation().toBuilder() + .setWorldStartLocationEvidence(com.google.protobuf.ByteString.EMPTY) + .build(), + response.getReleaseAttestation().toBuilder() + .setWorldStartLocationEvidence(com.google.protobuf.ByteString.copyFromUtf8("{} ")) + .build())) { + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, response.toBuilder().setReleaseAttestation(invalid).build())) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + response.toBuilder() + .setReleaseAttestation( + response.getReleaseAttestation().toBuilder() + .setUnknownFields(unknownFields())) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + private static final UUID TENANT_ID = UUID.fromString("12345678-1234-4234-8234-123456789abc"); private static final UUID SOURCE_OPERATION_ID = UUID.fromString("22345678-1234-4234-8234-123456789abc"); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java new file mode 100644 index 0000000000..f4fde9e072 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java @@ -0,0 +1,290 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodecTest; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class AuthoredWorldReleaseAttestationSelectorTest { + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void v2BindsCompleteOriginalEvidenceInItsOwnDomainAndSurvivesStoredReadback() throws Exception { + var selector = selectorEvidence(); + var descriptor = descriptor(selector); + var release = release(descriptor, selector); + var stored = JSON.writeValueAsString(release); + var readback = JSON.readValue(stored, AuthoredWorldReleaseAttestationEvidence.class); + + assertThat(release.schemaVersion()).isEqualTo(2); + assertThat(readback).isEqualTo(release); + readback.requireValid(descriptor); + assertThat( + new String( + AuthoredWorldReleaseAttestationEvidence.evidencePreimage(release), + StandardCharsets.UTF_8)) + .startsWith("49:game-design-authored-world-release-attestation/v2") + .contains("worldStartLocationEvidence.canonicalBytesBase64") + .endsWith(Base64.getEncoder().encodeToString(selector.canonicalBytes())); + assertThat(readback.worldStartLocationEvidence().selectorReceiptBytes()) + .containsExactly(selector.selectorReceiptBytes()); + assertThat(readback.worldStartLocationEvidence().originalAccountBindingBytes()) + .containsExactly(selector.originalAccountBindingBytes()); + assertThat(readback.worldStartLocationEvidence().appliedResultBytes()) + .containsExactly(selector.appliedResultBytes()); + } + + @Test + void v1BytesAndDigestRemainUnchangedAndCannotBePromotedBySupplyingASelector() throws Exception { + var selector = selectorEvidence(); + var descriptor = descriptor(selector); + var current = release(descriptor, selector); + var old = + AuthoredWorldReleaseAttestationEvidence.create( + current.targetNamespace(), + current.descriptorResultDigest(), + current.canonicalTenantId(), + current.canonicalVersionId(), + current.worldSlug(), + current.authoredWorldSourceOperationId(), + current.authoredWorldSourceEvidenceDigest(), + current.launchDescriptorId(), + current.publishedReleaseBundleRef(), + current.versionStateEpoch(), + current.publishWorkflowId(), + current.commitId(), + current.participantDigests(), + current.manifestHash(), + current.manifestSchemaVersion(), + current.requiredManifestAssetKeys(), + current.artifactDigests(), + current.commandDefinitions(), + current.generationConfigRevision()); + String stored = JSON.writeValueAsString(old); + assertThat(stored).doesNotContain("worldStartLocationEvidence"); + assertThat( + JSON.writeValueAsString( + JSON.readValue(stored, AuthoredWorldReleaseAttestationEvidence.class))) + .isEqualTo(stored); + assertThat( + AuthoredWorldLaunchDescriptorGrpcCodec.toReleaseAttestation(old) + .hasWorldStartLocationEvidence()) + .isFalse(); + assertThat(old.evidenceDigest()).isNotEqualTo(current.evidenceDigest()); + assertThatThrownBy(() -> copy(old, 1, selector)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> copy(current, 2, null)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> copy(current, 3, selector)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> copy(old, 2, selector).requireValid()) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void selectorSubstitutionAtAnOtherwiseValidCheckpointChangesTheDigest() throws Exception { + var selector = selectorEvidence(); + var descriptor = descriptor(selector); + var release = release(descriptor, selector); + var request = selector.request(); + var other = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + UUID.randomUUID(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + request.worldAffectedTuples()), + selector.selectorReceiptBytes(), + selector.originalAccountBindingBytes(), + selector.appliedResultBytes()); + assertThat(release(descriptor, other).evidenceDigest()).isNotEqualTo(release.evidenceDigest()); + assertThatThrownBy(() -> copy(release, 2, other).requireValid()) + .isInstanceOf(IllegalArgumentException.class); + var wrongCheckpoint = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + request.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + "other-workflow", + request.appliedCommitId(), + "c".repeat(64), + request.digestSchemaVersion(), + request.worldAffectedTuples()), + selector.selectorReceiptBytes(), + selector.originalAccountBindingBytes(), + selector.appliedResultBytes()); + assertThatThrownBy(() -> copy(release, 2, wrongCheckpoint)) + .isInstanceOf(IllegalArgumentException.class); + } + + static WorldPublishedStartLocationEvidence selectorEvidence() throws Exception { + var terminal = + WorldDraftTerminalReadGrpcCodecTest.freshGraphRequestForStartLocationEvidenceTest(); + var applied = + WorldDraftTerminalReadGrpcCodecTest.committedFreshGraphReadbackForStartLocationEvidenceTest( + terminal); + var account = terminal.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + var tuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + var request = + new WorldPublishedStartLocationEvidence.Request( + "test", + account.tenantId(), + account.versionId(), + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "publication-request", + "a".repeat(64), + 5L, + "publish-workflow", + account.commitId().toString(), + "b".repeat(64), + 3, + tuples); + var result = JSON.readTree(applied.result()); + return new WorldPublishedStartLocationEvidence( + request, + Base64.getDecoder().decode(result.get("startLocationReceiptBase64").textValue()), + applied.fullBinding(), + applied.result()); + } + + static AuthoredWorldLaunchDescriptorEvidence descriptor( + WorldPublishedStartLocationEvidence selector) { + var request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + "test", + "launch-control-request", + selector.request().canonicalTenantId(), + "synthetic-world", + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "sha256:" + "b".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + "descriptor", + 42L, + false, + null, + "{}", + "generation", + 9L, + 7L, + "release", + false, + null); + } + + static AuthoredWorldReleaseAttestationEvidence release( + AuthoredWorldLaunchDescriptorEvidence descriptor, + WorldPublishedStartLocationEvidence selector) { + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + "b".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .toList(); + return AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of("LOOK"), + descriptor.generationConfigRevision(), + selector); + } + + private static AuthoredWorldReleaseAttestationEvidence copy( + AuthoredWorldReleaseAttestationEvidence old, + int schema, + WorldPublishedStartLocationEvidence selector) { + return new AuthoredWorldReleaseAttestationEvidence( + schema, + old.targetNamespace(), + old.descriptorResultDigest(), + old.canonicalTenantId(), + old.canonicalVersionId(), + old.worldSlug(), + old.authoredWorldSourceOperationId(), + old.authoredWorldSourceEvidenceDigest(), + old.launchDescriptorId(), + old.publishedReleaseBundleRef(), + old.versionStateEpoch(), + old.publishWorkflowId(), + old.commitId(), + old.participantDigests(), + old.manifestHash(), + old.manifestSchemaVersion(), + old.requiredManifestAssetKeys(), + old.artifactDigests(), + old.commandDefinitions(), + old.generationConfigRevision(), + old.evidenceDigest(), + selector); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidenceTest.java new file mode 100644 index 0000000000..9534727da0 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidenceTest.java @@ -0,0 +1,156 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import java.util.function.Consumer; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ObjectNode; + +class WorldDraftStartLocationEvidenceTest { + private static final String ACCOUNT_BINDING_DIGEST = "sha256:" + "0".repeat(64); + private static final String BINDING_DIGEST = "sha256:" + "1".repeat(64); + private static final String GRAPH_DIGEST = "sha256:" + "2".repeat(64); + private static final String RECEIPT_DIGEST = + "sha256:9f267c68a4915e5c28dd66536663783808210422fef4ae6062a8cd185d90636c"; + private static final UUID OPERATION_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID FENCE_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final RoomTemplateRef START_LOCATION = + new RoomTemplateRef( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + uuid("77777777-7777-4777-8777-777777777777")); + private static final tools.jackson.databind.ObjectMapper JSON = JsonMapper.builder().build(); + + @Test + void createMatchesTheOriginalReceiptPreimageAndCanonicalBytes() { + var evidence = evidence(); + + assertThat(evidence.receiptDigest()).isEqualTo(RECEIPT_DIGEST); + assertThat(new String(evidence.canonicalBytes(), StandardCharsets.UTF_8)) + .isEqualTo( + "{\"accountBindingDigest\":\"sha256:" + + "0000000000000000000000000000000000000000000000000000000000000000" + + "\",\"authorizationFenceId\":\"bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb\"" + + ",\"bindingDigest\":\"sha256:" + + "1111111111111111111111111111111111111111111111111111111111111111" + + "\",\"commitId\":\"55555555-5555-4555-8555-555555555555\"" + + ",\"graphDigest\":\"sha256:" + + "2222222222222222222222222222222222222222222222222222222222222222" + + "\",\"operationId\":\"aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa\"" + + ",\"receiptDigest\":\"sha256:" + + "9f267c68a4915e5c28dd66536663783808210422fef4ae6062a8cd185d90636c" + + "\",\"requestId\":\"44444444-4444-4444-8444-444444444444\"" + + ",\"schema\":\"world-draft-start-location-receipt/v1\"" + + ",\"startLocation\":{\"roomTemplateId\":\"77777777-7777-4777-8777-777777777777\"" + + ",\"tenantId\":\"11111111-1111-4111-8111-111111111111\"" + + ",\"versionId\":\"22222222-2222-4222-8222-222222222222\"}" + + ",\"targetNamespace\":\"test\"}"); + assertThat(WorldDraftStartLocationEvidence.fromStored(evidence.canonicalBytes())) + .isEqualTo(evidence); + } + + @Test + void fromStoredRejectsUnknownDuplicateTrailingInvalidUtf8AndNoncanonicalBytes() throws Exception { + byte[] canonical = evidence().canonicalBytes(); + String json = new String(canonical, StandardCharsets.UTF_8); + assertRejected((" " + json).getBytes(StandardCharsets.UTF_8)); + assertRejected((json + "{}").getBytes(StandardCharsets.UTF_8)); + assertRejected( + (json.substring(0, json.length() - 1) + ",\"unsupported\":true}") + .getBytes(StandardCharsets.UTF_8)); + assertRejected( + json.replace("\"startLocation\":{", "\"startLocation\":{\"unsupported\":true,") + .getBytes(StandardCharsets.UTF_8)); + assertRejected( + json.replace( + "\"targetNamespace\":\"test\"", + "\"targetNamespace\":\"test\",\"targetNamespace\":\"test\"") + .getBytes(StandardCharsets.UTF_8)); + assertRejected( + json.replace( + "\"startLocation\":{", + "\"startLocation\":{\"tenantId\":\"11111111-1111-4111-8111-111111111111\",") + .getBytes(StandardCharsets.UTF_8)); + byte[] invalidUtf8 = canonical.clone(); + invalidUtf8[1] = (byte) 0xc3; + assertRejected(invalidUtf8); + } + + @Test + void fromStoredRejectsNilNoncanonicalAndDigestSubstitutedFields() throws Exception { + for (Consumer change : + List.>of( + receipt -> receipt.put("schema", "world-draft-start-location-receipt/v2"), + receipt -> receipt.put("operationId", "00000000-0000-0000-0000-000000000000"), + receipt -> receipt.put("operationId", "AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA"), + receipt -> receipt.put("targetNamespace", "test-two"), + receipt -> receipt.put("operationId", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + receipt -> receipt.put("requestId", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + receipt -> receipt.put("commitId", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + receipt -> receipt.put("authorizationFenceId", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + receipt -> receipt.put("accountBindingDigest", "sha256:" + "f".repeat(64)), + receipt -> receipt.put("bindingDigest", "sha256:" + "f".repeat(64)), + receipt -> selector(receipt).put("tenantId", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + receipt -> selector(receipt).put("versionId", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + receipt -> + selector(receipt).put("roomTemplateId", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + receipt -> receipt.put("graphDigest", "sha256:" + "f".repeat(64)), + receipt -> receipt.put("receiptDigest", "sha256:" + "f".repeat(64)))) { + assertRejected(changed(change)); + } + + assertThatThrownBy( + () -> + WorldDraftStartLocationEvidence.create( + "invalid/namespace", + OPERATION_ID, + REQUEST_ID, + COMMIT_ID, + FENCE_ID, + ACCOUNT_BINDING_DIGEST, + BINDING_DIGEST, + START_LOCATION, + GRAPH_DIGEST)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static WorldDraftStartLocationEvidence evidence() { + return WorldDraftStartLocationEvidence.create( + "test", + OPERATION_ID, + REQUEST_ID, + COMMIT_ID, + FENCE_ID, + ACCOUNT_BINDING_DIGEST, + BINDING_DIGEST, + START_LOCATION, + GRAPH_DIGEST); + } + + private static byte[] changed(Consumer change) throws Exception { + ObjectNode receipt = (ObjectNode) JSON.readTree(evidence().canonicalBytes()); + change.accept(receipt); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(receipt)); + } + + private static ObjectNode selector(ObjectNode receipt) { + return (ObjectNode) receipt.get("startLocation"); + } + + private static void assertRejected(byte[] stored) { + assertThatThrownBy(() -> WorldDraftStartLocationEvidence.fromStored(stored)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationClientTest.java new file mode 100644 index 0000000000..ad31df4c00 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationClientTest.java @@ -0,0 +1,155 @@ +package net.firedevops.firemud.common.world; + +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.times; +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.stub.AbstractStub; +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.WorldPublishedStartLocationReadServiceGrpc; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class WorldPublishedStartLocationClientTest { + @Test + void rejectsPlaintextAndWrongNamespaceBeforeCreatingTransport(@TempDir Path directory) + throws Exception { + var channelFactory = mock(GrpcChannelFactory.class); + var plaintext = tls(directory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldPublishedStartLocationClient( + new ServiceEndpointsProperties(), plaintext, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + + var client = + new WorldPublishedStartLocationClient( + new ServiceEndpointsProperties(), tls(directory), channelFactory, "test"); + try { + var request = WorldPublishedStartLocationGrpcCodecTest.evidence().request(); + assertThatThrownBy(() -> client.read(withNamespace(request, "other"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + verifyNoInteractions(channelFactory); + } finally { + client.close(); + } + } + + @Test + void initializesExactWorldPeerCredentialsAndReadsValidatedEvidence(@TempDir Path directory) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("world.internal:6565"); + var channelFactory = mock(GrpcChannelFactory.class); + var channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + eq("world.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + var client = + new WorldPublishedStartLocationClient(endpoints, tls(directory), channelFactory, "test"); + try { + client.init(); + verify(channelFactory) + .buildChannel( + eq("world.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true)); + AbstractStub initializedStub = initializedStub(client); + assertThat(initializedStub.getCallOptions().getCredentials()) + .isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); + assertThat(readField(initializedStub.getCallOptions().getCredentials(), "expectedPeerUri")) + .isEqualTo("spiffe://firemud/ns/test/sa/world-management-service"); + + WorldPublishedStartLocationEvidence evidence = + WorldPublishedStartLocationGrpcCodecTest.evidence(); + var stub = + mock( + WorldPublishedStartLocationReadServiceGrpc + .WorldPublishedStartLocationReadServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + setStub(client, stub); + var response = WorldPublishedStartLocationGrpcCodec.toResponse(evidence.request(), evidence); + when(stub.readWorldPublishedStartLocation(any())).thenReturn(response); + assertThat(client.read(evidence.request()).canonicalBytes()) + .containsExactly(evidence.canonicalBytes()); + + when(stub.readWorldPublishedStartLocation(any())) + .thenReturn( + response.toBuilder() + .setAppliedResultBytes(com.google.protobuf.ByteString.copyFrom(new byte[] {1})) + .build()); + assertThatThrownBy(() -> client.read(evidence.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid published selector evidence"); + verify(stub, times(2)).withDeadlineAfter(5L, TimeUnit.SECONDS); + } finally { + client.close(); + } + } + + private static AbstractStub initializedStub(WorldPublishedStartLocationClient client) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + return (AbstractStub) field.get(client); + } + + private static void setStub(WorldPublishedStartLocationClient client, AbstractStub stub) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + } + + private static Object readField(Object target, String name) throws ReflectiveOperationException { + Field field = target.getClass().getDeclaredField(name); + field.setAccessible(true); + return field.get(target); + } + + private static WorldPublishedStartLocationEvidence.Request withNamespace( + WorldPublishedStartLocationEvidence.Request source, String namespace) { + return new WorldPublishedStartLocationEvidence.Request( + namespace, + source.canonicalTenantId(), + source.canonicalVersionId(), + source.intakeRequestId(), + source.publicationFence(), + source.publicationRequestId(), + source.requestDigest(), + source.versionStateEpoch(), + source.publishWorkflowId(), + source.appliedCommitId(), + source.contentDigest(), + source.digestSchemaVersion(), + source.worldAffectedTuples()); + } + + private static CommonGrpcClientProperties tls(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/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java new file mode 100644 index 0000000000..58a6606492 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java @@ -0,0 +1,179 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodecTest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationResponse; +import org.junit.jupiter.api.Test; + +class WorldPublishedStartLocationGrpcCodecTest { + private static final tools.jackson.databind.ObjectMapper JSON = + new tools.jackson.databind.ObjectMapper(); + + @Test + void exactSelectionAndRetainedEvidenceRoundTripAcrossReadRetries() throws Exception { + WorldPublishedStartLocationEvidence expected = evidence(); + var wireRequest = WorldPublishedStartLocationGrpcCodec.toRequest(expected.request()); + assertThat(WorldPublishedStartLocationGrpcCodec.fromRequest(wireRequest)) + .isEqualTo(expected.request()); + + var firstResponse = + WorldPublishedStartLocationGrpcCodec.toResponse(expected.request(), expected); + var retryResponse = + WorldPublishedStartLocationGrpcCodec.toResponse(expected.request(), expected); + assertThat(retryResponse).isEqualTo(firstResponse); + var first = + WorldPublishedStartLocationGrpcCodec.fromResponse(expected.request(), firstResponse); + var retry = + WorldPublishedStartLocationGrpcCodec.fromResponse(expected.request(), retryResponse); + assertThat(first.canonicalBytes()).containsExactly(expected.canonicalBytes()); + assertThat(retry.canonicalBytes()).containsExactly(first.canonicalBytes()); + assertThat( + WorldPublishedStartLocationEvidence.fromStored(first.canonicalBytes()).canonicalBytes()) + .containsExactly(first.canonicalBytes()); + var decoded = WorldPublishedStartLocationEvidence.fromStored(first.canonicalBytes()); + assertThat(decoded).isEqualTo(expected); + assertThat(decoded.hashCode()).isEqualTo(expected.hashCode()); + } + + @Test + void rejectsChangedSelectionAndSubstitutedReceiptAccountOrAppliedBytes() throws Exception { + WorldPublishedStartLocationEvidence evidence = evidence(); + ReadWorldPublishedStartLocationResponse response = + WorldPublishedStartLocationGrpcCodec.toResponse(evidence.request(), evidence); + + assertThatThrownBy( + () -> + WorldPublishedStartLocationGrpcCodec.fromResponse( + evidence.request(), + response.toBuilder() + .setPublicationFence( + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd").toString()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed exact selection"); + + assertThatThrownBy( + () -> + WorldPublishedStartLocationGrpcCodec.fromResponse( + evidence.request(), + response.toBuilder() + .setSelectorReceiptBytes(ByteString.copyFrom(new byte[] {1})) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldPublishedStartLocationGrpcCodec.fromResponse( + evidence.request(), + response.toBuilder() + .setOriginalAccountBindingBytes(ByteString.copyFrom(new byte[] {1})) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldPublishedStartLocationGrpcCodec.fromResponse( + evidence.request(), + response.toBuilder() + .setAppliedResultBytes(ByteString.copyFrom(new byte[] {1})) + .build())) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + new WorldPublishedStartLocationEvidence( + evidence.request(), + evidence.selectorReceiptBytes(), + evidence.originalAccountBindingBytes(), + new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class); + + var changedIntake = + new WorldPublishedStartLocationEvidence.Request( + evidence.request().targetNamespace(), + evidence.request().canonicalTenantId(), + evidence.request().canonicalVersionId(), + uuid("99999999-9999-4999-8999-999999999999"), + evidence.request().publicationFence(), + evidence.request().publicationRequestId(), + evidence.request().requestDigest(), + evidence.request().versionStateEpoch(), + evidence.request().publishWorkflowId(), + evidence.request().appliedCommitId(), + evidence.request().contentDigest(), + evidence.request().digestSchemaVersion(), + evidence.request().worldAffectedTuples()); + assertThatThrownBy( + () -> + new WorldPublishedStartLocationEvidence( + changedIntake, + evidence.selectorReceiptBytes(), + evidence.originalAccountBindingBytes(), + evidence.appliedResultBytes())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("intake request"); + } + + static WorldPublishedStartLocationEvidence evidence() throws Exception { + WorldDraftTerminalReadEvidence.Request terminalRequest = freshGraphRequest(); + OwnerReadback committed = freshGraphReadback(terminalRequest); + var account = terminalRequest.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + List tuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + var request = + new WorldPublishedStartLocationEvidence.Request( + "test", + account.tenantId(), + account.versionId(), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "publication-request", + "a".repeat(64), + 5L, + "publish-workflow", + account.commitId().toString(), + "b".repeat(64), + 3, + tuples); + var applied = JSON.readTree(committed.result()); + byte[] receipt = + Base64.getDecoder().decode(applied.get("startLocationReceiptBase64").textValue()); + return new WorldPublishedStartLocationEvidence( + request, receipt, committed.fullBinding(), committed.result()); + } + + private static WorldDraftTerminalReadEvidence.Request freshGraphRequest() throws Exception { + return WorldDraftTerminalReadGrpcCodecTest.freshGraphRequestForStartLocationEvidenceTest(); + } + + private static OwnerReadback freshGraphReadback(WorldDraftTerminalReadEvidence.Request request) + throws Exception { + return WorldDraftTerminalReadGrpcCodecTest + .committedFreshGraphReadbackForStartLocationEvidenceTest(request); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java index 1358c92f51..b8cd545f21 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java @@ -3,6 +3,7 @@ import java.time.LocalDateTime; import java.util.List; import java.util.UUID; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; public record PublishedReleaseBundleDto( @@ -24,7 +25,8 @@ public record PublishedReleaseBundleDto( UUID canonicalVersionId, String publishedReleaseBundleRef, Integer manifestSchemaVersion, - List artifactDigests) { + List artifactDigests, + WorldPublishedStartLocationEvidence worldPublishedStartLocationEvidence) { public PublishedReleaseBundleDto { requiredManifestAssetKeys = List.copyOf(requiredManifestAssetKeys == null ? List.of() : requiredManifestAssetKeys); @@ -35,6 +37,54 @@ public record PublishedReleaseBundleDto( "Manifest schema and artifact proof must be present together"); } artifactDigests = artifactDigests == null ? null : List.copyOf(artifactDigests); + if ("v2".equals(attestationSchemaVersion) != (worldPublishedStartLocationEvidence != null)) { + throw new IllegalArgumentException( + "Selector evidence requires bundle v2 and is mandatory for v2"); + } + } + + /** Original retained bundle construction shape; cannot construct a selector-bearing v2 bundle. */ + public PublishedReleaseBundleDto( + Long id, + String tenantId, + Long versionId, + int versionNumber, + String attestationSchemaVersion, + String publishWorkflowId, + String manifestHash, + List requiredManifestAssetKeys, + List participantDigests, + List commandDefinitions, + String generationConfigRevision, + boolean scriptOnly, + String scriptPatchVersion, + LocalDateTime publishedAt, + UUID canonicalTenantId, + UUID canonicalVersionId, + String publishedReleaseBundleRef, + Integer manifestSchemaVersion, + List artifactDigests) { + this( + id, + tenantId, + versionId, + versionNumber, + attestationSchemaVersion, + publishWorkflowId, + manifestHash, + requiredManifestAssetKeys, + participantDigests, + commandDefinitions, + generationConfigRevision, + scriptOnly, + scriptPatchVersion, + publishedAt, + canonicalTenantId, + canonicalVersionId, + publishedReleaseBundleRef, + manifestSchemaVersion, + artifactDigests, + null); } public PublishedReleaseBundleDto( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishedReleaseBundle.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishedReleaseBundle.java index c22a7635e9..83853a7800 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishedReleaseBundle.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishedReleaseBundle.java @@ -22,6 +22,7 @@ public class PublishedReleaseBundle { private String requiredManifestAssetKeysJson; private String participantDigestsJson = "[]"; private String commandDefinitionsJson = "[]"; + private String worldPublishedStartLocationEvidenceJson; private boolean scriptOnly; private String scriptPatchVersion; private LocalDateTime publishedAt = LocalDateTime.now(); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java index e14f94b78c..b87f6bcde9 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java @@ -1,11 +1,13 @@ package net.firedevops.firemud.gamedesign.repository; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.Objects; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import org.jooq.DSLContext; import org.jooq.Field; @@ -52,6 +54,8 @@ public class PublishedReleaseBundleRepository { DSL.field(DSL.name("participant_digests_json"), String.class); private static final Field COMMAND_DEFINITIONS_JSON = DSL.field(DSL.name("command_definitions_json"), String.class); + private static final Field WORLD_SELECTOR_EVIDENCE_JSON = + DSL.field(DSL.name("world_published_start_location_evidence_json"), String.class); private static final Field SCRIPT_ONLY = DSL.field(DSL.name("script_only"), Boolean.class); private static final Field SCRIPT_PATCH_VERSION = @@ -122,6 +126,22 @@ private PublishedReleaseBundle insertNewBundle( DSLContext tx, PublishedReleaseBundle bundle, LocalDateTime publishedAt) { CanonicalSource source = findExactCanonicalSource(tx, bundle); rejectCallerIdentitySubstitution(bundle, source); + verifySelectorSource(bundle, source); + if ("v2".equals(bundle.getAttestationSchemaVersion())) { + PublishedReleaseBundle existing = + tx.selectFrom(TABLE_REF) + .where(TENANT_ID.eq(bundle.getTenantId()).and(VERSION_ID.eq(bundle.getVersionId()))) + .fetchOne(this::toEntity); + if (existing != null) { + try { + verifyPersistedSource(existing, bundle, source, existing.getPublishedReleaseBundleRef()); + } catch (IllegalStateException conflict) { + throw new IllegalStateException( + "IDEMPOTENCY_CONFLICT: changed immutable selector release input", conflict); + } + return existing; + } + } String publishedReleaseBundleRef = UUID.randomUUID().toString(); Long generatedId = @@ -141,6 +161,7 @@ private PublishedReleaseBundle insertNewBundle( .set(REQUIRED_MANIFEST_ASSET_KEYS_JSON, bundle.getRequiredManifestAssetKeysJson()) .set(PARTICIPANT_DIGESTS_JSON, bundle.getParticipantDigestsJson()) .set(COMMAND_DEFINITIONS_JSON, bundle.getCommandDefinitionsJson()) + .set(WORLD_SELECTOR_EVIDENCE_JSON, bundle.getWorldPublishedStartLocationEvidenceJson()) .set(SCRIPT_ONLY, bundle.isScriptOnly()) .set(SCRIPT_PATCH_VERSION, bundle.getScriptPatchVersion()) .set(PUBLISHED_AT, Timestamp.valueOf(publishedAt)) @@ -179,6 +200,7 @@ private CanonicalSource findExactCanonicalSource(DSLContext tx, PublishedRelease .and(SOURCE_PROVENANCE_KIND.in("NEW_GAME_ROW", "RETAINED_GAME_V30")) .and(SOURCE_GAME_SOURCE_ROW_ID.eq(SOURCE_GAME_ID)) .and(SOURCE_GAME_SOURCE_TENANT_KEY.eq(SOURCE_GAME_TENANT_ID))) + .forUpdate() .fetchOne(); if (source == null) { throw new IllegalStateException( @@ -220,6 +242,19 @@ private void verifyPersistedSource( || !Objects.equals( persisted.getManifestSchemaVersion(), requested.getManifestSchemaVersion()) || !Objects.equals(persisted.getArtifactDigestsJson(), requested.getArtifactDigestsJson()) + || !Objects.equals( + persisted.getWorldPublishedStartLocationEvidenceJson(), + requested.getWorldPublishedStartLocationEvidenceJson()) + || !Objects.equals( + persisted.getAttestationSchemaVersion(), requested.getAttestationSchemaVersion()) + || !Objects.equals(persisted.getPublishWorkflowId(), requested.getPublishWorkflowId()) + || persisted.getVersionNumber() != requested.getVersionNumber() + || !Objects.equals( + persisted.getGenerationConfigRevision(), requested.getGenerationConfigRevision()) + || !Objects.equals( + persisted.getCommandDefinitionsJson(), requested.getCommandDefinitionsJson()) + || persisted.isScriptOnly() != requested.isScriptOnly() + || !Objects.equals(persisted.getScriptPatchVersion(), requested.getScriptPatchVersion()) || !Objects.equals( persisted.getRequiredManifestAssetKeysJson(), requested.getRequiredManifestAssetKeysJson()) @@ -256,12 +291,38 @@ private PublishedReleaseBundle toEntity(Record record) { bundle.setRequiredManifestAssetKeysJson(record.get(REQUIRED_MANIFEST_ASSET_KEYS_JSON)); bundle.setParticipantDigestsJson(record.get(PARTICIPANT_DIGESTS_JSON)); bundle.setCommandDefinitionsJson(record.get(COMMAND_DEFINITIONS_JSON)); + bundle.setWorldPublishedStartLocationEvidenceJson(record.get(WORLD_SELECTOR_EVIDENCE_JSON)); bundle.setScriptOnly(Boolean.TRUE.equals(record.get(SCRIPT_ONLY))); bundle.setScriptPatchVersion(record.get(SCRIPT_PATCH_VERSION)); Timestamp publishedAt = record.get(PUBLISHED_AT); bundle.setPublishedAt(publishedAt == null ? null : publishedAt.toLocalDateTime()); + verifySelectorSource( + bundle, new CanonicalSource(bundle.getCanonicalTenantId(), bundle.getCanonicalVersionId())); return bundle; } + private static void verifySelectorSource(PublishedReleaseBundle bundle, CanonicalSource source) { + String bytes = bundle.getWorldPublishedStartLocationEvidenceJson(); + if (!"v2".equals(bundle.getAttestationSchemaVersion())) { + if (bytes != null) { + throw new IllegalArgumentException( + "Selector evidence is forbidden on historical release schemas"); + } + return; + } + if (bytes == null) { + throw new IllegalArgumentException("World selector evidence is mandatory for release v2"); + } + var request = + WorldPublishedStartLocationEvidence.fromStored(bytes.getBytes(StandardCharsets.UTF_8)) + .request(); + if (!request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.canonicalVersionId().equals(source.canonicalVersionId()) + || !request.publishWorkflowId().equals(bundle.getPublishWorkflowId())) { + throw new IllegalArgumentException( + "World selector differs from exact Version source/workflow"); + } + } + private record CanonicalSource(UUID canonicalTenantId, UUID canonicalVersionId) {} } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedReleaseBundleService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedReleaseBundleService.java index 4265e6884c..2b09e9d3e1 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedReleaseBundleService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedReleaseBundleService.java @@ -6,6 +6,17 @@ import net.firedevops.firemud.gamedesign.dto.VersionDto; public interface PublishedReleaseBundleService { + /** + * Requires evidence already obtained over the authenticated World client before this transaction. + */ + PublishedReleaseBundleDto createFullVersionBundle( + VersionDto version, + String publishWorkflowId, + ExportedAssetManifest exportedManifest, + String generationConfigRevision, + java.util.List participantDigests, + net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence worldEvidence); + PublishedReleaseBundleDto createFullVersionBundle( VersionDto version, String publishWorkflowId, diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java index 7be83c4d9c..d27efee5cf 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java @@ -135,27 +135,53 @@ public CompleteLaunchBindingDto getCompleteLaunchBinding( List artifacts = requireManifestAndArtifactEvidence(bundle); - AuthoredWorldReleaseAttestationEvidence releaseAttestation = - AuthoredWorldReleaseAttestationEvidence.create( - descriptor.targetNamespace(), - descriptor.resultDigest(), - source.canonicalTenantId(), - canonicalVersion.getCanonicalVersionId(), - source.worldSlug(), - source.operationId(), - source.evidenceDigest(), - descriptor.launchDescriptorId(), - descriptor.publishedReleaseBundleRef(), - descriptor.versionStateEpoch(), - bundle.publishWorkflowId(), - commitId, - participants, - bundle.manifestHash(), - bundle.manifestSchemaVersion(), - bundle.requiredManifestAssetKeys(), - artifacts, - bundle.commandDefinitions(), - bundle.generationConfigRevision()); + AuthoredWorldReleaseAttestationEvidence releaseAttestation; + if ("v2".equals(bundle.attestationSchemaVersion())) { + releaseAttestation = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + source.canonicalTenantId(), + canonicalVersion.getCanonicalVersionId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + bundle.publishWorkflowId(), + commitId, + participants, + bundle.manifestHash(), + bundle.manifestSchemaVersion(), + bundle.requiredManifestAssetKeys(), + artifacts, + bundle.commandDefinitions(), + bundle.generationConfigRevision(), + bundle.worldPublishedStartLocationEvidence()); + } else { + releaseAttestation = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + source.canonicalTenantId(), + canonicalVersion.getCanonicalVersionId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + bundle.publishWorkflowId(), + commitId, + participants, + bundle.manifestHash(), + bundle.manifestSchemaVersion(), + bundle.requiredManifestAssetKeys(), + artifacts, + bundle.commandDefinitions(), + bundle.generationConfigRevision()); + } releaseAttestation.requireValid(descriptor); return new CompleteLaunchBindingDto(descriptor, releaseAttestation); } @@ -247,7 +273,10 @@ private void requireExactBundleBinding( || snapshotCanonicalVersionId == null || NIL_UUID.equals(snapshotCanonicalVersionId) || !Objects.equals(snapshotCanonicalVersionId, bundle.canonicalVersionId()) - || !"v1".equals(bundle.attestationSchemaVersion()) + || !("v1".equals(bundle.attestationSchemaVersion()) + && bundle.worldPublishedStartLocationEvidence() == null + || "v2".equals(bundle.attestationSchemaVersion()) + && bundle.worldPublishedStartLocationEvidence() != null) || !Objects.equals(bundle.id(), descriptor.releaseBundleId()) || !Objects.equals(bundle.versionId(), descriptor.versionId()) || !Objects.equals(bundle.tenantId(), source.sourceGameTenantKey()) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java index 6c6ca9567d..f295ad77fc 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java @@ -177,12 +177,19 @@ private ResolvedLaunchDescriptorDto resolveNewLaunchDescriptor( throw denial( "RELEASE_BUNDLE_NOT_FOUND", "release bundle is not owned by the resolved source version"); } - if (!PublishedReleaseBundleContract.SUPPORTED_ATTESTATION_SCHEMA_VERSION.equals( - bundle.attestationSchemaVersion())) { - throw denial( - PublishedReleaseBundleContract.SCHEMA_VERSION_UNSUPPORTED, - "unsupported published release bundle attestation schema " - + bundle.attestationSchemaVersion()); + try { + PublishedReleaseBundleContract.requireSupportedSchemaForLaunchDescriptor(bundle); + } catch (IllegalArgumentException invalid) { + if (invalid.getMessage() != null + && invalid + .getMessage() + .startsWith(PublishedReleaseBundleContract.SCHEMA_VERSION_UNSUPPORTED + ":")) { + throw denial( + PublishedReleaseBundleContract.SCHEMA_VERSION_UNSUPPORTED, + "unsupported published release bundle attestation schema " + + bundle.attestationSchemaVersion()); + } + throw invalid; } if (bundle.publishedReleaseBundleRef() == null || bundle.publishedReleaseBundleRef().isBlank()) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java index e21fe68126..24f62bbc0c 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java @@ -1,18 +1,112 @@ package net.firedevops.firemud.gamedesign.service.impl; +import java.util.Arrays; +import java.util.HashSet; import java.util.List; import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; final class PublishedReleaseBundleContract { static final String SUPPORTED_ATTESTATION_SCHEMA_VERSION = "v1"; + static final String SELECTOR_ATTESTATION_SCHEMA_VERSION = "v2"; static final String SCHEMA_VERSION_UNSUPPORTED = "SCHEMA_VERSION_UNSUPPORTED"; static final String REPAIR_ATTESTATION_MISMATCH = "REPAIR_ATTESTATION_MISMATCH"; static final String REPAIR_ATTESTED_ASSET_KEY_MISMATCH = "REPAIR_ATTESTED_ASSET_KEY_MISMATCH"; private PublishedReleaseBundleContract() {} + static void requireSelectorBinding(PublishedReleaseBundleDto bundle) { + new ExportedAssetManifest( + bundle.manifestHash(), + Objects.requireNonNull(bundle.manifestSchemaVersion(), "manifestSchemaVersion"), + bundle.requiredManifestAssetKeys(), + Objects.requireNonNull(bundle.artifactDigests(), "artifactDigests")); + var evidence = + Objects.requireNonNull(bundle.worldPublishedStartLocationEvidence(), "World evidence"); + var request = evidence.request(); + if (!SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion()) + || bundle.scriptOnly() + || bundle.scriptPatchVersion() != null + || !request.canonicalTenantId().equals(bundle.canonicalTenantId()) + || !request.canonicalVersionId().equals(bundle.canonicalVersionId()) + || !request.publishWorkflowId().equals(bundle.publishWorkflowId()) + || bundle.manifestSchemaVersion() == null + || bundle.artifactDigests() == null) { + throw new IllegalArgumentException( + "World selector differs from complete immutable release binding"); + } + var required = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder(); + var seen = new HashSet(); + for (var participant : bundle.participantDigests()) { + if (!required.contains(participant.participantKey()) + || !seen.add(participant.participantKey()) + || !participant.succeeded() + || participant.baseVersionId() != null + || !Long.toString(bundle.versionId()).equals(participant.scopeValue()) + || !request.appliedCommitId().equals(participant.appliedCommitId()) + || participant.contentDigest() == null + || !participant.contentDigest().matches("[0-9a-f]{64}") + || !Objects.equals( + participant.digestSchemaVersion(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participant.participantKey()))) { + throw new IllegalArgumentException( + "World selector requires all exact successful release participants"); + } + if ("WORLD_MANAGEMENT".equals(participant.participantKey()) + && (!request.contentDigest().equals(participant.contentDigest()) + || request.digestSchemaVersion() != participant.digestSchemaVersion())) { + throw new IllegalArgumentException( + "World selector differs from World participant digest/schema"); + } + if ("GAME_LOGIC".equals(participant.participantKey()) + && (participant.abilitySchemaDigest() == null + || !participant.abilitySchemaDigest().matches("sha256:[0-9a-f]{64}"))) { + throw new IllegalArgumentException( + "World selector release lacks Game Logic ability schema proof"); + } + } + if (seen.size() != required.size()) { + throw new IllegalArgumentException("World selector release lacks required participants"); + } + } + + static void requireExactSelectorRetry( + PublishedReleaseBundleDto stored, + VersionDto version, + String workflow, + ExportedAssetManifest manifest, + String generationRevision, + List participants, + WorldPublishedStartLocationEvidence evidence) { + if (!SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(stored.attestationSchemaVersion())) { + throw new IllegalStateException( + "IDEMPOTENCY_CONFLICT: historical release is selector-ineligible"); + } + requireSelectorBinding(stored); + if (stored.versionNumber() != version.versionNumber() + || version.scriptOnly() + || version.scriptPatchVersion() != null + || !Objects.equals(stored.publishWorkflowId(), workflow) + || !Objects.equals(stored.manifestHash(), manifest.manifestHash()) + || !Objects.equals(stored.manifestSchemaVersion(), manifest.manifestSchemaVersion()) + || !Objects.equals(stored.artifactDigests(), manifest.artifactDigests()) + || !stored.requiredManifestAssetKeys().equals(manifest.requiredManifestAssetKeys()) + || !Objects.equals(stored.generationConfigRevision(), generationRevision) + || !stored.participantDigests().equals(participants) + || !Arrays.equals( + stored.worldPublishedStartLocationEvidence().canonicalBytes(), + evidence.canonicalBytes())) { + throw new IllegalStateException( + "IDEMPOTENCY_CONFLICT: changed immutable selector release input"); + } + } + static void requireSupportedSchemaForRead(PublishedReleaseBundleDto bundle) { if (!SUPPORTED_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { throw new IllegalStateException( @@ -22,6 +116,17 @@ static void requireSupportedSchemaForRead(PublishedReleaseBundleDto bundle) { } } + /** + * Publication reconciliation only; does not widen launch or repair authorization/schema support. + */ + static void requireSupportedSchemaForPublicationRead(PublishedReleaseBundleDto bundle) { + if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { + requireSelectorBinding(bundle); + return; + } + requireSupportedSchemaForRead(bundle); + } + static void requireSupportedSchemaForLaunch(PublishedReleaseBundleDto bundle) { if (!SUPPORTED_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { throw new IllegalArgumentException( @@ -31,6 +136,17 @@ static void requireSupportedSchemaForLaunch(PublishedReleaseBundleDto bundle) { } } + /** + * Descriptor resolution only; descriptor/v1 remains separate from the complete release carrier. + */ + static void requireSupportedSchemaForLaunchDescriptor(PublishedReleaseBundleDto bundle) { + if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { + requireSelectorBinding(bundle); + return; + } + requireSupportedSchemaForLaunch(bundle); + } + static void requireExactRepairMatch( PublishedReleaseBundleDto bundle, ExportedAssetManifest exportedManifest) { requireSupportedSchemaForRead(bundle); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java index 4abdc4165d..f87e29e9eb 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamedesign.service.impl; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -10,6 +11,7 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; @@ -56,15 +58,61 @@ public PublishedReleaseBundleDto createFullVersionBundle( ExportedAssetManifest exportedManifest, String generationConfigRevision, List participantDigests) { + return createBundle( + version, + publishWorkflowId, + exportedManifest, + generationConfigRevision, + participantDigests, + null); + } + + @Override + @Transactional + public PublishedReleaseBundleDto createFullVersionBundle( + VersionDto version, + String publishWorkflowId, + ExportedAssetManifest exportedManifest, + String generationConfigRevision, + List participantDigests, + WorldPublishedStartLocationEvidence worldEvidence) { + Objects.requireNonNull(worldEvidence, "Authenticated World evidence is required"); + return createBundle( + version, + publishWorkflowId, + exportedManifest, + generationConfigRevision, + participantDigests, + worldEvidence); + } + + private PublishedReleaseBundleDto createBundle( + VersionDto version, + String publishWorkflowId, + ExportedAssetManifest exportedManifest, + String generationConfigRevision, + List participantDigests, + WorldPublishedStartLocationEvidence worldEvidence) { Objects.requireNonNull(version, "version must not be null"); Objects.requireNonNull(exportedManifest, "exportedManifest must not be null"); Objects.requireNonNull(participantDigests, "participantDigests must not be null"); - repository - .findByTenantIdAndVersionId(version.tenantId(), version.id()) - .ifPresent( - ignored -> { - throw new IllegalStateException("published release bundle already exists"); - }); + Optional existing = + repository.findByTenantIdAndVersionId(version.tenantId(), version.id()); + if (existing.isPresent() && worldEvidence == null) { + throw new IllegalStateException("published release bundle already exists"); + } + if (existing.isPresent()) { + PublishedReleaseBundleDto stored = toDto(existing.orElseThrow()); + PublishedReleaseBundleContract.requireExactSelectorRetry( + stored, + version, + publishWorkflowId, + exportedManifest, + generationConfigRevision, + participantDigests, + worldEvidence); + return stored; + } var identitySource = versionRepository .findByTenantIdAndId(version.tenantId(), version.id()) @@ -87,7 +135,13 @@ public PublishedReleaseBundleDto createFullVersionBundle( entity.setCanonicalVersionId(canonicalVersionId); entity.setVersionNumber(version.versionNumber()); entity.setAttestationSchemaVersion( - PublishedReleaseBundleContract.SUPPORTED_ATTESTATION_SCHEMA_VERSION); + worldEvidence == null + ? PublishedReleaseBundleContract.SUPPORTED_ATTESTATION_SCHEMA_VERSION + : PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION); + entity.setWorldPublishedStartLocationEvidenceJson( + worldEvidence == null + ? null + : new String(worldEvidence.canonicalBytes(), StandardCharsets.UTF_8)); entity.setPublishWorkflowId(publishWorkflowId); entity.setManifestHash(exportedManifest.manifestHash()); entity.setManifestSchemaVersion(exportedManifest.manifestSchemaVersion()); @@ -108,6 +162,7 @@ public PublishedReleaseBundleDto createFullVersionBundle( entity.setCommandDefinitionsJson(serializeCommandDefinitions(commandDefinitions)); entity.setScriptOnly(version.scriptOnly()); entity.setScriptPatchVersion(version.scriptPatchVersion()); + if (worldEvidence != null) toDto(entity); return toDto(repository.save(entity)); } @@ -126,32 +181,44 @@ public Optional findPublishedReleaseBundle( } private PublishedReleaseBundleDto toDto(PublishedReleaseBundle entity) { - return new PublishedReleaseBundleDto( - entity.getId(), - entity.getTenantId(), - entity.getVersionId(), - entity.getVersionNumber(), - entity.getAttestationSchemaVersion(), - entity.getPublishWorkflowId(), - entity.getManifestHash(), - deserializeKeys(entity.getRequiredManifestAssetKeysJson()), - deserializeParticipantDigests(entity.getParticipantDigestsJson()), - deserializeCommandDefinitions(entity.getCommandDefinitionsJson()), - entity.getGenerationConfigRevision(), - entity.isScriptOnly(), - entity.getScriptPatchVersion(), - entity.getPublishedAt(), - entity.getCanonicalTenantId(), - entity.getCanonicalVersionId(), - entity.getPublishedReleaseBundleRef(), - entity.getManifestSchemaVersion(), - entity.getArtifactDigestsJson() == null - ? null - : objectMapper.readValue( - entity.getArtifactDigestsJson(), - objectMapper - .getTypeFactory() - .constructCollectionType(List.class, PublishedArtifactDigest.class))); + PublishedReleaseBundleDto dto = + new PublishedReleaseBundleDto( + entity.getId(), + entity.getTenantId(), + entity.getVersionId(), + entity.getVersionNumber(), + entity.getAttestationSchemaVersion(), + entity.getPublishWorkflowId(), + entity.getManifestHash(), + deserializeKeys(entity.getRequiredManifestAssetKeysJson()), + deserializeParticipantDigests(entity.getParticipantDigestsJson()), + deserializeCommandDefinitions(entity.getCommandDefinitionsJson()), + entity.getGenerationConfigRevision(), + entity.isScriptOnly(), + entity.getScriptPatchVersion(), + entity.getPublishedAt(), + entity.getCanonicalTenantId(), + entity.getCanonicalVersionId(), + entity.getPublishedReleaseBundleRef(), + entity.getManifestSchemaVersion(), + entity.getArtifactDigestsJson() == null + ? null + : objectMapper.readValue( + entity.getArtifactDigestsJson(), + objectMapper + .getTypeFactory() + .constructCollectionType(List.class, PublishedArtifactDigest.class)), + entity.getWorldPublishedStartLocationEvidenceJson() == null + ? null + : WorldPublishedStartLocationEvidence.fromStored( + entity + .getWorldPublishedStartLocationEvidenceJson() + .getBytes(StandardCharsets.UTF_8))); + if (PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION.equals( + dto.attestationSchemaVersion())) { + PublishedReleaseBundleContract.requireSelectorBinding(dto); + } + return dto; } private boolean isCanonicalNonNilUuid(UUID value) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java index 37c057e5f0..1de3dda72f 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java @@ -2,10 +2,12 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.LocalDateTime; +import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Optional; import net.firedevops.firemud.common.LoggingUtil; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; @@ -537,7 +539,7 @@ private void assertCommittedBundleMayMarkSuccess( "published release evidence is incomplete; readback/reconciliation is required"); } VersionDto versionDto = versionMapper.toDto(readback.version()); - PublishedReleaseBundleContract.requireSupportedSchemaForRead(readback.bundle()); + PublishedReleaseBundleContract.requireSupportedSchemaForPublicationRead(readback.bundle()); assertSelectedCommit(request, readback.bundle().participantDigests()); publishGateService.assertGatePassed(versionDto, readback.bundle().participantDigests()); recordedParticipantDigestService.assertMatchesRecordedDigests( @@ -744,7 +746,7 @@ private PublicationReadback readPublication( return PublicationReadback.partial(); } try { - PublishedReleaseBundleContract.requireSupportedSchemaForRead(bundle); + PublishedReleaseBundleContract.requireSupportedSchemaForPublicationRead(bundle); requireExactBundleEvidence(request, attempt, version.get(), bundle); requireExactArtifactEvidence(request, attempt, bundle, artifact); } catch (RuntimeException ex) { @@ -803,7 +805,12 @@ private void requireExactBundleEvidence( requireExactCommittedBundleIdentity(request, attempt, bundle); if (!Objects.equals(version.getTenantId(), bundle.tenantId()) || version.getVersionNumber() != bundle.versionNumber() - || version.isScriptOnly()) { + || version.isScriptOnly() + || (PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION.equals( + bundle.attestationSchemaVersion()) + && (!Objects.equals(version.getCanonicalTenantId(), bundle.canonicalTenantId()) + || !Objects.equals( + version.getCanonicalVersionId(), bundle.canonicalVersionId())))) { throw new IllegalStateException("PUBLISH_ATTEMPT_BUNDLE_SCOPE_MISMATCH"); } } @@ -818,6 +825,39 @@ private void requireExactCommittedBundleIdentity( || bundle.scriptPatchVersion() != null) { throw new IllegalStateException("PUBLISH_ATTEMPT_BUNDLE_SCOPE_MISMATCH"); } + if (PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION.equals( + bundle.attestationSchemaVersion())) { + PublishedReleaseBundleContract.requireSupportedSchemaForPublicationRead(bundle); + requireExactSelectedWorldEvidence(request, bundle); + } + } + + private void requireExactSelectedWorldEvidence( + PublishWorkflowRequest request, PublishedReleaseBundleDto bundle) { + // The stored owner payload is historical readback. It does not reconstruct a missing current + // owner freeze/Account permission producer or authorize another publication. + AuthoredDraftPublishSelection selected = requireSelectedIntent(request); + var evidence = bundle.worldPublishedStartLocationEvidence(); + var worldRequest = evidence.request(); + var account = DraftAuthorizationFenceBinding.fromStored(evidence.originalAccountBindingBytes()); + byte[] originalDraft = account.gameDesignBinding(); + if (!Arrays.equals(originalDraft, selected.selectedCommit().canonicalBytes()) + || !Arrays.equals(account.normalizedInput(), originalDraft) + || !selected.intent().selectedCommitDigest().equals(account.inputDigest()) + || !selected.intent().selectedCommitRequestId().equals(account.requestId()) + || !selected.intent().selectedCommitId().equals(account.commitId()) + || !selected.target().canonicalTenantId().equals(worldRequest.canonicalTenantId()) + || !selected.target().canonicalVersionId().equals(worldRequest.canonicalVersionId()) + || !selected.target().canonicalTenantId().equals(bundle.canonicalTenantId()) + || !selected.target().canonicalVersionId().equals(bundle.canonicalVersionId()) + || !selected.intent().publishRequestId().equals(worldRequest.publicationRequestId()) + || !request.publishWorkflowId().equals(worldRequest.publishWorkflowId()) + || !selected + .intent() + .expectedVersionStateEpoch() + .equals(Long.toString(worldRequest.versionStateEpoch()))) { + throw new IllegalStateException("PUBLISH_ATTEMPT_WORLD_SELECTION_MISMATCH"); + } } private void requireExactArtifactEvidence( diff --git a/services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql b/services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql new file mode 100644 index 0000000000..001c180d16 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql @@ -0,0 +1,235 @@ +-- Retained attestations keep their original schema and bytes; no selector is inferred or backfilled. +ALTER TABLE published_release_bundle + ADD COLUMN world_published_start_location_evidence_json TEXT; + +-- This adds an insertion guard beside (and does not replace) the existing immutable row/source guards. +-- Payload decoding checks storage relations, not authenticated World producer provenance. +-- [jooq ignore start] +-- The retained Account and World operation use big-endian byte-length frames. +CREATE FUNCTION published_world_selector_frame(payload BYTEA, wanted INTEGER) RETURNS BYTEA AS $$ +DECLARE + offset_bytes INTEGER := 0; + frame_index INTEGER := 0; + frame_length BIGINT; +BEGIN + WHILE offset_bytes < octet_length(payload) LOOP + IF offset_bytes + 4 > octet_length(payload) THEN + RAISE EXCEPTION 'truncated published World evidence frame' USING ERRCODE = 'check_violation'; + END IF; + frame_length := get_byte(payload, offset_bytes)::BIGINT * 16777216 + + get_byte(payload, offset_bytes + 1)::BIGINT * 65536 + + get_byte(payload, offset_bytes + 2)::BIGINT * 256 + get_byte(payload, offset_bytes + 3); + offset_bytes := offset_bytes + 4; + IF frame_length > octet_length(payload) - offset_bytes THEN + RAISE EXCEPTION 'invalid published World evidence frame length' USING ERRCODE = 'check_violation'; + END IF; + IF frame_index = wanted THEN + RETURN substring(payload FROM offset_bytes + 1 FOR frame_length::INTEGER); + END IF; + offset_bytes := offset_bytes + frame_length::INTEGER; + frame_index := frame_index + 1; + END LOOP; + RAISE EXCEPTION 'missing published World evidence frame' USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; + +CREATE FUNCTION enforce_published_world_start_location_evidence() RETURNS trigger AS $$ +DECLARE + evidence JSONB; + selection JSONB; + applied JSONB; + receipt JSONB; + participants JSONB; + item JSONB; + owner_key TEXT; + required_schema INTEGER; + field_name TEXT; + account_bytes BYTEA; + operation_bytes BYTEA; + draft JSONB; + affected JSONB; +BEGIN + IF NEW.attestation_schema_version <> 'v2' THEN + IF NEW.world_published_start_location_evidence_json IS NOT NULL THEN + RAISE EXCEPTION 'historical release schemas cannot carry a World selector' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.world_published_start_location_evidence_json IS NULL + OR NEW.script_only OR NEW.script_patch_version IS NOT NULL + OR NEW.canonical_tenant_id IS NULL OR NEW.canonical_version_id IS NULL + OR NEW.manifest_schema_version IS NULL OR NEW.artifact_digests_json IS NULL THEN + RAISE EXCEPTION 'release v2 requires complete full-Version selector evidence' + USING ERRCODE = 'check_violation'; + END IF; + evidence := NEW.world_published_start_location_evidence_json::JSONB; + selection := evidence->'request'; + FOR field_name IN SELECT unnest(ARRAY['targetNamespace','canonicalTenantId','canonicalVersionId', + 'intakeRequestId','publicationFence','publicationRequestId','requestDigest', + 'publishWorkflowId','appliedCommitId','contentDigest']) + LOOP + IF jsonb_typeof(selection->field_name) IS DISTINCT FROM 'string' + OR coalesce(selection->>field_name,'') = '' THEN + RAISE EXCEPTION 'release v2 has missing selection text binding' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + IF jsonb_typeof(evidence) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(evidence)) <> 5 + OR NOT evidence ?& ARRAY['schema','request','selectorReceiptBytesBase64', + 'originalAccountBindingBytesBase64','appliedResultBytesBase64'] + OR evidence->>'schema' IS DISTINCT FROM 'world-published-start-location-evidence/v1' + OR jsonb_typeof(selection) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(selection)) <> 13 + OR NOT selection ?& ARRAY['targetNamespace','canonicalTenantId','canonicalVersionId', + 'intakeRequestId','publicationFence','publicationRequestId','requestDigest', + 'versionStateEpoch','publishWorkflowId','appliedCommitId','contentDigest', + 'digestSchemaVersion','worldAffectedTuples'] + OR selection->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR selection->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR selection->>'publishWorkflowId' IS DISTINCT FROM NEW.publish_workflow_id + OR selection->>'targetNamespace' !~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + OR selection->>'intakeRequestId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'intakeRequestId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR selection->>'publicationFence' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'publicationFence')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR selection->>'appliedCommitId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'appliedCommitId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR coalesce(selection->>'publicationRequestId','') = '' + OR selection->>'requestDigest' !~ '^[0-9a-f]{64}$' + OR selection->>'contentDigest' !~ '^[0-9a-f]{64}$' + OR selection->>'versionStateEpoch' !~ '^[1-9][0-9]*$' + OR jsonb_typeof(selection->'versionStateEpoch') IS DISTINCT FROM 'number' + OR jsonb_typeof(selection->'digestSchemaVersion') IS DISTINCT FROM 'number' + OR selection->>'digestSchemaVersion' IS DISTINCT FROM '3' + OR jsonb_typeof(selection->'worldAffectedTuples') IS DISTINCT FROM 'array' THEN + RAISE EXCEPTION 'release v2 World selection has missing, unsupported or mismatched bindings' + USING ERRCODE = 'check_violation'; + END IF; + IF jsonb_array_length(selection->'worldAffectedTuples') = 0 THEN + RAISE EXCEPTION 'release v2 requires the complete World affected set' USING ERRCODE = 'check_violation'; + END IF; + -- Binary Account and APPLIED bytes remain intact; Java independently checks their full relation. + IF jsonb_typeof(evidence->'originalAccountBindingBytesBase64') IS DISTINCT FROM 'string' + OR octet_length(decode(evidence->>'originalAccountBindingBytesBase64','base64')) = 0 + OR jsonb_typeof(evidence->'appliedResultBytesBase64') IS DISTINCT FROM 'string' + OR jsonb_typeof(evidence->'selectorReceiptBytesBase64') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'release v2 requires complete original owner bytes' + USING ERRCODE = 'check_violation'; + END IF; + applied := convert_from(decode(evidence->>'appliedResultBytesBase64','base64'),'UTF8')::JSONB; + receipt := convert_from(decode(evidence->>'selectorReceiptBytesBase64','base64'),'UTF8')::JSONB; + FOR field_name IN SELECT unnest(ARRAY['selectorReceiptBytesBase64', + 'originalAccountBindingBytesBase64','appliedResultBytesBase64']) + LOOP + IF replace(encode(decode(evidence->>field_name,'base64'),'base64'), E'\n','') + IS DISTINCT FROM evidence->>field_name THEN + RAISE EXCEPTION 'release v2 owner bytes are not canonical base64' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + FOR field_name IN SELECT unnest(ARRAY['schema','status','operationBytesBase64','graphBytesBase64', + 'graphDigest','startLocationReceiptBase64','startLocationReceiptDigest']) + LOOP + IF jsonb_typeof(applied->field_name) IS DISTINCT FROM 'string' + OR coalesce(applied->>field_name,'') = '' THEN + RAISE EXCEPTION 'release v2 APPLIED result has missing bindings' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + FOR field_name IN SELECT unnest(ARRAY['schema','targetNamespace','operationId','requestId','commitId', + 'authorizationFenceId','accountBindingDigest','bindingDigest','graphDigest','receiptDigest']) + LOOP + IF jsonb_typeof(receipt->field_name) IS DISTINCT FROM 'string' + OR coalesce(receipt->>field_name,'') = '' THEN + RAISE EXCEPTION 'release v2 selector receipt has missing bindings' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + account_bytes := decode(evidence->>'originalAccountBindingBytesBase64','base64'); + operation_bytes := decode(applied->>'operationBytesBase64','base64'); + draft := convert_from(published_world_selector_frame(account_bytes, 11),'UTF8')::JSONB; + SELECT coalesce(jsonb_agg(unit ORDER BY unit->>'owner', unit->>'aggregateType', + unit->>'aggregateId', unit->>'scopeType', unit->>'scopeId', unit->>'expectedEpoch'),'[]'::JSONB) + INTO affected FROM jsonb_array_elements(draft->'affectedUnits') unit + WHERE unit->>'owner' = 'WORLD_MANAGEMENT'; + IF applied->>'schema' IS DISTINCT FROM 'world-draft-graph-applied/v2' + OR applied->>'status' IS DISTINCT FROM 'APPLIED' + OR applied->>'startLocationReceiptBase64' IS DISTINCT FROM evidence->>'selectorReceiptBytesBase64' + OR receipt->>'schema' IS DISTINCT FROM 'world-draft-start-location-receipt/v1' + OR receipt->>'targetNamespace' IS DISTINCT FROM selection->>'targetNamespace' + OR receipt->>'commitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR receipt->'startLocation'->>'tenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR receipt->'startLocation'->>'versionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR receipt->>'graphDigest' IS DISTINCT FROM applied->>'graphDigest' + OR receipt->>'receiptDigest' IS DISTINCT FROM applied->>'startLocationReceiptDigest' + OR jsonb_typeof(applied) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(applied)) <> 8 + OR NOT applied ?& ARRAY['schema','status','operationBytesBase64','graphBytesBase64', + 'graphDigest','startLocationReceiptBase64','startLocationReceiptDigest','appliedEpochs'] + OR jsonb_typeof(receipt) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(receipt)) <> 11 + OR NOT receipt ?& ARRAY['schema','targetNamespace','operationId','requestId','commitId', + 'authorizationFenceId','accountBindingDigest','bindingDigest','startLocation','graphDigest','receiptDigest'] + OR jsonb_typeof(receipt->'startLocation') IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(receipt->'startLocation')) <> 3 + OR NOT (receipt->'startLocation') ?& ARRAY['tenantId','versionId','roomTemplateId'] + OR selection->'worldAffectedTuples' IS DISTINCT FROM affected + OR draft->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR draft->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR draft->>'commitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR draft->'target'->>'gameDesignVersionRowId' IS DISTINCT FROM NEW.version_id::TEXT + OR draft->'target'->>'gameDesignVersionTenantKey' IS DISTINCT FROM NEW.tenant_id + OR published_world_selector_frame(account_bytes, 11) IS DISTINCT FROM published_world_selector_frame(account_bytes, 12) + OR published_world_selector_frame(operation_bytes, 7) IS DISTINCT FROM published_world_selector_frame(account_bytes, 11) + OR convert_from(published_world_selector_frame(account_bytes, 13),'UTF8') IS DISTINCT FROM receipt->>'bindingDigest' + OR receipt->>'accountBindingDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(account_bytes),'hex') + OR applied->>'graphDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(decode(applied->>'graphBytesBase64','base64')),'hex') + OR convert_from(published_world_selector_frame(account_bytes, 0),'UTF8') IS DISTINCT FROM 'account-draft-authorization-fence/v1' + OR convert_from(published_world_selector_frame(account_bytes, 1),'UTF8') IS DISTINCT FROM receipt->>'operationId' + OR convert_from(published_world_selector_frame(account_bytes, 2),'UTF8') IS DISTINCT FROM receipt->>'requestId' + OR convert_from(published_world_selector_frame(account_bytes, 3),'UTF8') IS DISTINCT FROM selection->>'appliedCommitId' + OR convert_from(published_world_selector_frame(account_bytes, 4),'UTF8') IS DISTINCT FROM receipt->>'authorizationFenceId' + OR convert_from(published_world_selector_frame(account_bytes, 6),'UTF8') IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR convert_from(published_world_selector_frame(account_bytes, 7),'UTF8') IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR convert_from(published_world_selector_frame(operation_bytes, 0),'UTF8') IS DISTINCT FROM 'world-draft-terminal-operation/v1' + OR published_world_selector_frame(operation_bytes, 20) IS DISTINCT FROM account_bytes + OR convert_from(published_world_selector_frame(operation_bytes, 13),'UTF8') IS DISTINCT FROM selection->>'intakeRequestId' + OR convert_from(published_world_selector_frame(operation_bytes, 8),'UTF8') IS DISTINCT FROM selection->>'targetNamespace' + OR convert_from(published_world_selector_frame(operation_bytes, 9),'UTF8') IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR convert_from(published_world_selector_frame(operation_bytes, 10),'UTF8') IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR receipt->'startLocation'->>'roomTemplateId' IS NULL THEN + RAISE EXCEPTION 'release v2 selector differs from original selected APPLIED receipt' + USING ERRCODE = 'check_violation'; + END IF; + participants := NEW.participant_digests_json::JSONB; + IF jsonb_typeof(participants) IS DISTINCT FROM 'array' OR jsonb_array_length(participants) <> 5 THEN + RAISE EXCEPTION 'release v2 requires all five participant owners' USING ERRCODE = 'check_violation'; + END IF; + FOR owner_key, required_schema IN SELECT * FROM (VALUES + ('WORLD_MANAGEMENT',3),('ENTITY_MANAGEMENT',2),('GAME_LOGIC',1), + ('AUTOMATION_SCRIPTING',5),('GAME_DESIGN_CONTROL_PLANE',1)) owners(owner_key, required_schema) + LOOP + IF (SELECT count(*) FROM jsonb_array_elements(participants) p + WHERE p->>'participantKey' = owner_key) <> 1 THEN + RAISE EXCEPTION 'release v2 has missing or duplicate participant owner' USING ERRCODE = 'check_violation'; + END IF; + SELECT p INTO item FROM jsonb_array_elements(participants) p WHERE p->>'participantKey' = owner_key; + IF item->>'scopeValue' IS DISTINCT FROM NEW.version_id::TEXT + OR item->>'baseVersionId' IS NOT NULL + OR item->>'appliedCommitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR item->>'digestSchemaVersion' IS DISTINCT FROM required_schema::TEXT + OR coalesce(item->>'contentDigest','') !~ '^[0-9a-f]{64}$' + OR coalesce(item->>'errorCode','') <> '' + OR (owner_key = 'WORLD_MANAGEMENT' AND item->>'contentDigest' IS DISTINCT FROM selection->>'contentDigest') + OR (owner_key = 'GAME_LOGIC' AND coalesce(item->>'abilitySchemaDigest','') !~ '^sha256:[0-9a-f]{64}$') THEN + RAISE EXCEPTION 'release v2 participant differs from selected commit/digest/schema' + USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_published_world_start_location_evidence + BEFORE INSERT ON published_release_bundle + FOR EACH ROW EXECUTE FUNCTION enforce_published_world_start_location_evidence(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepositoryIntegrationTest.java index 9f94e095f5..7e2c860a31 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepositoryIntegrationTest.java @@ -113,7 +113,9 @@ void v45PreservesRetainedAttemptDigestsAndStoresExactSelectionDigest() { Map>> coordinatorBeforeLatest = retainedCoordinatorRows(retained); migrate(retained.dataSource(), retained.schema(), null); - assertThat(retainedCoordinatorRows(retained)).isEqualTo(coordinatorBeforeLatest); + assertThat(retainedCoordinatorRows(retained)) + .usingRecursiveComparison() + .isEqualTo(coordinatorBeforeLatest); assertThat( retained.dsl().fetchCount(DSL.table(DSL.name("game_design_draft_terminal_operation")))) .isZero(); @@ -186,7 +188,9 @@ void v44PreservesExactSelectionsRetainedAtV43() { Map>> coordinatorBeforeLatest = retainedCoordinatorRows(retained); migrate(retained.dataSource(), retained.schema(), null); - assertThat(retainedCoordinatorRows(retained)).isEqualTo(coordinatorBeforeLatest); + assertThat(retainedCoordinatorRows(retained)) + .usingRecursiveComparison() + .isEqualTo(coordinatorBeforeLatest); assertThat( retained.dsl().fetchCount(DSL.table(DSL.name("game_design_draft_terminal_operation")))) @@ -205,8 +209,6 @@ void v44RejectsConflictingRetainedRequestAcrossVersionsWithoutDiscardingEitherHi DraftCommitBinding firstCommit = binding(first.target(), UUID.randomUUID(), UUID.randomUUID()); DraftCommitBinding secondCommit = binding(second.target(), UUID.randomUUID(), UUID.randomUUID()); - retained.synchronize(firstCommit); - retained.synchronize(secondCommit); PublishIntent firstIntent = intent(first, firstCommit, "first retained history"); PublishIntent secondIntent = sameRequestIntent(second, secondCommit, firstIntent.publishRequestId()); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java index 222c5e985b..0b7d6ce70b 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java @@ -3,10 +3,14 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.nio.charset.StandardCharsets; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.config.PostgresProperties; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.entity.Version; @@ -14,6 +18,7 @@ import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; @@ -33,6 +38,7 @@ import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; @Testcontainers(disabledWithoutDocker = true) class PublishedReleaseCanonicalIdentityIntegrationTest { @@ -132,6 +138,17 @@ void migrationLeavesRetainedReleaseTupleAndXminUnchangedAndUnmapped() { assertThat(row.get(MANIFEST_SCHEMA_VERSION)).isNull(); assertThat(row.get(ARTIFACT_DIGESTS_JSON)).isNull(); }); + migrate(fixture.dataSource(), fixture.schema(), null); + assertThat(retainedTuple(fixture.dsl(), retainedBundleId)).isEqualTo(retainedTupleBefore); + assertThat(bundleXmin(fixture.dsl(), retainedBundleId)).isEqualTo(retainedXminBefore); + assertThat( + fixture + .dsl() + .fetchOne( + "SELECT world_published_start_location_evidence_json FROM published_release_bundle WHERE id = ?", + retainedBundleId) + .get(0)) + .isNull(); PublishedReleaseBundle retained = fixture .releaseBundleRepository() @@ -157,7 +174,7 @@ void migrationLeavesRetainedReleaseTupleAndXminUnchangedAndUnmapped() { @Test void normalSavePersistsExactVersionAndVerifiedGameIdentityAndReadsBackWithinTransaction() { - Fixture fixture = fixture(V38); + Fixture fixture = fixture(null); Game owner = saveGame(fixture, "fresh-release-source"); Game other = saveGame(fixture, "other-release-source"); Version version = saveVersion(fixture, owner); @@ -210,7 +227,7 @@ void normalSavePersistsExactVersionAndVerifiedGameIdentityAndReadsBackWithinTran @Test void repositoryNestedTransactionRollsBackWithOuterSpringPublisherTransaction() { - Fixture fixture = fixture(V38); + Fixture fixture = fixture(null); Game owner = saveGame(fixture, "outer-release-rollback-owner"); Version version = saveVersion(fixture, owner); String versionXminBefore = versionXmin(fixture.dsl(), version.getId()); @@ -280,7 +297,7 @@ void repositoryNestedTransactionRollsBackWithOuterSpringPublisherTransaction() { @Test void deniesWrongTenantNilAndSubstitutedCallerOrDatabaseIdentityWithoutGrowingBundles() { - Fixture fixture = fixture(V38); + Fixture fixture = fixture(null); Game owner = saveGame(fixture, "denied-release-owner"); Game other = saveGame(fixture, "denied-release-other"); Version version = saveVersion(fixture, owner); @@ -408,6 +425,9 @@ void bundleIdentityIsImmutableRetainedNullCannotBeBackfilledAndMetadataCannotBeD }); Version mappedVersion = saveVersion(fixture, game); + migrate(fixture.dataSource(), fixture.schema(), null); + assertThat(retainedTuple(fixture.dsl(), retainedBundleId)).isEqualTo(retainedTupleBeforeV38); + assertThat(bundleXmin(fixture.dsl(), retainedBundleId)).isEqualTo(retainedXminBeforeV38); PublishedReleaseBundle mapped = fixture.releaseBundleRepository().save(bundle(game.getTenantId(), mappedVersion.getId())); Map mappedTupleBefore = releaseBundleTuple(fixture.dsl(), mapped.getId()); @@ -549,6 +569,203 @@ void bundleIdentityIsImmutableRetainedNullCannotBeBackfilledAndMetadataCannotBeD assertThat(bundleCount(fixture.dsl())).isEqualTo(2); } + @Test + void selectorV2RetainsCompleteOriginalEvidenceAndExactlyReplaysWithoutReplacingRelease() + throws Exception { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "selector-release-source"); + Version version = saveVersion(fixture, owner); + WorldPublishedStartLocationEvidence evidence = selectorEvidence(version); + PublishedReleaseBundle requested = selectorBundle(version, evidence); + PublishedReleaseBundle saved = fixture.releaseBundleRepository().save(requested); + String beforeXmin = bundleXmin(fixture.dsl(), saved.getId()); + String original = new String(evidence.canonicalBytes(), StandardCharsets.UTF_8); + assertThat(saved.getWorldPublishedStartLocationEvidenceJson()).isEqualTo(original); + PublishedReleaseBundle independent = + new PublishedReleaseBundleRepository(fixture.dsl()) + .findByTenantIdAndVersionId(owner.getTenantId(), version.getId()) + .orElseThrow(); + assertThat( + WorldPublishedStartLocationEvidence.fromStored( + independent + .getWorldPublishedStartLocationEvidenceJson() + .getBytes(StandardCharsets.UTF_8)) + .canonicalBytes()) + .containsExactly(evidence.canonicalBytes()); + assertThat(fixture.releaseBundleRepository().save(selectorBundle(version, evidence))) + .usingRecursiveComparison() + .isEqualTo(saved); + assertThat(bundleXmin(fixture.dsl(), saved.getId())).isEqualTo(beforeXmin); + + PublishedReleaseBundle changed = selectorBundle(version, evidence); + changed.setGenerationConfigRevision("changed-generation"); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(changed)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE published_release_bundle SET world_published_start_location_evidence_json = NULL WHERE id = ?", + saved.getId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute("DELETE FROM published_release_bundle WHERE id = ?", saved.getId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("retained"); + assertThat(bundleXmin(fixture.dsl(), saved.getId())).isEqualTo(beforeXmin); + assertThat(bundleCount(fixture.dsl())).isEqualTo(1); + } + + @Test + void concurrentExactSelectorRetriesCommitOneImmutableBundle() throws Exception { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "selector-concurrent-source"); + Version version = saveVersion(fixture, owner); + var evidence = selectorEvidence(version); + var start = new java.util.concurrent.CountDownLatch(1); + try (var executor = java.util.concurrent.Executors.newFixedThreadPool(2)) { + java.util.concurrent.Callable save = + () -> { + start.await(); + return new PublishedReleaseBundleRepository(fixture.dsl()) + .save(selectorBundle(version, evidence)); + }; + var first = executor.submit(save); + var second = executor.submit(save); + start.countDown(); + var one = first.get(20, java.util.concurrent.TimeUnit.SECONDS); + var two = second.get(20, java.util.concurrent.TimeUnit.SECONDS); + assertThat(two).usingRecursiveComparison().isEqualTo(one); + assertThat(bundleCount(fixture.dsl())).isEqualTo(1); + } + } + + @Test + void sqlGuardRejectsMissingInjectedAndMismatchedSelectorBindingsWithoutAnyRelease() + throws Exception { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "selector-denial-source"); + Version version = saveVersion(fixture, owner); + WorldPublishedStartLocationEvidence evidence = selectorEvidence(version); + var json = new ObjectMapper(); + String original = new String(evidence.canonicalBytes(), StandardCharsets.UTF_8); + String participants = + json.writeValueAsString( + PublishedWorldSelectorFixtures.participants(version.getId(), evidence)); + assertThatThrownBy(() -> insertRawSelector(fixture, version, "v2", null, participants)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> insertRawSelector(fixture, version, "v1", original, participants)) + .isInstanceOf(DataAccessException.class); + for (String field : + List.of( + "canonicalTenantId", + "canonicalVersionId", + "publishWorkflowId", + "appliedCommitId", + "contentDigest", + "digestSchemaVersion", + "intakeRequestId")) { + var root = (tools.jackson.databind.node.ObjectNode) json.readTree(original); + var request = (tools.jackson.databind.node.ObjectNode) root.get("request"); + if (field.equals("digestSchemaVersion")) request.put(field, 2); + else + request.put( + field, + field.endsWith("Id") || field.equals("publicationFence") + ? UUID.randomUUID().toString() + : "changed"); + assertThatThrownBy( + () -> + insertRawSelector( + fixture, version, "v2", json.writeValueAsString(root), participants)) + .isInstanceOf(DataAccessException.class); + } + for (String field : + List.of( + "selectorReceiptBytesBase64", + "originalAccountBindingBytesBase64", + "appliedResultBytesBase64")) { + var root = (tools.jackson.databind.node.ObjectNode) json.readTree(original); + root.remove(field); + assertThatThrownBy( + () -> + insertRawSelector( + fixture, version, "v2", json.writeValueAsString(root), participants)) + .isInstanceOf(DataAccessException.class); + } + assertThatThrownBy(() -> insertRawSelector(fixture, version, "v2", original, "[]")) + .isInstanceOf(DataAccessException.class); + var changedParticipants = (tools.jackson.databind.node.ArrayNode) json.readTree(participants); + ((tools.jackson.databind.node.ObjectNode) changedParticipants.get(0)) + .put("contentDigest", "c".repeat(64)); + assertThatThrownBy( + () -> + insertRawSelector( + fixture, version, "v2", original, json.writeValueAsString(changedParticipants))) + .isInstanceOf(DataAccessException.class); + assertThat(bundleCount(fixture.dsl())).isZero(); + insertRawSelector(fixture, version, "v2", original, participants); + assertThat( + new PublishedReleaseBundleRepository(fixture.dsl()) + .findByTenantIdAndVersionId(version.getTenantId(), version.getId()) + .orElseThrow() + .getWorldPublishedStartLocationEvidenceJson()) + .isEqualTo(original); + } + + private WorldPublishedStartLocationEvidence selectorEvidence(Version version) throws Exception { + return PublishedWorldSelectorFixtures.evidence( + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind())); + } + + private PublishedReleaseBundle selectorBundle( + Version version, WorldPublishedStartLocationEvidence evidence) { + PublishedReleaseBundle bundle = bundle(version.getTenantId(), version.getId()); + bundle.setAttestationSchemaVersion("v2"); + bundle.setPublishWorkflowId(evidence.request().publishWorkflowId()); + bundle.setParticipantDigestsJson( + new ObjectMapper() + .writeValueAsString( + PublishedWorldSelectorFixtures.participants(version.getId(), evidence))); + bundle.setWorldPublishedStartLocationEvidenceJson( + new String(evidence.canonicalBytes(), StandardCharsets.UTF_8)); + return bundle; + } + + private void insertRawSelector( + Fixture fixture, Version version, String schema, String evidence, String participants) { + fixture + .dsl() + .execute( + "INSERT INTO published_release_bundle (tenant_id, version_id, version_number, " + + "canonical_tenant_id, canonical_version_id, published_release_bundle_ref, attestation_schema_version, " + + "publish_workflow_id, manifest_hash, manifest_schema_version, artifact_digests_json, " + + "required_manifest_asset_keys_json, participant_digests_json, command_definitions_json, script_only, " + + "world_published_start_location_evidence_json) VALUES (?, ?, 1, ?, ?, ?, ?, 'publish-workflow', ?, 1, '[]', '[]', ?, '[]', FALSE, ?)", + version.getTenantId(), + version.getId(), + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + UUID.randomUUID().toString(), + schema, + MANIFEST_HASH, + participants, + evidence); + } + private Fixture fixture(MigrationVersion target) { String schema = "game_design_release_identity_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = dataSource(schema); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java index a9a267fc4d..755f6ce80a 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java @@ -3,14 +3,18 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.DriverManager; import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; class PublishedReleaseBundleRepositoryTest { private static final UUID TENANT_UUID = UUID.fromString("11111111-1111-4111-8111-111111111111"); @@ -18,6 +22,57 @@ class PublishedReleaseBundleRepositoryTest { private static final UUID OTHER_UUID = UUID.fromString("33333333-3333-4333-8333-333333333333"); private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + @Test + void selectorEvidenceRequiresExactSourceAndReadbackPreservesOriginalBytes() throws Exception { + try (Fixture fixture = fixture()) { + insertGame(fixture.dsl(), 7L, "tenant-key", TENANT_UUID, 7L, "tenant-key", "NEW_GAME_ROW"); + insertVersion( + fixture.dsl(), + 17L, + "tenant-key", + TENANT_UUID, + VERSION_UUID, + 7L, + "tenant-key", + "NEW_GAME_ROW"); + var evidence = + PublishedWorldSelectorFixtures.evidence( + new TargetProof( + TENANT_UUID, VERSION_UUID, 17L, "tenant-key", 7L, "tenant-key", "NEW_GAME_ROW")); + PublishedReleaseBundle requested = bundle("tenant-key", 17L); + requested.setAttestationSchemaVersion("v2"); + requested.setPublishWorkflowId(evidence.request().publishWorkflowId()); + assertThatThrownBy(() -> fixture.repository().save(requested)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mandatory"); + requested.setWorldPublishedStartLocationEvidenceJson( + new String(evidence.canonicalBytes(), StandardCharsets.UTF_8)); + requested.setPublishWorkflowId("other-workflow"); + assertThatThrownBy(() -> fixture.repository().save(requested)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("source/workflow"); + requested.setPublishWorkflowId(evidence.request().publishWorkflowId()); + requested.setParticipantDigestsJson( + new ObjectMapper() + .writeValueAsString(PublishedWorldSelectorFixtures.participants(17L, evidence))); + var saved = fixture.repository().save(requested); + assertThat(saved.getWorldPublishedStartLocationEvidenceJson()) + .isEqualTo(requested.getWorldPublishedStartLocationEvidenceJson()); + assertThat( + new PublishedReleaseBundleRepository(fixture.dsl()) + .findByTenantIdAndVersionId("tenant-key", 17L) + .orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(saved); + assertThat(fixture.repository().save(requested)).usingRecursiveComparison().isEqualTo(saved); + requested.setParticipantDigestsJson("[]"); + assertThatThrownBy(() -> fixture.repository().save(requested)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + assertThat(fixture.bundleCount()).isEqualTo(1); + } + } + @Test void newBundleUsesExactPersistedVersionAndGameIdentityAndReadsItBack() throws Exception { try (Fixture fixture = fixture()) { @@ -156,6 +211,7 @@ private static Fixture fixture() throws Exception { + "required_manifest_asset_keys_json CLOB NOT NULL, " + "participant_digests_json CLOB NOT NULL, command_definitions_json CLOB NOT NULL, " + "manifest_schema_version INT, artifact_digests_json CLOB, " + + "world_published_start_location_evidence_json CLOB, " + "script_only BOOLEAN NOT NULL, script_patch_version VARCHAR(100), " + "published_at TIMESTAMP NOT NULL)"); return new Fixture(connection, dsl, new PublishedReleaseBundleRepository(dsl)); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java index 3afb1d2d54..3917711ae3 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java @@ -35,6 +35,56 @@ import org.springframework.test.util.ReflectionTestUtils; class CompleteLaunchBindingServiceImplTest { + @Test + void selectorReleaseIsAssembledFromImmutableLocalBundleWithoutMutableOwnerReads() + throws Exception { + var selector = + PublishedWorldSelectorFixtures.evidence( + new net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_ID, + PRIVATE_TENANT_KEY, + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind())); + var selected = + new PublishedReleaseBundleDto( + bundle.id(), + bundle.tenantId(), + bundle.versionId(), + bundle.versionNumber(), + "v2", + selector.request().publishWorkflowId(), + bundle.manifestHash(), + bundle.requiredManifestAssetKeys(), + PublishedWorldSelectorFixtures.participants(VERSION_ID, selector), + bundle.commandDefinitions(), + bundle.generationConfigRevision(), + bundle.scriptOnly(), + bundle.scriptPatchVersion(), + bundle.publishedAt(), + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.publishedReleaseBundleRef(), + bundle.manifestSchemaVersion(), + bundle.artifactDigests(), + selector); + givenBundle(selected); + var result = + service.getCompleteLaunchBinding( + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + CONTROL_PLANE_REQUEST_ID, + descriptor.requestDigest(), + descriptor.resultDigest()); + assertEquals(2, result.releaseAttestation().schemaVersion()); + assertEquals(selector, result.releaseAttestation().worldStartLocationEvidence()); + result.releaseAttestation().requireValid(descriptor); + verifyReadOnlyCallsOnly(); + } + private static final String NAMESPACE = "test"; private static final UUID READ_REQUEST_ID = UUID.fromString("72345678-1234-4234-8234-123456789abc"); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java index 6d51a192d8..378f8aa1c8 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java @@ -18,9 +18,11 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; 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.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.TemplateRemapSetDto; import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; @@ -68,6 +70,76 @@ class LaunchDescriptorServiceImplTest { private LaunchDescriptorServiceImpl service; + @Test + void completeSelectorV2ResolvesTheUnchangedDescriptorV1Binding() throws Exception { + var request = request("cp-selector-v2", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + var bundle = selectorBundle(false); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) + .thenReturn(bundle); + + var resolved = service.resolveLaunchDescriptor(request); + + assertEquals(7L, resolved.versionId()); + assertEquals(11L, resolved.releaseBundleId()); + assertEquals(PUBLISHED_RELEASE_BUNDLE_REF, resolved.publishedReleaseBundleRef()); + assertEquals( + AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION, + resolved.authoredWorldBinding().schemaVersion()); + assertEquals(request.requestDigest(), resolved.authoredWorldBinding().requestDigest()); + assertEquals(17L, resolved.versionStateEpoch()); + verify(launchDescriptorRepository).insertImmutable(any(LaunchDescriptor.class)); + } + + @Test + void selectorV2WithoutCompleteParticipantProofCannotResolveOrFreezeSyntheticSuccess() + throws Exception { + var request = request("cp-incomplete-selector-v2", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) + .thenReturn(selectorBundle(true)); + + assertThrows(IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); + } + + private PublishedReleaseBundleDto selectorBundle(boolean omitParticipant) throws Exception { + // Stipulated original component bytes; this fixture does not authenticate a producer or admit + // gameplay. + WorldPublishedStartLocationEvidence evidence = + PublishedWorldSelectorFixtures.evidence( + new TargetProof( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + 7L, + PRIVATE_SOURCE_TENANT_KEY, + 1L, + PRIVATE_SOURCE_TENANT_KEY, + "NEW_GAME_ROW")); + var participants = PublishedWorldSelectorFixtures.participants(7L, evidence); + return new PublishedReleaseBundleDto( + 11L, + PRIVATE_SOURCE_TENANT_KEY, + 7L, + 8, + "v2", + evidence.request().publishWorkflowId(), + MANIFEST_HASH, + List.of(), + omitParticipant ? participants.subList(0, 4) : participants, + List.of(), + "genrev-1", + false, + null, + LocalDateTime.now(), + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + PUBLISHED_RELEASE_BUNDLE_REF, + 1, + List.of(), + evidence); + } + @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); @@ -456,7 +528,7 @@ void resolveLaunchDescriptorFailsClosedOnUnsupportedAttestationSchema() { stubSource(request, sourceEvidence(WORLD_SLUG)); stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) - .thenReturn(releaseBundle(7L, 11L, "v2")); + .thenReturn(releaseBundle(7L, 11L, "v999")); IllegalArgumentException thrown = assertThrows( diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java index 5aa68e052e..f2479067bb 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java @@ -2,16 +2,21 @@ import static net.firedevops.firemud.gamedesign.service.impl.CommandDefinitionFixtures.commandDefinition; import static net.firedevops.firemud.gamedesign.service.impl.CommandDefinitionFixtures.validCommandDefinition; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; +import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; @@ -39,6 +44,188 @@ class PublishedReleaseBundleServiceImplTest { private PublishedReleaseBundleServiceImpl service; + @Test + void selectorV2PersistsActualOriginalBytesAndRetryReturnsStoredEvidenceWithoutResolvingDefaults() + throws Exception { + var evidence = selectorEvidence(); + var participants = PublishedWorldSelectorFixtures.participants(7L, evidence); + when(repository.save(any(PublishedReleaseBundle.class))) + .thenAnswer( + invocation -> { + PublishedReleaseBundle saved = invocation.getArgument(0); + saved.setId(11L); + saved.setPublishedReleaseBundleRef("owner-release"); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)) + .thenReturn(Optional.of(saved)); + return saved; + }); + var first = + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + participants, + evidence); + assertEquals("v2", first.attestationSchemaVersion()); + assertThat(first.worldPublishedStartLocationEvidence().canonicalBytes()) + .containsExactly(evidence.canonicalBytes()); + org.mockito.Mockito.clearInvocations(versionRepository, revisionRepository, repository); + when(versionRepository.findByTenantIdAndId("tenant-1", 7L)).thenReturn(Optional.empty()); + var retry = + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + participants, + WorldPublishedStartLocationEvidence.fromStored(evidence.canonicalBytes())); + assertEquals(first.id(), retry.id()); + assertThat(retry.worldPublishedStartLocationEvidence().canonicalBytes()) + .containsExactly(first.worldPublishedStartLocationEvidence().canonicalBytes()); + org.mockito.Mockito.verifyNoInteractions(versionRepository, revisionRepository); + org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "changed", + participants, + evidence)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + assertThatThrownBy(() -> PublishedReleaseBundleContract.requireSupportedSchemaForLaunch(first)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("SCHEMA_VERSION_UNSUPPORTED"); + assertThatThrownBy( + () -> PublishedReleaseBundleContract.requireExactRepairMatch(first, emptyManifest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("SCHEMA_VERSION_UNSUPPORTED"); + } + + @Test + void selectorV2RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChangedWorldDigest() + throws Exception { + var evidence = selectorEvidence(); + var participants = PublishedWorldSelectorFixtures.participants(7L, evidence); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + participants, + null)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "wrong-workflow", + emptyManifest(), + "genrev-1", + participants, + evidence)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + participants.subList(0, 4), + evidence)) + .isInstanceOf(IllegalArgumentException.class); + var world = participants.getFirst(); + var changed = new java.util.ArrayList<>(participants); + changed.set( + 0, + new PublishParticipantDigestDto( + world.participantKey(), + world.scopeValue(), + null, + world.appliedCommitId(), + "e".repeat(64), + 3, + null, + null, + null)); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + changed, + evidence)) + .isInstanceOf(IllegalArgumentException.class); + org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); + } + + @Test + void historicalReleaseNeverGainsSelectorAndCorruptedStoredCarrierFailsReadback() + throws Exception { + PublishedReleaseBundle retained = new PublishedReleaseBundle(); + retained.setAttestationSchemaVersion("v1"); + retained.setTenantId("tenant-1"); + retained.setVersionId(7L); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(retained)); + assertNull( + service.getPublishedReleaseBundle("tenant-1", 7L).worldPublishedStartLocationEvidence()); + var evidence = selectorEvidence(); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + PublishedWorldSelectorFixtures.participants(7L, evidence), + evidence)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("selector-ineligible"); + retained.setWorldPublishedStartLocationEvidenceJson( + new String(evidence.canonicalBytes(), StandardCharsets.UTF_8)); + assertThatThrownBy(() -> service.getPublishedReleaseBundle("tenant-1", 7L)) + .isInstanceOf(IllegalArgumentException.class); + retained.setAttestationSchemaVersion("v2"); + retained.setWorldPublishedStartLocationEvidenceJson("{}"); + assertThatThrownBy(() -> service.getPublishedReleaseBundle("tenant-1", 7L)) + .isInstanceOf(IllegalArgumentException.class); + } + + private WorldPublishedStartLocationEvidence selectorEvidence() throws Exception { + return PublishedWorldSelectorFixtures.evidence( + new TargetProof( + sourceIdentity().getCanonicalTenantId(), + sourceIdentity().getCanonicalVersionId(), + 7L, + "tenant-1", + 42L, + "tenant-1", + "NEW_GAME_ROW")); + } + + private VersionDto selectorVersion() { + return new VersionDto( + 7L, + "tenant-1", + 8, + VersionLifecycleState.PUBLISHED, + 2L, + null, + null, + false, + "notes", + LocalDateTime.now(), + LocalDateTime.now()); + } + @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java new file mode 100644 index 0000000000..566327ef2d --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java @@ -0,0 +1,406 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; + +/** Stipulated original Account/APPLIED component bytes; no live producer/currentness proof. */ +public final class PublishedWorldSelectorFixtures { + private final TargetProof target; + + private PublishedWorldSelectorFixtures(TargetProof target) { + this.target = target; + this.TENANT_ID = target.canonicalTenantId(); + this.VERSION_ID = target.canonicalVersionId(); + } + + public static WorldPublishedStartLocationEvidence evidence(TargetProof target) throws Exception { + return new PublishedWorldSelectorFixtures(target).build(); + } + + public static List + participants(long versionId, WorldPublishedStartLocationEvidence evidence) { + return net + .firedevops + .firemud + .common + .gamedesign + .AuthoredWorldReleaseAttestationEvidence + .requiredParticipantOrder() + .stream() + .map( + owner -> + new net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto( + owner, + Long.toString(versionId), + null, + evidence.request().appliedCommitId(), + "WORLD_MANAGEMENT".equals(owner) + ? evidence.request().contentDigest() + : "c".repeat(64), + net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence + .supportedParticipantDigestSchema(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null, + null, + null)) + .toList(); + } + + private WorldPublishedStartLocationEvidence build() throws Exception { + var draft = freshGraphBinding(); + var terminal = WorldDraftTerminalReadEvidence.Request.create("test", accountBinding(draft)); + var result = committedReadback(terminal, true); + var applied = JSON.readTree(result.result()); + var tuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + u -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + u.owner().name(), + u.aggregateType(), + u.aggregateId(), + u.scopeType(), + u.scopeId(), + u.expectedEpoch())) + .toList(); + var request = + new WorldPublishedStartLocationEvidence.Request( + "test", + TENANT_ID, + VERSION_ID, + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "publication-request", + "a".repeat(64), + 5L, + "publish-workflow", + draft.commitId().toString(), + "b".repeat(64), + 3, + tuples); + return new WorldPublishedStartLocationEvidence( + request, + Base64.getDecoder().decode(applied.get("startLocationReceiptBase64").textValue()), + result.fullBinding(), + result.result()); + } + + private final UUID OPERATION_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private final UUID REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + private final UUID FENCE_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private final UUID ACTOR_ID = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private final UUID TENANT_ID; + private final UUID VERSION_ID; + private final UUID REVISION_ID = uuid("66666666-6666-4666-8666-666666666666"); + private final UUID REGION_TEMPLATE_ID = uuid("88888888-8888-4888-8888-888888888888"); + private final UUID ZONE_TEMPLATE_ID = uuid("99999999-9999-4999-8999-999999999999"); + private final UUID ROOM_TEMPLATE_ID = uuid("77777777-7777-4777-8777-777777777777"); + private final UUID REGION_REVISION_ID = uuid("12345678-1234-4234-8234-123456789001"); + private final UUID ZONE_REVISION_ID = uuid("12345678-1234-4234-8234-123456789002"); + private final UUID ROOM_REVISION_ID = uuid("12345678-1234-4234-8234-123456789003"); + private final tools.jackson.databind.ObjectMapper JSON = + new tools.jackson.databind.ObjectMapper(); + + private DraftAuthorizationFenceBinding.OwnerReadback committedReadback( + WorldDraftTerminalReadEvidence.Request request, boolean freshGraph) throws Exception { + var account = request.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + var operation = new ByteArrayOutputStream(); + var frames = new java.io.DataOutputStream(operation); + java.util.function.Consumer frame = + bytes -> { + try { + frames.writeInt(bytes.length); + frames.write(bytes); + } catch (java.io.IOException impossible) { + throw new AssertionError(impossible); + } + }; + java.util.function.Consumer text = + value -> frame.accept(value.getBytes(StandardCharsets.UTF_8)); + text.accept("world-draft-terminal-operation/v1"); + for (UUID id : + List.of( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId())) text.accept(id.toString()); + frame.accept(draft.canonicalBytes()); + for (String value : + List.of( + request.targetNamespace(), + account.tenantId().toString(), + account.versionId().toString(), + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + Long.toString(draft.target().gameDesignVersionRowId()), + "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "cccccccc-cccc-4ccc-8ccc-cccccccccccc", + "a".repeat(64), + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + "b".repeat(64), + "c".repeat(64))) text.accept(value); + text.accept(sha256(account.canonicalBytes())); + frame.accept(account.canonicalBytes()); + byte[] graph = freshGraph ? graphBytes(request, draft) : historicalGraphBytes(account); + String graphDigest = sha256(graph); + var result = new java.util.LinkedHashMap(); + result.put( + "schema", freshGraph ? "world-draft-graph-applied/v2" : "world-draft-graph-applied/v1"); + result.put("status", "APPLIED"); + result.put("operationBytesBase64", Base64.getEncoder().encodeToString(operation.toByteArray())); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(graph)); + result.put("graphDigest", graphDigest); + if (freshGraph) { + var receipt = receipt(request, draft, graphDigest); + byte[] receiptBytes = canonical(receipt); + result.put("startLocationReceiptBase64", Base64.getEncoder().encodeToString(receiptBytes)); + result.put("startLocationReceiptDigest", receipt.get("receiptDigest").textValue()); + } + result.put( + "appliedEpochs", + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + Map.of( + "aggregateType", + unit.aggregateType(), + "aggregateId", + unit.aggregateId(), + "scopeType", + unit.scopeType(), + "scopeId", + unit.scopeId(), + "expectedEpoch", + unit.expectedEpoch(), + "resultingEpoch", + new java.math.BigInteger(unit.expectedEpoch()) + .add(java.math.BigInteger.ONE) + .toString())) + .toList()); + return new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + account.operationId(), + account.commitId(), + account.fenceId(), + account.inputDigest(), + account.canonicalBytes(), + canonical(JSON.valueToTree(result))); + } + + private DraftCommitBinding freshGraphBinding() throws Exception { + String declaration = + JSON.writeValueAsString( + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "startLocation", + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "roomTemplateId", ROOM_TEMPLATE_ID.toString()), + "familyCounts", + List.of( + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_REGION", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT", "count", 0), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE", "count", 0), + Map.of( + "family", + "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING", + "count", + 0)))); + return DraftCommitBinding.create( + new TargetProof( + TENANT_ID, + VERSION_ID, + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind()), + REQUEST_ID, + COMMIT_ID, + "base-1", + List.of( + new RevisionPayload( + "0", + REGION_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + REGION_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + REGION_TEMPLATE_ID, + declaration)), + new RevisionPayload( + "1", + ZONE_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ZONE_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", ZONE_TEMPLATE_ID, null)), + new RevisionPayload( + "2", + ROOM_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ROOM_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", ROOM_TEMPLATE_ID, null))), + List.of( + affected("REGION", REGION_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ZONE", ZONE_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ROOM", ROOM_TEMPLATE_ID, "ZONE_SUBTREE", ZONE_TEMPLATE_ID)) + .stream() + .flatMap(List::stream) + .toList()); + } + + private String worldRevisionPayload( + UUID revisionId, String family, UUID templateId, String declaration) throws Exception { + var payload = new java.util.LinkedHashMap(); + payload.put("logicalRevisionId", revisionId.toString()); + payload.put("commitId", COMMIT_ID.toString()); + payload.put("aggregateType", family); + payload.put("aggregateId", templateId.toString()); + if (declaration != null) payload.put("freshGraphDeclaration", JSON.readTree(declaration)); + return JSON.writeValueAsString(payload); + } + + private List affected( + String family, UUID templateId, String scopeType, UUID scopeId) { + return List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + "AGGREGATE", + templateId.toString(), + "0"), + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + scopeType, + scopeId.toString(), + "0")); + } + + private byte[] accountBinding(DraftCommitBinding draft) { + byte[] draftBytes = draft.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + OPERATION_ID, + REQUEST_ID, + COMMIT_ID, + FENCE_ID, + ACTOR_ID, + TENANT_ID, + VERSION_ID, + "base-1", + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd").toString(), + null, + "1", + null, + null, + new byte[] {4, 5}))) + .canonicalBytes(); + } + + private byte[] graphBytes( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft) throws Exception { + var root = new java.util.LinkedHashMap(); + root.put("schemaVersion", "2"); + root.put("canonicalTenantId", draft.target().canonicalTenantId().toString()); + root.put("canonicalVersionId", draft.target().canonicalVersionId().toString()); + var rows = new java.util.ArrayList>(); + int mappingId = 1; + long privateRowKey = 101; + for (RevisionPayload revision : draft.revisions()) { + if (revision.owner() != DraftCommitBinding.Owner.WORLD_MANAGEMENT) continue; + var mutation = JSON.readTree(revision.payload()); + String family = + mutation.get("aggregateType").textValue().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + var mapping = new java.util.LinkedHashMap(); + mapping.put("id", mappingId++); + mapping.put("target_namespace", request.targetNamespace()); + mapping.put("canonical_tenant_id", draft.target().canonicalTenantId().toString()); + mapping.put("canonical_version_id", draft.target().canonicalVersionId().toString()); + mapping.put("family", family); + mapping.put("template_id", mutation.get("aggregateId").textValue()); + mapping.put("private_row_key", privateRowKey++); + mapping.put("tenant_id", 11); + mapping.put("version_id", 19); + mapping.put("version_identity_operation_id", OPERATION_ID.toString()); + mapping.put("request_id", draft.requestId().toString()); + mapping.put("commit_id", draft.commitId().toString()); + mapping.put("revision_id", revision.revisionId().toString()); + mapping.put("revision_order", revision.revisionOrder()); + rows.add(Map.of("mapping", mapping, "content", Map.of())); + } + root.put("rows", rows); + return JSON.writeValueAsBytes(root); + } + + private byte[] historicalGraphBytes(DraftAuthorizationFenceBinding account) { + throw new IllegalArgumentException("This fixture supplies only selector-bearing APPLIED v2"); + } + + private tools.jackson.databind.node.ObjectNode receipt( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft, String graphDigest) + throws Exception { + var account = request.accountBinding(); + var receipt = + WorldDraftStartLocationEvidence.create( + request.targetNamespace(), + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + sha256(account.canonicalBytes()), + draft.digest(), + new RoomTemplateRef(TENANT_ID, VERSION_ID, ROOM_TEMPLATE_ID), + graphDigest); + return (tools.jackson.databind.node.ObjectNode) JSON.readTree(receipt.canonicalBytes()); + } + + private byte[] canonical(tools.jackson.databind.JsonNode value) throws Exception { + return net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(value)); + } + + private String sha256(byte[] bytes) throws Exception { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index 9d3e584d69..564aa6b094 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -11,6 +11,7 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; +import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZoneOffset; @@ -18,12 +19,14 @@ import java.util.Optional; import java.util.UUID; import java.util.stream.Stream; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; @@ -88,6 +91,258 @@ class VersionPublishCommandServiceImplTest { private VersionPublishCommandServiceImpl service; + @Test + void selectorV2CommittedReadbackReconcilesAndExactlyReplaysWithoutCreatingAnotherRelease() + throws Exception { + // Original Account/APPLIED and freeze fields are stipulated component fixtures, not a live + // authenticated freeze/permission producer or authorization to enable new publication. + SelectorReadback fixture = selectorReadback(); + PublishAttempt attempt = + selectedAttempt( + PublishAttemptStatus.PENDING, + 10L, + 1, + fixture.selected().request(), + fixture.selected().selection()); + stubSelectorReadback(fixture, attempt); + var first = service.reconcileFullVersionPublish(fixture.selected().request()); + assertEquals("SUCCEEDED", first.status()); + verify(publishAttemptService) + .markFullVersionSucceeded(fixture.selected().request().publishWorkflowId()); + attempt.setStatus(PublishAttemptStatus.SUCCEEDED); + var retry = service.reconcileFullVersionPublish(fixture.selected().request()); + assertEquals(first, retry); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(publishedReleaseBundleService, never()) + .createFullVersionBundle(any(), any(), any(), any(), any()); + verify(publishedReleaseBundleService, never()) + .createFullVersionBundle(any(), any(), any(), any(), any(), any()); + verify(versionRepository, never()).save(any()); + } + + @Test + void selectorV2ReadbackRejectsAnotherOriginalSelectedBindingEvenWithSameCommitUuid() + throws Exception { + SelectorReadback fixture = selectorReadback(); + var original = fixture.selected().selection().selectedCommit(); + var changed = + DraftCommitBinding.create( + original.target(), + original.requestId(), + original.commitId(), + "changed-original-base", + original.revisions(), + original.affectedUnits()); + SelectedRequest selected = selectOriginalForReadback(changed, "5"); + PublishAttempt attempt = + selectedAttempt( + PublishAttemptStatus.PENDING, 10L, 1, selected.request(), selected.selection()); + SelectorReadback substituted = + new SelectorReadback(selected, fixture.evidence(), fixture.bundle(), fixture.version()); + stubSelectorReadback(substituted, attempt); + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> service.reconcileFullVersionPublish(selected.request())); + verify(publishAttemptService, never()).markFullVersionSucceeded(any()); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + } + + @ParameterizedTest + @EnumSource(value = SelectorSubstitution.class) + void selectorV2ReadbackRejectsChangedPublicationRequestOrHistoricalEpoch( + SelectorSubstitution substitution) throws Exception { + SelectorReadback fixture = selectorReadback(); + var original = fixture.evidence().request(); + var changedRequest = + new WorldPublishedStartLocationEvidence.Request( + original.targetNamespace(), + original.canonicalTenantId(), + original.canonicalVersionId(), + original.intakeRequestId(), + original.publicationFence(), + substitution == SelectorSubstitution.REQUEST + ? "another-request" + : original.publicationRequestId(), + original.requestDigest(), + substitution == SelectorSubstitution.EPOCH ? 6L : original.versionStateEpoch(), + original.publishWorkflowId(), + original.appliedCommitId(), + original.contentDigest(), + original.digestSchemaVersion(), + original.worldAffectedTuples()); + var changed = + new WorldPublishedStartLocationEvidence( + changedRequest, + fixture.evidence().selectorReceiptBytes(), + fixture.evidence().originalAccountBindingBytes(), + fixture.evidence().appliedResultBytes()); + SelectorReadback substituted = + new SelectorReadback( + fixture.selected(), + changed, + selectorBundle(fixture.selected(), changed), + fixture.version()); + PublishAttempt attempt = + selectedAttempt( + PublishAttemptStatus.PENDING, + 10L, + 1, + fixture.selected().request(), + fixture.selected().selection()); + stubSelectorReadback(substituted, attempt); + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> service.reconcileFullVersionPublish(fixture.selected().request())); + verify(publishAttemptService, never()).markFullVersionSucceeded(any()); + } + + private enum SelectorSubstitution { + REQUEST, + EPOCH + } + + private SelectorReadback selectorReadback() throws Exception { + var target = + new TargetProof( + UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), + 10L, + "tenant-1", + 1L, + "tenant-1", + "NEW_GAME_ROW"); + var original = PublishedWorldSelectorFixtures.evidence(target); + var account = DraftAuthorizationFenceBinding.fromStored(original.originalAccountBindingBytes()); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + var selected = selectOriginalForReadback(draft, "5"); + var r = original.request(); + var request = + new WorldPublishedStartLocationEvidence.Request( + r.targetNamespace(), + r.canonicalTenantId(), + r.canonicalVersionId(), + r.intakeRequestId(), + r.publicationFence(), + selected.request().publishRequestId(), + r.requestDigest(), + 5L, + selected.request().publishWorkflowId(), + r.appliedCommitId(), + r.contentDigest(), + r.digestSchemaVersion(), + r.worldAffectedTuples()); + var evidence = + new WorldPublishedStartLocationEvidence( + request, + original.selectorReceiptBytes(), + original.originalAccountBindingBytes(), + original.appliedResultBytes()); + var version = new Version(); + version.setId(10L); + version.setTenantId("tenant-1"); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(6L); + version.setCanonicalTenantId(target.canonicalTenantId()); + version.setCanonicalVersionId(target.canonicalVersionId()); + return new SelectorReadback(selected, evidence, selectorBundle(selected, evidence), version); + } + + private SelectedRequest selectOriginalForReadback(DraftCommitBinding draft, String epoch) { + var target = draft.target(); + var intent = + new PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + "workflow-1", + epoch, + "notes", + draft.requestId(), + draft.commitId(), + draft.digest()); + var fence = + new VisibilityFence( + target, + draft.requestId(), + draft.commitId(), + draft.digest(), + "[]", + OffsetDateTime.now(ZoneOffset.UTC)); + var selected = + AuthoredDraftPublishSelection.capture( + intent, target, new PublicationEvidence(draft, fence)); + var snapshot = new SelectionSnapshot(selected, OffsetDateTime.now(ZoneOffset.UTC)); + when(authoredSelections.readByPublishRequest(target.canonicalTenantId(), "workflow-1")) + .thenReturn(Optional.of(snapshot)); + var request = + new PublishWorkflowRequest( + "tenant-1", "notes", "workflow-1", selectedWorkflowId("workflow-1"), intent); + return new SelectedRequest(selected, intent, snapshot, request); + } + + private PublishedReleaseBundleDto selectorBundle( + SelectedRequest selected, WorldPublishedStartLocationEvidence evidence) { + return new PublishedReleaseBundleDto( + 1L, + "tenant-1", + 10L, + 1, + "v2", + selected.request().publishWorkflowId(), + MANIFEST_HASH, + List.of(), + PublishedWorldSelectorFixtures.participants(10L, evidence), + List.of(), + "generation-revision", + false, + null, + LocalDateTime.now(), + evidence.request().canonicalTenantId(), + evidence.request().canonicalVersionId(), + "opaque-owner-release", + 1, + List.of(), + evidence); + } + + private void stubSelectorReadback(SelectorReadback fixture, PublishAttempt attempt) { + var workflow = fixture.selected().request().publishWorkflowId(); + var game = new Game(); + game.setTenantId("tenant-1"); + when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); + when(publishAttemptRepository.findByPublishWorkflowId(workflow)) + .thenReturn(Optional.of(attempt)); + when(versionRepository.findByTenantIdAndId("tenant-1", 10L)) + .thenReturn(Optional.of(fixture.version())); + when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) + .thenReturn(Optional.of(fixture.bundle())); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn( + Optional.of( + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "PUBLISHED", + 4L, + MANIFEST_HASH, + workflow, + null, + null, + LocalDateTime.now(), + List.of()))); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) + .thenReturn(emptyManifest()); + } + + private record SelectorReadback( + SelectedRequest selected, + WorldPublishedStartLocationEvidence evidence, + PublishedReleaseBundleDto bundle, + Version version) {} + @BeforeEach void setup() { MockitoAnnotations.openMocks(this); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/WorldPublishedStartLocationMtlsTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/WorldPublishedStartLocationMtlsTest.java new file mode 100644 index 0000000000..00cdfb1993 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/WorldPublishedStartLocationMtlsTest.java @@ -0,0 +1,335 @@ +package unit.net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.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.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationClient; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationGrpcCodec; +import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; +import net.firedevops.firemud.test.TlsTestSupport; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedStartLocationReadServiceGrpc; +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.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Physical mTLS proof of the selector client's pre-send and response peer identity checks. */ +class WorldPublishedStartLocationMtlsTest { + private static final String NAMESPACE = "test"; + private static final String GAME_DESIGN_PEER = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String WORLD_PEER = "spiffe://firemud/ns/test/sa/world-management-service"; + private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1L); + private static TestPki pki; + + @BeforeAll + static void generateEphemeralPki() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + KeyPair caKeyPair = newRsaKeyPair(); + X500Name caName = new X500Name("CN=World Published Selector Test CA, O=FireMUD Test"); + X509Certificate caCertificate = + issueCertificate(caName, caKeyPair.getPublic(), caName, caKeyPair.getPrivate(), true); + pki = + new TestPki( + caCertificate, + issueLeaf(caName, caKeyPair.getPrivate(), "game-design-service", GAME_DESIGN_PEER), + issueLeaf(caName, caKeyPair.getPrivate(), "world-management-service", WORLD_PEER), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "wrong-service-world-server", + "spiffe://firemud/ns/test/sa/game-design-service"), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "wrong-namespace-world-server", + "spiffe://firemud/ns/other-test/sa/world-management-service")); + } + + @Test + void wrongWorldServiceOrNamespaceSendsNoRpcMetadataOrRequestBodyButExactPeerSucceeds( + @TempDir Path directory) throws Exception { + WorldPublishedStartLocationEvidence evidence = evidence(); + int index = 0; + for (TestCertificate wrongServer : + List.of(pki.wrongServiceServer(), pki.wrongNamespaceServer())) { + PhysicalServer receiver = startReceiver(wrongServer, evidence); + try (WorldPublishedStartLocationClient client = + newClient(receiver.server().getPort(), directory.resolve("wrong-" + index++))) { + client.init(); + Throwable failure = catchThrowable(() -> client.read(evidence.request())); + + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isFalse(); + assertThat(receiver.requestMetadataCalls()).hasValue(0); + assertThat(receiver.requestBodies()).hasValue(0); + assertThat(receiver.request()).hasValue(null); + } finally { + stopServer(receiver.server()); + } + } + + PhysicalServer receiver = startReceiver(pki.worldServer(), evidence); + try (WorldPublishedStartLocationClient client = + newClient(receiver.server().getPort(), directory.resolve("exact-world-peer"))) { + client.init(); + WorldPublishedStartLocationEvidence received = client.read(evidence.request()); + + assertThat(received).isEqualTo(evidence); + assertThat(receiver.requestMetadataCalls()).hasValue(1); + assertThat(receiver.requestBodies()).hasValue(1); + assertThat(receiver.authenticatedCallerPeer()).hasValue(GAME_DESIGN_PEER); + assertThat(receiver.request()) + .hasValue(WorldPublishedStartLocationGrpcCodec.toRequest(evidence.request())); + } finally { + stopServer(receiver.server()); + } + } + + private static PhysicalServer startReceiver( + TestCertificate serverCertificate, WorldPublishedStartLocationEvidence evidence) + throws Exception { + AtomicInteger requestMetadataCalls = new AtomicInteger(); + AtomicInteger requestBodies = new AtomicInteger(); + AtomicReference request = new AtomicReference<>(); + AtomicReference authenticatedCallerPeer = new AtomicReference<>(); + ReadWorldPublishedStartLocationResponse response = + WorldPublishedStartLocationGrpcCodec.toResponse(evidence.request(), evidence); + var service = + new WorldPublishedStartLocationReadServiceGrpc + .WorldPublishedStartLocationReadServiceImplBase() { + @Override + public void readWorldPublishedStartLocation( + ReadWorldPublishedStartLocationRequest readRequest, + StreamObserver responseObserver) { + requestBodies.incrementAndGet(); + request.set(readRequest); + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + authenticatedCallerPeer.set(peer == null ? null : peer.uri()); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + }; + ServerInterceptor metadataCounter = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + io.grpc.Metadata headers, + ServerCallHandler next) { + requestMetadataCalls.incrementAndGet(); + return next.startCall(call, headers); + } + }; + Server 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( + ServerInterceptors.intercept( + service, metadataCounter, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + return new PhysicalServer( + server, requestMetadataCalls, requestBodies, request, authenticatedCallerPeer); + } + + private static WorldPublishedStartLocationClient newClient(int port, Path directory) + throws Exception { + Files.createDirectories(directory); + Path clientCertificate = + writePem( + directory.resolve("game-design-client.crt"), + "CERTIFICATE", + pki.gameDesignClient().certificate().getEncoded()); + Path clientPrivateKey = + writePem( + directory.resolve("game-design-client.key"), + "PRIVATE KEY", + pki.gameDesignClient().privateKey().getEncoded()); + Path caCertificate = + writePem(directory.resolve("test-ca.crt"), "CERTIFICATE", pki.caCertificate().getEncoded()); + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(clientCertificate.toString()); + tls.setPrivateKey(clientPrivateKey.toString()); + tls.setCaCert(caCertificate.toString()); + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("127.0.0.1:" + port); + return new WorldPublishedStartLocationClient( + endpoints, tls, new GrpcChannelFactory(), NAMESPACE); + } + + private static WorldPublishedStartLocationEvidence evidence() throws Exception { + return PublishedWorldSelectorFixtures.evidence( + new TargetProof( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 19L, + "tenant-key", + 42L, + "tenant-key", + "NEW_GAME_ROW")); + } + + private static void stopServer(Server server) throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + 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) + throws Exception { + return issueCertificate(subject, publicKey, issuer, issuerPrivateKey, ca, null); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerPrivateKey, + boolean ca, + GeneralNames subjectAltNames) + throws Exception { + Instant notBefore = Instant.now().minusSeconds(60); + JcaX509v3CertificateBuilder builder = + new JcaX509v3CertificateBuilder( + issuer, + BigInteger.valueOf(CERTIFICATE_SERIAL.getAndIncrement()), + Date.from(notBefore), + Date.from(notBefore.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 static Path writePem(Path path, String type, byte[] encoded) throws IOException { + String base64 = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(encoded); + Files.writeString( + path, "-----BEGIN " + type + "-----\n" + base64 + "\n-----END " + type + "-----\n"); + return path; + } + + private record TestCertificate(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestCertificate gameDesignClient, + TestCertificate worldServer, + TestCertificate wrongServiceServer, + TestCertificate wrongNamespaceServer) {} + + private record PhysicalServer( + Server server, + AtomicInteger requestMetadataCalls, + AtomicInteger requestBodies, + AtomicReference request, + AtomicReference authenticatedCallerPeer) {} +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java index 5174f1c952..9932ad43be 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java @@ -54,6 +54,28 @@ public Optional readCommitted(Request request) { return Optional.ofNullable(find(Objects.requireNonNull(request, "request"))); } + /** Complete publication selection; owner and original commit are reconstructed internally. */ + public Optional readCommitted(CaptureRequest request) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException("Frozen topology readback requires no caller transaction"); + } + Objects.requireNonNull(request, "request"); + Record row = + dsl.resultQuery( + "SELECT binding_json,binding_digest,owner_binding_json FROM world_canonical_frozen_topology WHERE publication_fence=?", + request.publicationFence()) + .fetchOne(); + if (row == null) return Optional.empty(); + var binding = + DraftCommitBinding.fromStored( + required(row, "binding_json", String.class), + required(row, "binding_digest", String.class)); + var ownerBinding = + JSON.readValue(required(row, "owner_binding_json", String.class), OwnerBinding.class); + return readCommitted( + new Request(WorldDraftTopologyCommitPlan.create(binding, ownerBinding), request)); + } + WorldCanonicalFrozenTopology capture(Request request) { // This seam validates actual PostgreSQL isolation and serializes through the existing V25 row. var provenance = owner.lockAndResolve(request.freeze()); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java index 8bc58263c8..cb23eeebd9 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java @@ -3,6 +3,9 @@ import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; /** * Typed input and storage result for the owner-private canonical instance materialization cut. @@ -81,7 +84,9 @@ public record Result( int zoneCount, int roomCount, int exitCount, - String storageStatus) { + String storageStatus, + RoomTemplateRef startLocation, + Long runtimeRoomInstanceId) { public Result { Objects.requireNonNull(association, "association"); Objects.requireNonNull(captureId, "captureId"); @@ -94,6 +99,35 @@ public record Result( if (!"MATERIALIZED_UNVERIFIED".equals(storageStatus)) { throw new IllegalArgumentException("Unsupported canonical preparation result status"); } + if ((startLocation == null) != (runtimeRoomInstanceId == null) + || runtimeRoomInstanceId != null && runtimeRoomInstanceId <= 0) { + throw new IllegalArgumentException( + "Canonical selector and runtime mapping must be complete together"); + } + } + + public Result( + WorldCanonicalInstanceAssociation association, + UUID captureId, + String graphSha256, + String inputDigest, + int regionCount, + int zoneCount, + int roomCount, + int exitCount, + String storageStatus) { + this( + association, + captureId, + graphSha256, + inputDigest, + regionCount, + zoneCount, + roomCount, + exitCount, + storageStatus, + null, + null); } } @@ -156,6 +190,67 @@ static void requireExactReleaseGraph( } // The freeze observes the Draft epoch; the descriptor attests the later published Version // epoch. Those distinct lifecycle observations must not be treated as an equality join. + requireExactSelector(release, topologyPlan); + } + + /** V1 remains inert history; v2 must carry the complete original selector and frozen request. */ + static void requireExactSelector( + AuthoredWorldReleaseAttestationEvidence release, + WorldCanonicalInstanceTopologyPlan topologyPlan) { + if (release.schemaVersion() == AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION) return; + var selector = + Objects.requireNonNull(release.worldStartLocationEvidence(), "World selector evidence"); + var freeze = topologyPlan.sourceBinding().freeze(); + var expected = + new WorldPublishedStartLocationEvidence.Request( + freeze.targetNamespace(), + freeze.canonicalTenantId(), + freeze.canonicalVersionId(), + freeze.intakeRequestId(), + freeze.publicationFence(), + freeze.publicationRequestId(), + freeze.requestDigest(), + freeze.versionStateEpoch(), + freeze.publishWorkflowId(), + freeze.appliedCommitId(), + freeze.contentDigest(), + freeze.digestSchemaVersion(), + freeze.suppliedOwnedAffectedTuples().stream() + .map( + tuple -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) + .toList()); + var receipt = WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()); + var declaration = + topologyPlan + .sourceBinding() + .plan() + .graph() + .freshGraphDeclaration() + .orElseThrow( + () -> + new IllegalArgumentException( + "Selected World graph has no original fresh declaration")); + if (!selector.request().equals(expected) + || !declaration.startLocation().equals(receipt.startLocation()) + || !receipt.bindingDigest().equals(topologyPlan.sourceBinding().plan().binding().digest()) + || topologyPlan.rooms().stream() + .filter( + room -> + room.identity() + .templateId() + .equals(receipt.startLocation().roomTemplateId())) + .count() + != 1) { + throw new IllegalArgumentException( + "Release selector differs from the exact frozen request, declaration or ROOM"); + } } static int entryCount(Input input, EntryType family) { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java index aa0218476c..d14c9aa0c1 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java @@ -5,6 +5,7 @@ import java.security.NoSuchAlgorithmException; import java.sql.SQLException; import java.util.ArrayList; +import java.util.Arrays; import java.util.Base64; import java.util.HexFormat; import java.util.LinkedHashMap; @@ -12,6 +13,8 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopology.Request; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.Input; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.Result; @@ -218,6 +221,58 @@ public Optional readOwnerPreparation(Input input) { throw new InvalidPreparationEvidenceException( "Canonical World preparation readback omitted or added a selected topology family row"); } + var selector = + input.completeLaunchBinding().evidence().releaseAttestation().worldStartLocationEvidence(); + RoomTemplateRef startLocation = null; + Long runtimeRoomInstanceId = null; + if (selector != null) { + requireExactOriginalSelector(input, graphBytes); + var receipt = WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()); + Record selected = + dsl.fetchOne( + "SELECT s.*, m.runtime_room_instance_id AS mapped_room_instance_id, " + + "r.room_instance_id AS actual_room_instance_id,r.tenant_id AS room_tenant_key,r.game_instance_id AS room_game_instance_key " + + "FROM world_canonical_preparation_start_location s " + + "JOIN world_canonical_instance_topology_identity m ON m.world_instance_id=s.world_instance_id " + + "AND m.canonical_game_instance_id=s.canonical_game_instance_id AND m.family='ROOM' " + + "AND m.template_id=s.room_template_id JOIN room_instance r ON r.id=m.runtime_row_id " + + "WHERE s.canonical_game_instance_id=?", + input.canonicalGameInstanceId()); + if (selected == null + || !Arrays.equals( + selector.canonicalBytes(), required(selected, "evidence_bytes", byte[].class)) + || !receipt + .startLocation() + .tenantId() + .equals(required(selected, "canonical_tenant_id", java.util.UUID.class)) + || !receipt + .startLocation() + .versionId() + .equals(required(selected, "canonical_version_id", java.util.UUID.class)) + || !receipt + .startLocation() + .roomTemplateId() + .equals(required(selected, "room_template_id", java.util.UUID.class)) + || !receipt.receiptDigest().equals(required(selected, "receipt_digest", String.class)) + || !receipt.graphDigest().equals(required(selected, "graph_digest", String.class)) + || !Objects.equals( + required(selected, "runtime_room_instance_id", Long.class), + required(selected, "mapped_room_instance_id", Long.class)) + || !Objects.equals( + required(selected, "runtime_room_instance_id", Long.class), + required(selected, "actual_room_instance_id", Long.class)) + || required(selected, "room_tenant_key", Long.class) + != input.versionIdentity().sourceIntakeReceipt().localTenantKey() + || !Objects.equals( + required(selected, "room_game_instance_key", Long.class), + required(row, "private_game_instance_key", Long.class)) + || required(selected, "world_instance_id", Long.class) != association.worldInstanceId()) { + throw new InvalidPreparationEvidenceException( + "Canonical preparation lost exact original selector or runtime ROOM mapping"); + } + startLocation = receipt.startLocation(); + runtimeRoomInstanceId = required(selected, "runtime_room_instance_id", Long.class); + } return Optional.of( new Result( association, @@ -228,7 +283,9 @@ public Optional readOwnerPreparation(Input input) { zones, rooms, exits, - required(row, "storage_status", String.class))); + required(row, "storage_status", String.class), + startLocation, + runtimeRoomInstanceId)); } private void requireExactFrozenSource(Input input) { @@ -256,6 +313,43 @@ private void requireExactFrozenSource(Input input) { WorldCanonicalInstancePreparation.requireGenerationFree(reconstructed); WorldCanonicalInstancePreparation.requireExactReleaseGraph( input.completeLaunchBinding().evidence().releaseAttestation(), reconstructed); + requireExactOriginalSelector(input, frozen.graphBytes()); + } + + /** Exact immutable Account/APPLIED/receipt readback; no mutable remote owner read. */ + private void requireExactOriginalSelector(Input input, byte[] graphBytes) { + var evidence = + input.completeLaunchBinding().evidence().releaseAttestation().worldStartLocationEvidence(); + if (evidence == null) return; + var receipt = WorldDraftStartLocationEvidence.fromStored(evidence.selectorReceiptBytes()); + Record original = + dsl.fetchOne( + "SELECT s.receipt_bytes,s.account_binding_bytes,s.graph_digest,a.result_bytes,g.graph_bytes " + + "FROM world_draft_start_location_receipt s JOIN world_draft_graph_application a " + + "ON a.operation_id=s.operation_id AND a.request_id=s.request_id AND a.commit_id=s.commit_id " + + "AND a.authorization_fence_id=s.authorization_fence_id " + + "JOIN world_topology_draft_commit g ON g.request_id=s.request_id AND g.commit_id=s.commit_id " + + "WHERE s.operation_id=? AND s.target_namespace=? AND s.canonical_tenant_id=? " + + "AND s.canonical_version_id=? AND s.room_template_id=?", + receipt.operationId(), + receipt.targetNamespace(), + receipt.startLocation().tenantId(), + receipt.startLocation().versionId(), + receipt.startLocation().roomTemplateId()); + if (original == null + || !Arrays.equals( + evidence.selectorReceiptBytes(), required(original, "receipt_bytes", byte[].class)) + || !Arrays.equals( + evidence.originalAccountBindingBytes(), + required(original, "account_binding_bytes", byte[].class)) + || !Arrays.equals( + evidence.appliedResultBytes(), required(original, "result_bytes", byte[].class)) + || !Arrays.equals(graphBytes, required(original, "graph_bytes", byte[].class)) + || !receipt.graphDigest().equals(digest(graphBytes)) + || !receipt.graphDigest().equals(required(original, "graph_digest", String.class))) { + throw new InvalidPreparationEvidenceException( + "Canonical preparation selector differs from original World Account/APPLIED/graph receipt"); + } } /** @@ -274,6 +368,7 @@ static boolean matchesCompleteFrozenSource(Request retained, Request supplied) { && retainedPlan.ownerBinding().equals(suppliedPlan.ownerBinding()) && retainedGraph.tenantId().equals(suppliedGraph.tenantId()) && retainedGraph.versionId().equals(suppliedGraph.versionId()) + && retainedGraph.freshGraphDeclaration().equals(suppliedGraph.freshGraphDeclaration()) && retainedGraph.nodes().equals(suppliedGraph.nodes()); } @@ -356,7 +451,8 @@ static String inputJson(Input input) { Map root = object( - "schemaVersion", 1, + "schemaVersion", + launch.evidence().releaseAttestation().worldStartLocationEvidence() == null ? 1 : 2, "identity", object( "canonicalGameInstanceId", evidence.canonicalGameInstanceId().toString(), @@ -474,6 +570,12 @@ static String inputJson(Input input) { "exitCount", topology.roomExits().size(), "generationRuleCount", topology.generationRules().size(), "spawnBindingCount", topology.spawnBindings().size())); + var selector = launch.evidence().releaseAttestation().worldStartLocationEvidence(); + if (selector != null) { + root.put( + "worldStartLocationEvidenceBase64", + Base64.getEncoder().encodeToString(selector.canonicalBytes())); + } try { return JSON.writeValueAsString(root); } catch (JacksonException exception) { 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 index a3b3c44f5e..31889f4382 100644 --- 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 @@ -38,6 +38,12 @@ public record WorldCompleteLaunchBindingReceipt( 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()) diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftStartLocationReceipt.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftStartLocationReceipt.java index 421f916ccb..d7796b0f66 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftStartLocationReceipt.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftStartLocationReceipt.java @@ -1,17 +1,8 @@ package net.firedevops.firemud.worldmanagement.tenant; -import java.io.ByteArrayOutputStream; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; import java.util.UUID; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; /** Exact durable selector evidence tied to its original Account operation and stored graph. */ public record WorldDraftStartLocationReceipt( @@ -25,19 +16,18 @@ public record WorldDraftStartLocationReceipt( RoomTemplateRef startLocation, String graphDigest, String receiptDigest) { - private static final String SCHEMA = "world-draft-start-location-receipt/v1"; - public WorldDraftStartLocationReceipt { - Objects.requireNonNull(targetNamespace, "targetNamespace"); - Objects.requireNonNull(operationId, "operationId"); - Objects.requireNonNull(requestId, "requestId"); - Objects.requireNonNull(commitId, "commitId"); - Objects.requireNonNull(authorizationFenceId, "authorizationFenceId"); - Objects.requireNonNull(accountBindingDigest, "accountBindingDigest"); - Objects.requireNonNull(bindingDigest, "bindingDigest"); - Objects.requireNonNull(startLocation, "startLocation"); - Objects.requireNonNull(graphDigest, "graphDigest"); - Objects.requireNonNull(receiptDigest, "receiptDigest"); + new WorldDraftStartLocationEvidence( + targetNamespace, + operationId, + requestId, + commitId, + authorizationFenceId, + accountBindingDigest, + bindingDigest, + startLocation, + graphDigest, + receiptDigest); } static WorldDraftStartLocationReceipt create( @@ -54,8 +44,8 @@ static WorldDraftStartLocationReceipt create( "World start-location receipt requires an original graph declaration")) .startLocation(); String graphDigest = WorldDraftGraphAppliedResult.digest(graphBytes); - String receiptDigest = - digest( + var evidence = + WorldDraftStartLocationEvidence.create( operation.ownerBinding().targetNamespace(), operation.operationId(), operation.requestId(), @@ -66,80 +56,33 @@ static WorldDraftStartLocationReceipt create( selector, graphDigest); return new WorldDraftStartLocationReceipt( - operation.ownerBinding().targetNamespace(), - operation.operationId(), - operation.requestId(), - operation.commitId(), - operation.authorizationFenceId(), - operation.accountBindingDigest(), - operation.binding().digest(), - selector, - graphDigest, - receiptDigest); + evidence.targetNamespace(), + evidence.operationId(), + evidence.requestId(), + evidence.commitId(), + evidence.authorizationFenceId(), + evidence.accountBindingDigest(), + evidence.bindingDigest(), + evidence.startLocation(), + evidence.graphDigest(), + evidence.receiptDigest()); } byte[] canonicalBytes() { - Map selector = new LinkedHashMap<>(); - selector.put("tenantId", startLocation.tenantId().toString()); - selector.put("versionId", startLocation.versionId().toString()); - selector.put("roomTemplateId", startLocation.roomTemplateId().toString()); - Map json = new LinkedHashMap<>(); - json.put("schema", SCHEMA); - json.put("targetNamespace", targetNamespace); - json.put("operationId", operationId.toString()); - json.put("requestId", requestId.toString()); - json.put("commitId", commitId.toString()); - json.put("authorizationFenceId", authorizationFenceId.toString()); - json.put("accountBindingDigest", accountBindingDigest); - json.put("bindingDigest", bindingDigest); - json.put("startLocation", selector); - json.put("graphDigest", graphDigest); - json.put("receiptDigest", receiptDigest); - try { - return Rfc8785CanonicalJson.canonicalizeUtf8( - new tools.jackson.databind.ObjectMapper().writeValueAsString(json)); - } catch (java.io.IOException exception) { - throw new IllegalArgumentException( - "World start-location receipt cannot be encoded", exception); - } + return asEvidence().canonicalBytes(); } - private static String digest( - String namespace, - UUID operationId, - UUID requestId, - UUID commitId, - UUID fenceId, - String accountBindingDigest, - String bindingDigest, - RoomTemplateRef selector, - String graphDigest) { - ByteArrayOutputStream framed = new ByteArrayOutputStream(); - for (String segment : - new String[] { - SCHEMA, - namespace, - operationId.toString(), - requestId.toString(), - commitId.toString(), - fenceId.toString(), - accountBindingDigest, - bindingDigest, - selector.tenantId().toString(), - selector.versionId().toString(), - selector.roomTemplateId().toString(), - graphDigest - }) { - byte[] bytes = segment.getBytes(StandardCharsets.UTF_8); - framed.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); - framed.writeBytes(bytes); - } - try { - return "sha256:" - + HexFormat.of() - .formatHex(MessageDigest.getInstance("SHA-256").digest(framed.toByteArray())); - } catch (NoSuchAlgorithmException impossible) { - throw new IllegalStateException("SHA-256 unavailable", impossible); - } + private WorldDraftStartLocationEvidence asEvidence() { + return new WorldDraftStartLocationEvidence( + targetNamespace, + operationId, + requestId, + commitId, + authorizationFenceId, + accountBindingDigest, + bindingDigest, + startLocation, + graphDigest, + receiptDigest); } } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationReadGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationReadGrpcService.java new file mode 100644 index 0000000000..c07983669b --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationReadGrpcService.java @@ -0,0 +1,167 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +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.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationGrpcCodec; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedStartLocationReadServiceGrpc; +import org.jooq.exception.DataAccessException; +import org.springframework.dao.TransientDataAccessException; + +/** Standalone authenticated read-only adapter; intentionally not registered as a runtime RPC. */ +public final class WorldPublishedStartLocationReadGrpcService + extends WorldPublishedStartLocationReadServiceGrpc + .WorldPublishedStartLocationReadServiceImplBase { + private final WorldPublishedStartLocationRepository repository; + private final String trustedNamespace; + + public WorldPublishedStartLocationReadGrpcService( + WorldPublishedStartLocationRepository repository, String trustedNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void readWorldPublishedStartLocation( + ReadWorldPublishedStartLocationRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedGameDesignPeer(responseObserver)) return; + + WorldPublishedStartLocationEvidence.Request readRequest; + try { + readRequest = WorldPublishedStartLocationGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException invalid) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical World published selector request is required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(readRequest.targetNamespace())) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("World selector namespace must match the authenticated peer") + .asRuntimeException()); + return; + } + + Optional stored; + try { + stored = repository.readCommitted(toCaptureRequest(readRequest)); + } catch (WorldDesignPublicationFenceRepository.ConflictException conflict) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("World selector conflicts with exact frozen or APPLIED evidence") + .asRuntimeException()); + return; + } catch (TransientDataAccessException | DataAccessException unavailable) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("World published selector storage is temporarily unavailable") + .asRuntimeException()); + return; + } catch (RuntimeException failure) { + responseObserver.onError( + Status.INTERNAL + .withDescription("World published selector read failed") + .asRuntimeException()); + return; + } + if (stored.isEmpty()) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No exact frozen World selector matches the complete selection") + .asRuntimeException()); + return; + } + + ReadWorldPublishedStartLocationResponse response; + try { + WorldPublishedStartLocationSource source = stored.orElseThrow(); + var receipt = source.selectorReceipt(); + byte[] receiptBytes = + new WorldDraftStartLocationEvidence( + receipt.targetNamespace(), + receipt.operationId(), + receipt.requestId(), + receipt.commitId(), + receipt.authorizationFenceId(), + receipt.accountBindingDigest(), + receipt.bindingDigest(), + receipt.startLocation(), + receipt.graphDigest(), + receipt.receiptDigest()) + .canonicalBytes(); + var evidence = + new WorldPublishedStartLocationEvidence( + readRequest, + receiptBytes, + source.appliedResult().application().operation().accountBindingBytes(), + source.appliedResult().canonicalBytes()); + response = WorldPublishedStartLocationGrpcCodec.toResponse(readRequest, evidence); + } catch (IllegalArgumentException | IllegalStateException invalidEvidence) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("World published selector evidence is inconsistent") + .asRuntimeException()); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + private boolean requireAuthenticatedGameDesignPeer(StreamObserver responseObserver) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer != null + && peer.isService("game-design-service") + && peer.isInNamespace(trustedNamespace) + && !SessionContext.hasAuthenticatedCallerContext()) { + return true; + } + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "Only the verified same-namespace Game Design workload without end-user context is allowed") + .asRuntimeException()); + return false; + } + + private static CaptureRequest toCaptureRequest( + WorldPublishedStartLocationEvidence.Request request) { + return new CaptureRequest( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + request.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + request.worldAffectedTuples().stream() + .map( + tuple -> + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) + .toList()); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationRepository.java new file mode 100644 index 0000000000..c0ab0e5b8a --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationRepository.java @@ -0,0 +1,79 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import org.jooq.DSLContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicitly unwired immutable frozen-selection to original APPLIED selector join. */ +public final class WorldPublishedStartLocationRepository { + private final DSLContext dsl; + private final WorldCanonicalFrozenTopologyRepository frozen; + private final WorldDraftGraphApplicationRepository applications; + + public WorldPublishedStartLocationRepository( + DSLContext dsl, + WorldCanonicalFrozenTopologyRepository frozen, + WorldDraftGraphApplicationRepository applications) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.frozen = Objects.requireNonNull(frozen, "frozen"); + this.applications = Objects.requireNonNull(applications, "applications"); + } + + /** Immutable journals need no distributed transaction; absence never authorizes a fallback. */ + public Optional readCommitted(CaptureRequest request) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException("World published selector read requires no caller transaction"); + } + var selected = frozen.readCommitted(Objects.requireNonNull(request, "request")); + if (selected.isEmpty()) return Optional.empty(); + var capture = selected.orElseThrow(); + var plan = capture.request().plan(); + if (!request.equals(capture.request().freeze())) { + throw new ConflictException("World published selector differs from exact frozen selection"); + } + var rows = + dsl.fetch( + "SELECT account_binding_bytes FROM world_draft_graph_application WHERE request_id=? OR commit_id=?", + plan.binding().requestId(), + plan.binding().commitId()); + if (rows.isEmpty()) { + throw new ConflictException("World published selector lacks original APPLIED application"); + } + if (rows.size() != 1) { + throw new ConflictException("World published selector selects conflicting applications"); + } + var account = + DraftAuthorizationFenceBinding.fromStored( + rows.getFirst().get("account_binding_bytes", byte[].class)); + var applied = + applications + .readCommitted(request.targetNamespace(), account.canonicalBytes()) + .orElseThrow( + () -> new ConflictException("World published selector lacks committed APPLIED")); + var application = applied.application(); + var receipt = + applied + .startLocationReceipt() + .orElseThrow( + () -> + new ConflictException( + "World published selector lacks original selector receipt")); + if (!plan.binding().equals(application.plan().binding()) + || !plan.ownerBinding().equals(application.plan().ownerBinding()) + || !Arrays.equals(account.canonicalBytes(), application.operation().accountBindingBytes()) + || !request.appliedCommitId().equals(application.operation().commitId().toString()) + || !Arrays.equals(capture.graphBytes(), applied.graphBytes()) + || !receipt.graphDigest().equals(WorldDraftGraphAppliedResult.digest(capture.graphBytes())) + || !receipt.equals( + WorldDraftStartLocationReceipt.create(application, capture.graphBytes()))) { + throw new ConflictException( + "World published selector differs from original frozen application"); + } + return Optional.of(new WorldPublishedStartLocationSource(capture, applied, receipt)); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationSource.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationSource.java new file mode 100644 index 0000000000..0e59008b55 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationSource.java @@ -0,0 +1,18 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; + +/** + * Original selector and immutable owner evidence for publication transport. This value grants no + * current Account permission, complete release proof or runtime admission authority. + */ +public record WorldPublishedStartLocationSource( + WorldCanonicalFrozenTopology frozenTopology, + WorldDraftGraphAppliedResult appliedResult, + WorldDraftStartLocationReceipt selectorReceipt) { + public WorldPublishedStartLocationSource { + Objects.requireNonNull(frozenTopology, "frozenTopology"); + Objects.requireNonNull(appliedResult, "appliedResult"); + Objects.requireNonNull(selectorReceipt, "selectorReceipt"); + } +} diff --git a/services/world-management-service/src/main/resources/db/migration/V42__world_release_start_location_materialization.sql b/services/world-management-service/src/main/resources/db/migration/V42__world_release_start_location_materialization.sql new file mode 100644 index 0000000000..626ea1831f --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V42__world_release_start_location_materialization.sql @@ -0,0 +1,218 @@ +-- Keep V1 materialization history inert and byte-for-byte retryable. V2 retains the authored +-- ROOM reference separately from its exact World-owned runtime mapping; neither activates it. +CREATE TABLE world_canonical_preparation_start_location ( + canonical_game_instance_id UUID PRIMARY KEY REFERENCES world_canonical_instance_preparation(canonical_game_instance_id) ON DELETE RESTRICT, + world_instance_id BIGINT NOT NULL REFERENCES world_instance(id) ON DELETE RESTRICT, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + room_template_id UUID NOT NULL, + runtime_room_instance_id BIGINT NOT NULL CHECK (runtime_room_instance_id > 0), + receipt_digest VARCHAR(71) NOT NULL CHECK (receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + graph_digest VARCHAR(71) NOT NULL CHECK (graph_digest ~ '^sha256:[0-9a-f]{64}$'), + evidence_bytes BYTEA NOT NULL CHECK (octet_length(evidence_bytes) > 0), + recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +-- [jooq ignore start] +REVOKE ALL ON world_canonical_preparation_start_location FROM PUBLIC; + +-- This independently checks immutable producer evidence before allocation and on every retry. +CREATE FUNCTION world_require_preparation_start_location(input JSONB, binding JSONB, capture UUID) +RETURNS VOID LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + frozen "${serviceSchema}".world_canonical_frozen_topology%ROWTYPE; + receipt "${serviceSchema}".world_draft_start_location_receipt%ROWTYPE; + application "${serviceSchema}".world_draft_graph_application%ROWTYPE; + graph "${serviceSchema}".world_topology_draft_commit%ROWTYPE; + evidence JSONB; + selected JSONB; + freeze JSONB; + retained JSONB; + expected_tuples JSONB; +BEGIN + IF input->>'schemaVersion' = '1' THEN + IF binding->>'schemaVersion' IS DISTINCT FROM '1' + OR binding ? 'worldStartLocationEvidence' OR input ? 'worldStartLocationEvidenceBase64' THEN + RAISE EXCEPTION 'V1 preparation cannot acquire selector evidence' USING ERRCODE = '23514'; + END IF; + RETURN; + END IF; + IF input->>'schemaVersion' IS DISTINCT FROM '2' OR binding->>'schemaVersion' IS DISTINCT FROM '2' + OR input->>'worldStartLocationEvidenceBase64' IS NULL + OR jsonb_typeof(binding->'worldStartLocationEvidence') IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'V2 preparation requires original complete World selector evidence' USING ERRCODE = '23514'; + END IF; + evidence := convert_from(decode(input->>'worldStartLocationEvidenceBase64', 'base64'), 'UTF8')::JSONB; + selected := evidence->'request'; + retained := binding->'worldStartLocationEvidence'; + SELECT * INTO STRICT frozen FROM "${serviceSchema}".world_canonical_frozen_topology WHERE capture_id=capture; + freeze := frozen.freeze_request_json::JSONB; + SELECT coalesce(jsonb_agg(value ORDER BY value->>'owner',value->>'aggregateType',value->>'aggregateId', + value->>'scopeType',value->>'scopeId',value->>'expectedEpoch'), '[]'::JSONB) + INTO expected_tuples FROM jsonb_array_elements(freeze->'suppliedOwnedAffectedTuples'); + IF evidence->>'schema' IS DISTINCT FROM 'world-published-start-location-evidence/v1' + OR (SELECT count(*) FROM jsonb_object_keys(evidence)) <> 5 + OR selected IS DISTINCT FROM retained->'request' + OR (SELECT count(*) FROM jsonb_object_keys(selected)) <> 13 + OR selected->>'targetNamespace' IS DISTINCT FROM freeze->>'targetNamespace' + OR selected->>'canonicalTenantId' IS DISTINCT FROM freeze->>'canonicalTenantId' + OR selected->>'canonicalVersionId' IS DISTINCT FROM freeze->>'canonicalVersionId' + OR selected->>'intakeRequestId' IS DISTINCT FROM freeze->>'intakeRequestId' + OR selected->>'publicationFence' IS DISTINCT FROM freeze->>'publicationFence' + OR selected->>'publicationRequestId' IS DISTINCT FROM freeze->>'publicationRequestId' + OR selected->>'requestDigest' IS DISTINCT FROM freeze->>'requestDigest' + OR selected->>'versionStateEpoch' IS DISTINCT FROM freeze->>'versionStateEpoch' + OR selected->>'publishWorkflowId' IS DISTINCT FROM freeze->>'publishWorkflowId' + OR selected->>'appliedCommitId' IS DISTINCT FROM freeze->>'appliedCommitId' + OR selected->>'contentDigest' IS DISTINCT FROM freeze->>'contentDigest' + OR selected->>'digestSchemaVersion' IS DISTINCT FROM '3' + OR selected->>'digestSchemaVersion' IS DISTINCT FROM freeze->>'digestSchemaVersion' + OR selected->'worldAffectedTuples' IS DISTINCT FROM expected_tuples + OR decode(evidence->>'selectorReceiptBytesBase64','base64') IS DISTINCT FROM decode(retained->>'selectorReceiptBytes','base64') + OR decode(evidence->>'originalAccountBindingBytesBase64','base64') IS DISTINCT FROM decode(retained->>'originalAccountBindingBytes','base64') + OR decode(evidence->>'appliedResultBytesBase64','base64') IS DISTINCT FROM decode(retained->>'appliedResultBytes','base64') THEN + RAISE EXCEPTION 'Preparation selector differs from complete frozen request or retained release bytes' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT receipt FROM "${serviceSchema}".world_draft_start_location_receipt + WHERE request_id=frozen.request_id AND commit_id=frozen.commit_id; + SELECT * INTO STRICT application FROM "${serviceSchema}".world_draft_graph_application + WHERE operation_id=receipt.operation_id AND request_id=receipt.request_id AND commit_id=receipt.commit_id + AND authorization_fence_id=receipt.authorization_fence_id; + SELECT * INTO STRICT graph FROM "${serviceSchema}".world_topology_draft_commit + WHERE request_id=frozen.request_id AND commit_id=frozen.commit_id; + IF receipt.target_namespace IS DISTINCT FROM selected->>'targetNamespace' + OR receipt.canonical_tenant_id::TEXT IS DISTINCT FROM selected->>'canonicalTenantId' + OR receipt.canonical_version_id::TEXT IS DISTINCT FROM selected->>'canonicalVersionId' + OR receipt.binding_digest IS DISTINCT FROM graph.binding_digest + OR receipt.graph_digest IS DISTINCT FROM ('sha256:' || frozen.graph_sha256) + OR graph.graph_bytes IS DISTINCT FROM frozen.graph_bytes + OR graph.binding_json IS DISTINCT FROM frozen.binding_json + OR graph.owner_binding_json IS DISTINCT FROM frozen.owner_binding_json + OR receipt.account_binding_bytes IS DISTINCT FROM application.account_binding_bytes + OR receipt.account_binding_digest IS DISTINCT FROM application.account_binding_digest + OR receipt.receipt_bytes IS DISTINCT FROM decode(evidence->>'selectorReceiptBytesBase64','base64') + OR receipt.account_binding_bytes IS DISTINCT FROM decode(evidence->>'originalAccountBindingBytesBase64','base64') + OR application.result_bytes IS DISTINCT FROM decode(evidence->>'appliedResultBytesBase64','base64') + OR convert_from(application.result_bytes,'UTF8')::JSONB->>'schema' IS DISTINCT FROM 'world-draft-graph-applied/v2' + OR convert_from(application.result_bytes,'UTF8')::JSONB->>'status' IS DISTINCT FROM 'APPLIED' + OR NOT EXISTS (SELECT 1 FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".room r ON r.id=m.private_row_key + WHERE m.request_id=frozen.request_id AND m.commit_id=frozen.commit_id AND m.family='ROOM' + AND m.template_id=receipt.room_template_id AND m.canonical_tenant_id=receipt.canonical_tenant_id + AND m.canonical_version_id=receipt.canonical_version_id AND m.target_namespace=receipt.target_namespace + AND r.tenant_id=graph.local_tenant_key AND r.version_id=graph.local_version_key + AND m.tenant_id=r.tenant_id AND m.version_id=r.version_id) THEN + RAISE EXCEPTION 'Preparation selector lacks exact original Account/APPLIED/graph/ROOM evidence' USING ERRCODE = '23514'; + END IF; +END; +$$; +REVOKE ALL ON FUNCTION world_require_preparation_start_location(JSONB, JSONB, UUID) FROM PUBLIC; + +-- Amend only the input-schema gate and insert additional guards. Preserve the complete existing +-- V35/V40 guard body, grants, ownership, materialization writes and V1 historical input bytes. +DO $migration$ +DECLARE + original TEXT; + schema_anchor TEXT := $anchor$ IF p->>'schemaVersion' IS DISTINCT FROM '1' THEN$anchor$; + join_anchor TEXT := $anchor$ IF identity_row.operation_id::TEXT IS DISTINCT FROM topology->>'versionIdentityOperationId'$anchor$; + retry_anchor TEXT := $anchor$ IF FOUND THEN + IF prior.input_json IS DISTINCT FROM p_input_json$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_prepare_canonical_instance(text,text)'::REGPROCEDURE) INTO STRICT original; + IF (length(original)-length(replace(original,schema_anchor,'')))/length(schema_anchor) <> 1 + OR (length(original)-length(replace(original,join_anchor,'')))/length(join_anchor) <> 1 + OR (length(original)-length(replace(original,retry_anchor,'')))/length(retry_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one original preparation schema/join/retry guard'; + END IF; + original := replace(original,schema_anchor,$replacement$ IF p->>'schemaVersion' IS NULL OR p->>'schemaVersion' NOT IN ('1','2') THEN$replacement$); + original := replace(original,join_anchor,$replacement$ PERFORM "${serviceSchema}".world_require_preparation_start_location(p, binding_row.release_attestation_json::JSONB, capture_row.capture_id); + +$replacement$ || join_anchor); + original := replace(original,retry_anchor,$replacement$ IF FOUND THEN + IF p->>'schemaVersion' = '2' AND NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_preparation_start_location s + WHERE s.canonical_game_instance_id=prior.canonical_game_instance_id + AND s.world_instance_id=prior.world_instance_id + AND s.evidence_bytes=decode(p->>'worldStartLocationEvidenceBase64','base64')) THEN + RAISE EXCEPTION 'V2 preparation retry lacks original selector readback' USING ERRCODE='23514'; + END IF; + IF prior.input_json IS DISTINCT FROM p_input_json$replacement$); + EXECUTE original; +END; +$migration$; + +CREATE FUNCTION world_retain_preparation_start_location() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,"${serviceSchema}" +AS $$ +DECLARE + receipt "${serviceSchema}".world_draft_start_location_receipt%ROWTYPE; + mapping "${serviceSchema}".world_canonical_instance_topology_identity%ROWTYPE; + frozen "${serviceSchema}".world_canonical_frozen_topology%ROWTYPE; +BEGIN + IF NEW.input_json::JSONB->>'schemaVersion' = '1' THEN RETURN NEW; END IF; + SELECT * INTO STRICT frozen FROM "${serviceSchema}".world_canonical_frozen_topology WHERE capture_id=NEW.capture_id; + SELECT * INTO STRICT receipt FROM "${serviceSchema}".world_draft_start_location_receipt + WHERE request_id=frozen.request_id AND commit_id=frozen.commit_id; + SELECT * INTO STRICT mapping FROM "${serviceSchema}".world_canonical_instance_topology_identity + WHERE world_instance_id=NEW.world_instance_id AND canonical_game_instance_id=NEW.canonical_game_instance_id + AND family='ROOM' AND template_id=receipt.room_template_id; + INSERT INTO "${serviceSchema}".world_canonical_preparation_start_location + (canonical_game_instance_id,world_instance_id,canonical_tenant_id,canonical_version_id,room_template_id, + runtime_room_instance_id,receipt_digest,graph_digest,evidence_bytes) + VALUES (NEW.canonical_game_instance_id,NEW.world_instance_id,receipt.canonical_tenant_id,receipt.canonical_version_id, + receipt.room_template_id,mapping.runtime_room_instance_id,receipt.receipt_digest,receipt.graph_digest, + decode(NEW.input_json::JSONB->>'worldStartLocationEvidenceBase64','base64')); + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_preparation_retain_start_location AFTER INSERT ON world_canonical_instance_preparation + FOR EACH ROW EXECUTE FUNCTION world_retain_preparation_start_location(); + +CREATE FUNCTION world_guard_preparation_start_location() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,"${serviceSchema}" +AS $$ +DECLARE + prepared "${serviceSchema}".world_canonical_instance_preparation%ROWTYPE; + binding TEXT; + original JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Original canonical preparation selector is immutable and retained' USING ERRCODE='23514'; + END IF; + SELECT p.* INTO STRICT prepared FROM "${serviceSchema}".world_canonical_instance_preparation p + WHERE p.canonical_game_instance_id=NEW.canonical_game_instance_id + AND p.xmin::TEXT=(txid_current() % 4294967296)::TEXT; + original := prepared.input_json::JSONB; + SELECT release_attestation_json INTO STRICT binding FROM "${serviceSchema}".world_complete_launch_binding + WHERE binding_operation_id=(original->'launchBinding'->>'operationId')::UUID; + IF original->>'schemaVersion' IS DISTINCT FROM '2' + OR prepared.world_instance_id IS DISTINCT FROM NEW.world_instance_id + OR prepared.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR prepared.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR NEW.evidence_bytes IS DISTINCT FROM decode(original->>'worldStartLocationEvidenceBase64','base64') + OR NOT EXISTS (SELECT 1 FROM "${serviceSchema}".world_draft_start_location_receipt s + JOIN "${serviceSchema}".world_canonical_frozen_topology f ON f.request_id=s.request_id AND f.commit_id=s.commit_id + WHERE f.capture_id=prepared.capture_id AND s.canonical_tenant_id=NEW.canonical_tenant_id + AND s.canonical_version_id=NEW.canonical_version_id AND s.room_template_id=NEW.room_template_id + AND s.receipt_digest=NEW.receipt_digest AND s.graph_digest=NEW.graph_digest) + OR NOT EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_topology_identity m + JOIN "${serviceSchema}".room_instance r ON r.id=m.runtime_row_id + JOIN "${serviceSchema}".world_instance w ON w.id=m.world_instance_id + WHERE m.world_instance_id=prepared.world_instance_id AND m.canonical_game_instance_id=NEW.canonical_game_instance_id + AND m.family='ROOM' AND m.template_id=NEW.room_template_id + AND m.runtime_room_instance_id=NEW.runtime_room_instance_id AND r.room_instance_id=NEW.runtime_room_instance_id + AND r.tenant_id=w.tenant_id AND r.game_instance_id=w.game_instance_id) THEN + RAISE EXCEPTION 'Original preparation selector differs from exact authored/runtime ROOM mapping' USING ERRCODE='23514'; + END IF; + PERFORM "${serviceSchema}".world_require_preparation_start_location(original,binding::JSONB,prepared.capture_id); + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_preparation_start_location_guard BEFORE INSERT OR UPDATE OR DELETE ON world_canonical_preparation_start_location + FOR EACH ROW EXECUTE FUNCTION world_guard_preparation_start_location(); +CREATE TRIGGER trg_world_preparation_start_location_no_truncate BEFORE TRUNCATE ON world_canonical_preparation_start_location + FOR EACH STATEMENT EXECUTE FUNCTION world_guard_preparation_start_location(); +REVOKE ALL ON FUNCTION world_retain_preparation_start_location() FROM PUBLIC; +REVOKE ALL ON FUNCTION world_guard_preparation_start_location() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java index 3ddc2bebff..93ab4006d1 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java @@ -38,6 +38,55 @@ classes = WorldManagementServiceApplication.class, properties = "spring.grpc.server.port=0") class WorldCanonicalInstancePreparationPostgresIntegrationTest { + @Test + void selectorGuardPreservesInertV1ShapeAndDeniesPromotionOrMissingV2BeforeAllocation() { + long before = + Objects.requireNonNull(dsl.fetchOne("SELECT count(*) FROM world_instance")) + .get(0, Long.class); + UUID absentCapture = UUID.randomUUID(); + dsl.fetchOne( + "SELECT world_require_preparation_start_location(?::jsonb,?::jsonb,?)", + "{\"schemaVersion\":1}", + "{\"schemaVersion\":1}", + absentCapture); + for (String input : + java.util.List.of( + "{\"schemaVersion\":2}", + "{\"schemaVersion\":1,\"worldStartLocationEvidenceBase64\":\"e30=\"}")) { + assertThatThrownBy( + () -> + dsl.fetchOne( + "SELECT world_require_preparation_start_location(?::jsonb,?::jsonb,?)", + input, + "{\"schemaVersion\":1}", + absentCapture)) + .isInstanceOf(DataIntegrityViolationException.class); + } + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO world_canonical_preparation_start_location (canonical_game_instance_id,world_instance_id," + + "canonical_tenant_id,canonical_version_id,room_template_id,runtime_room_instance_id,receipt_digest,graph_digest,evidence_bytes) " + + "VALUES (?,1,?,?,?,1,?,?,?)", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + new byte[] {1})) + .isInstanceOf(RuntimeException.class); + assertThat( + Objects.requireNonNull(dsl.fetchOne("SELECT count(*) FROM world_instance")) + .get(0, Long.class)) + .isEqualTo(before); + assertThat( + Objects.requireNonNull( + dsl.fetchOne("SELECT count(*) FROM world_canonical_preparation_start_location")) + .get(0, Long.class)) + .isZero(); + } + private static final String NAMESPACE = "firemud"; @Container diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index d201cbaab8..2d99450abb 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -20,9 +20,13 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; @@ -103,6 +107,12 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private WorldAuthoredSourceIntakeRepository intakeRepository; @Autowired private WorldDesignPublicationFenceRepository fence; @Autowired private ObjectMapper mapper; + @Autowired private WorldAuthoredGraphSnapshotRepository snapshots; + + @Autowired + private net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService + digestService; + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; @MockitoBean(enforceOverride = true) @@ -112,6 +122,805 @@ static void configure(DynamicPropertyRegistry registry) { @MockitoBean private GameSessionClient gameSessionClient; @MockitoBean private EntityManagementClient entityManagementClient; + @Test + void releaseSelectorMaterializesItsOriginalRoomAndExactlyRetriesWithSeparateRuntimeMapping() { + Fixture f = fixture(); + var original = application(generationFreePlan(f)); + var lastRoom = + original.plan().graph().nodes().stream() + .filter( + node -> + node.mutation().getAggregateType() + == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .map(node -> node.templateId()) + .toList() + .getLast(); + var application = withStartRoom(original, lastRoom); + appliedComponent().apply(application); + var frozen = capture(application.plan()); + var selector = + publishedEvidence( + publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + var input = preparationInput(f, frozen, selector); + var repository = preparationRepository(); + var service = preparationComponent(repository); + var result = service.prepare(input); + assertThat(result.startLocation().roomTemplateId()).isEqualTo(lastRoom); + assertThat(result.runtimeRoomInstanceId()).isPositive(); + assertThat(result.storageStatus()).isEqualTo("MATERIALIZED_UNVERIFIED"); + assertThat(result.startLocation().roomTemplateId()) + .isNotEqualTo(input.topologyPlan().rooms().getFirst().identity().templateId()); + var mapped = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT m.template_id,r.room_instance_id FROM world_canonical_instance_topology_identity m " + + "JOIN room_instance r ON r.id=m.runtime_row_id WHERE m.world_instance_id=? AND m.family='ROOM' AND m.template_id=?", + result.association().worldInstanceId(), + lastRoom)); + assertThat(mapped.get("room_instance_id", Long.class)) + .isEqualTo(result.runtimeRoomInstanceId()); + byte[] before = preparationRows(input.canonicalGameInstanceId()); + assertThat(preparationComponent(preparationRepository()).prepare(input)).isEqualTo(result); + assertThat(preparationRepository().readOwnerPreparation(input)).contains(result); + assertThat(preparationRows(input.canonicalGameInstanceId())).containsExactly(before); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_canonical_preparation_start_location SET runtime_room_instance_id=runtime_room_instance_id+1 WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId())) + .hasMessageContaining("immutable and retained"); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM world_canonical_preparation_start_location WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId())) + .hasMessageContaining("immutable and retained"); + assertOrigin(); + } + + @Test + void releaseSelectorRejectsChangedFrozenRequestAndSqlSubstitutionWithoutRuntimeWrites() { + Fixture f = fixture(); + var application = application(generationFreePlan(f)); + appliedComponent().apply(application); + var frozen = capture(application.plan()); + var selector = + publishedEvidence( + publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + var selected = selector.request(); + var changed = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + selected.targetNamespace(), + selected.canonicalTenantId(), + selected.canonicalVersionId(), + selected.intakeRequestId(), + UUID.randomUUID(), + selected.publicationRequestId(), + selected.requestDigest(), + selected.versionStateEpoch(), + selected.publishWorkflowId(), + selected.appliedCommitId(), + selected.contentDigest(), + selected.digestSchemaVersion(), + selected.worldAffectedTuples()), + selector.selectorReceiptBytes(), + selector.originalAccountBindingBytes(), + selector.appliedResultBytes()); + assertThatThrownBy(() -> preparationInput(f, frozen, changed)) + .hasMessageContaining("exact frozen request"); + var input = preparationInput(f, frozen, selector); + var encoded = + (tools.jackson.databind.node.ObjectNode) + mapper.readTree(WorldCanonicalInstancePreparationRepository.inputJson(input)); + encoded.put( + "worldStartLocationEvidenceBase64", + java.util.Base64.getEncoder().encodeToString(changed.canonicalBytes())); + String substituted = mapper.writeValueAsString(encoded); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> + dsl.fetchOne( + "SELECT * FROM world_prepare_canonical_instance(?,?)", + substituted, + WorldDraftGraphAppliedResult.digest( + substituted.getBytes(StandardCharsets.UTF_8))))) + .hasMessageContaining("complete frozen request"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_instance WHERE tenant_id=?", + f.intake().localTenantKey())) + .get(0, Long.class)) + .isZero(); + assertThat(preparationRepository().readOwnerPreparation(input)).isEmpty(); + assertOrigin(); + } + + @Test + void inertV1PreparationRetainsOriginalBytesAndCannotGainSelectorOnRetry() { + Fixture f = fixture(); + var application = application(generationFreePlan(f)); + appliedComponent().apply(application); + var frozen = capture(application.plan()); + var input = preparationInput(f, frozen, null); + var repository = preparationRepository(); + var first = preparationComponent(repository).prepare(input); + assertThat(first.startLocation()).isNull(); + assertThat(first.runtimeRoomInstanceId()).isNull(); + byte[] before = preparationRows(input.canonicalGameInstanceId()); + assertThat(preparationComponent(preparationRepository()).prepare(input)).isEqualTo(first); + assertThat(preparationRows(input.canonicalGameInstanceId())).containsExactly(before); + assertThat(WorldCanonicalInstancePreparationRepository.inputJson(input)) + .doesNotContain("worldStartLocationEvidence"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_preparation_start_location WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId())) + .get(0, Long.class)) + .isZero(); + // A new direct selector write cannot reinterpret the existing V1 preparation. + var receipt = + appliedRepository() + .readCommitted(application) + .orElseThrow() + .startLocationReceipt() + .orElseThrow(); + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO world_canonical_preparation_start_location (canonical_game_instance_id,world_instance_id,canonical_tenant_id,canonical_version_id,room_template_id," + + "runtime_room_instance_id,receipt_digest,graph_digest,evidence_bytes) VALUES (?,?,?,?,?,1,?,?,?)", + input.canonicalGameInstanceId(), + first.association().worldInstanceId(), + receipt.startLocation().tenantId(), + receipt.startLocation().versionId(), + receipt.startLocation().roomTemplateId(), + receipt.receiptDigest(), + receipt.graphDigest(), + receipt.canonicalBytes())) + .isInstanceOf(RuntimeException.class); + assertThat(preparationRows(input.canonicalGameInstanceId())).containsExactly(before); + assertOrigin(); + } + + @Test + void selectorPreparationLateFenceLossRollsBackSelectorRuntimeAndAssociationTogether() { + Fixture f = fixture(); + var application = application(generationFreePlan(f)); + appliedComponent().apply(application); + var frozen = capture(application.plan()); + var selector = + publishedEvidence( + publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + var input = preparationInput(f, frozen, selector); + var component = + new WorldCanonicalInstancePreparationService( + preparationRepository(), + ignored -> + new WorldCanonicalInstancePreparationService.HeldCommitAuthority() { + private int calls; + + public void requireHeld() { + calls++; + if (calls == 3) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_preparation_start_location WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId())) + .get(0, Long.class)) + .isEqualTo(1L); + throw new IllegalStateException("stipulated late Account fence loss"); + } + } + + public void close() {} + }); + assertThatThrownBy(() -> component.prepare(input)) + .hasMessageContaining("late Account fence loss"); + for (String table : + List.of( + "world_instance", + "world_canonical_instance_association", + "world_canonical_instance_preparation", + "world_canonical_preparation_start_location")) { + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM " + table + " WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId())) + .get(0, Long.class)) + .isZero(); + } + assertThat(appliedRepository().readCommitted(application).orElseThrow().canonicalBytes()) + .containsExactly(selector.appliedResultBytes()); + assertOrigin(); + } + + private WorldDraftTopologyCommitPlan generationFreePlan(Fixture f) { + var original = plan(f); + var binding = original.binding(); + List revisions = new ArrayList<>(); + for (var revision : binding.revisions()) { + if (revision.owner() != Owner.WORLD_MANAGEMENT) { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisions.size()), + revision.revisionId(), + revision.owner(), + revision.payload())); + continue; + } + try { + var value = WorldDesignMutationRevision.newBuilder(); + JsonFormat.parser().merge(revision.payload(), value); + if (value.hasGenerationRule() || value.hasWorldEntitySpawnBinding()) continue; + if (value.hasRegion()) + value.setRegion( + value.getRegion().toBuilder() + .clearGenerationSeed() + .clearGeneratorType() + .clearGeneratorParams()); + if (value.hasFreshGraphDeclaration()) { + var declaration = value.getFreshGraphDeclaration().toBuilder(); + for (int index = 0; index < declaration.getFamilyCountsCount(); index++) { + var family = declaration.getFamilyCounts(index).getFamily(); + if (family == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE + || family + == WorldDesignAggregateType + .WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING) { + declaration.setFamilyCounts( + index, declaration.getFamilyCounts(index).toBuilder().setCount(0)); + } + } + value.setFreshGraphDeclaration(declaration); + } + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisions.size()), + revision.revisionId(), + revision.owner(), + JsonFormat.printer().print(value))); + } catch (InvalidProtocolBufferException failure) { + throw new IllegalStateException(failure); + } + } + return WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + binding.target(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + revisions, + binding.affectedUnits().stream() + .filter( + unit -> + !unit.aggregateType().equals("GENERATION_RULE") + && !unit.aggregateType().equals("WORLD_ENTITY_SPAWN_BINDING")) + .toList()), + original.ownerBinding()); + } + + @Test + void v41MaterializedV1HistoryRemainsByteExactAndRetryableAfterV42WithoutSelectorPromotion() { + String schema = "world_v41_preparation_" + UUID.randomUUID().toString().replace("-", ""); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_world_management_service") + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion("41")) + .load() + .migrate(); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + // Reuse exactly the same actual producer/preparation fixture against the historical schema. + var historical = new WorldDraftGraphApplicationPostgresIntegrationTest(); + historical.dsl = + DSL.using( + new TransactionAwareDataSourceProxy(dataSource), + SQLDialect.POSTGRES, + new org.jooq.conf.Settings().withRenderSchema(false)); + historical.manager = new DataSourceTransactionManager(dataSource); + historical.intakeRepository = proxiedIntakeRepository(historical.dsl, historical.manager); + historical.fence = + new WorldDesignPublicationFenceRepository(historical.dsl, historical.intakeRepository); + historical.mapper = mapper; + historical.snapshots = new WorldAuthoredGraphSnapshotRepository(historical.dsl); + historical.digestService = + new net.firedevops.firemud.worldmanagement.service.impl.WorldDraftDesignDigestServiceImpl( + new net.firedevops.firemud.worldmanagement.repository.RegionRepository(historical.dsl), + new net.firedevops.firemud.worldmanagement.repository.ZoneRepository(historical.dsl), + new net.firedevops.firemud.worldmanagement.repository.RoomRepository(historical.dsl), + new net.firedevops.firemud.worldmanagement.repository.RoomExitRepository( + historical.dsl), + new net.firedevops.firemud.worldmanagement.repository.GenerationRuleRepository( + historical.dsl), + new net.firedevops.firemud.worldmanagement.repository.WorldEntitySpawnBindingRepository( + historical.dsl), + mapper); + Fixture f = historical.fixture(); + var application = historical.application(historical.generationFreePlan(f)); + var applied = historical.appliedComponent().apply(application); + var frozen = historical.capture(application.plan()); + var input = historical.preparationInput(f, frozen, null); + var first = historical.preparationComponent(historical.preparationRepository()).prepare(input); + Map before = historical.preparationHistoryRows(); + byte[] originalApplied = applied.canonicalBytes(); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_world_management_service") + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + assertThat(historical.preparationHistoryRows()).isEqualTo(before); + assertThat(historical.preparationComponent(historical.preparationRepository()).prepare(input)) + .isEqualTo(first); + assertThat(historical.preparationHistoryRows()).isEqualTo(before); + assertThat( + historical + .appliedRepository() + .readCommitted(application) + .orElseThrow() + .canonicalBytes()) + .containsExactly(originalApplied); + assertThat(first.startLocation()).isNull(); + assertThat(first.runtimeRoomInstanceId()).isNull(); + assertThat( + Objects.requireNonNull( + historical.dsl.fetchOne( + "SELECT count(*) FROM world_canonical_preparation_start_location")) + .get(0, Long.class)) + .isZero(); + historical.assertOrigin(); + } + + private Map preparationHistoryRows() { + Map result = new LinkedHashMap<>(); + for (String table : + List.of( + "world_authored_source_intake", + "world_authored_version_identity", + "world_complete_launch_binding", + "world_topology_draft_commit", + "world_draft_graph_application", + "world_draft_start_location_receipt", + "world_canonical_frozen_topology", + "world_instance", + "region_instance", + "zone_instance", + "room_instance", + "room_instance_exit", + "world_canonical_instance_topology_identity", + "world_canonical_instance_preparation", + "world_canonical_instance_association")) { + result.put( + table, + Objects.requireNonNull( + dsl.fetchOne( + "SELECT coalesce(jsonb_agg(value ORDER BY value::text),'[]'::jsonb)::text " + + "FROM (SELECT to_jsonb(t) AS value FROM " + + table + + " t) rows")) + .get(0, String.class)); + } + return result; + } + + private WorldPublishedStartLocationEvidence publishedEvidence( + WorldPublishedStartLocationSource source) { + var freeze = source.frozenTopology().request().freeze(); + return new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + freeze.targetNamespace(), + freeze.canonicalTenantId(), + freeze.canonicalVersionId(), + freeze.intakeRequestId(), + freeze.publicationFence(), + freeze.publicationRequestId(), + freeze.requestDigest(), + freeze.versionStateEpoch(), + freeze.publishWorkflowId(), + freeze.appliedCommitId(), + freeze.contentDigest(), + freeze.digestSchemaVersion(), + freeze.suppliedOwnedAffectedTuples().stream() + .map( + tuple -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) + .toList()), + source.selectorReceipt().canonicalBytes(), + source.appliedResult().application().operation().accountBindingBytes(), + source.appliedResult().canonicalBytes()); + } + + private WorldCanonicalInstancePreparation.Input preparationInput( + Fixture f, + WorldCanonicalFrozenTopology frozen, + WorldPublishedStartLocationEvidence selector) { + var source = f.intake().source(); + String control = "prepare-" + UUID.randomUUID(); + var descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + control, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + 71L, + false, + null, + false, + null, + false, + null, + false, + null), + "ld-" + UUID.randomUUID(), + GAME_DESIGN_VERSION, + false, + null, + "{}", + "generation-free", + 2L, + 97L, + "release-" + UUID.randomUUID(), + false, + null); + var freeze = frozen.request().freeze(); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(GAME_DESIGN_VERSION), + false, + null, + freeze.appliedCommitId(), + "WORLD_MANAGEMENT".equals(owner) ? freeze.contentDigest() : "a".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "b".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence release = + selector == null + ? AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + source.canonicalTenantId(), + f.version().canonicalVersionId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + freeze.publishWorkflowId(), + freeze.appliedCommitId(), + participants, + "sha256:" + "c".repeat(64), + 1, + List.of(), + List.of(), + List.of("LOOK"), + descriptor.generationConfigRevision()) + : AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + source.canonicalTenantId(), + f.version().canonicalVersionId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + freeze.publishWorkflowId(), + freeze.appliedCommitId(), + participants, + "sha256:" + "c".repeat(64), + 1, + List.of(), + List.of(), + List.of("LOOK"), + descriptor.generationConfigRevision(), + selector); + var evidence = new CompleteLaunchBindingEvidence(descriptor, release); + var launch = + Objects.requireNonNull( + ownerTransaction() + .execute( + status -> + new WorldCompleteLaunchBindingRepository(dsl) + .acceptFresh(NAMESPACE, f.intake(), evidence))); + UUID instance = UUID.randomUUID(); + UUID read = UUID.randomUUID(); + var request = + new WorldCanonicalInstanceAssociation.GameSessionReadRequest( + read, + NAMESPACE, + source.canonicalTenantId(), + source.worldSlug(), + instance, + control, + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + var response = + new WorldCanonicalInstanceAssociation.GameSessionReadEvidence( + read, + NAMESPACE, + source.canonicalTenantId(), + source.worldSlug(), + instance, + control, + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest(), + UUID.randomUUID(), + "SHARED", + true, + "PREPARING", + 1L, + descriptor, + release); + return new WorldCanonicalInstancePreparation.Input( + request, response, launch, f.version(), WorldCanonicalInstanceTopologyPlan.create(frozen)); + } + + private WorldCanonicalInstancePreparationRepository preparationRepository() { + return new WorldCanonicalInstancePreparationRepository( + dsl, manager, new WorldCanonicalInstanceAssociationRepository(dsl), frozenRepository()); + } + + private WorldCanonicalInstancePreparationService preparationComponent( + WorldCanonicalInstancePreparationRepository repository) { + // Stipulated local verifier only: no production producer, currentness, lifecycle or admission + // claim. + return new WorldCanonicalInstancePreparationService( + repository, + input -> + new WorldCanonicalInstancePreparationService.HeldCommitAuthority() { + private boolean open = true; + + public void requireHeld() { + if (!open) throw new IllegalStateException("closed fixture authority"); + } + + public void close() { + open = false; + } + }); + } + + private byte[] preparationRows(UUID instance) { + return Objects.requireNonNull( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT convert_to(jsonb_build_object('preparation',to_jsonb(p),'selector',to_jsonb(s))::text,'UTF8') " + + "FROM world_canonical_instance_preparation p LEFT JOIN world_canonical_preparation_start_location s USING(canonical_game_instance_id) WHERE p.canonical_game_instance_id=?", + instance)) + .get(0, byte[].class)); + } + + @Test + void publishedSelectorJoinsExactFrozenCheckpointToOriginalAppliedWithoutWrites() { + Fixture f = fixture(); + var application = application(f); + var applied = appliedComponent().apply(application); + var capture = capture(application.plan()); + var request = capture.request().freeze(); + var source = publishedSelectors().readCommitted(request).orElseThrow(); + assertThat(source.selectorReceipt()).isEqualTo(applied.startLocationReceipt().orElseThrow()); + assertThat(source.appliedResult().canonicalBytes()).containsExactly(applied.canonicalBytes()); + assertThat(source.frozenTopology().resultBytes()).containsExactly(capture.resultBytes()); + assertThat(source.frozenTopology().status()).isEqualTo("CAPTURED_UNVERIFIED"); + assertThat(source.appliedResult().application().operation().accountBindingBytes()) + .containsExactly(application.operation().accountBindingBytes()); + var another = application(fixture()); + var anotherResult = appliedComponent().apply(another); + var substitutedApplications = + org.mockito.Mockito.mock(WorldDraftGraphApplicationRepository.class); + org.mockito.Mockito.when( + substitutedApplications.readCommitted( + org.mockito.ArgumentMatchers.eq(NAMESPACE), + org.mockito.ArgumentMatchers.any(byte[].class))) + .thenReturn(java.util.Optional.of(anotherResult)); + assertThatThrownBy( + () -> + new WorldPublishedStartLocationRepository( + dsl, frozenRepository(), substitutedApplications) + .readCommitted(request)) + .hasMessageContaining("differs from original frozen application"); + // A plausible result for a distinct Account operation on the same plan is also substitution. + org.mockito.Mockito.when( + substitutedApplications.readCommitted( + org.mockito.ArgumentMatchers.eq(NAMESPACE), + org.mockito.ArgumentMatchers.any(byte[].class))) + .thenReturn( + java.util.Optional.of( + WorldDraftGraphAppliedResult.create( + changedAccountApplication(application), applied.graphBytes()))); + assertThatThrownBy( + () -> + new WorldPublishedStartLocationRepository( + dsl, frozenRepository(), substitutedApplications) + .readCommitted(request)) + .hasMessageContaining("differs from original frozen application"); + byte[] before = retainedApplicationBytes(application); + assertThat(publishedSelectors().readCommitted(request).orElseThrow().selectorReceipt()) + .isEqualTo(source.selectorReceipt()); + assertThat(retainedApplicationBytes(application)).containsExactly(before); + assertThat(count(f, "world_draft_graph_application")).isEqualTo(1); + assertThat(count(f, "world_draft_start_location_receipt")).isEqualTo(1); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_frozen_topology WHERE publication_fence=?", + request.publicationFence())) + .get(0, Long.class)) + .isEqualTo(1L); + assertThatThrownBy( + () -> + publishedSelectors() + .readCommitted( + changedSelection(request, "changed-request", request.contentDigest()))) + .hasMessageContaining("canonical full-version workflow identity"); + assertThatThrownBy( + () -> + publishedSelectors() + .readCommitted( + changedSelection(request, request.publicationRequestId(), "c".repeat(64)))) + .hasMessageContaining("changed complete input or checkpoint"); + assertThatThrownBy( + () -> ownerTransaction().execute(status -> publishedSelectors().readCommitted(request))) + .hasMessageContaining("no caller transaction"); + assertOrigin(); + } + + @Test + void permissionUnverifiedGraphAndFrozenHistoryCannotSupplyPublishedSelector() { + var plan = plan(fixture()); + component().store(plan); + var capture = capture(plan); + assertThat(frozenRepository().readCommitted(capture.request().freeze())).isPresent(); + assertThatThrownBy(() -> publishedSelectors().readCommitted(capture.request().freeze())) + .hasMessageContaining("lacks original APPLIED application"); + assertOrigin(); + } + + private byte[] retainedApplicationBytes(WorldDraftGraphApplication application) { + return Objects.requireNonNull( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT convert_to(to_jsonb(a)::text,'UTF8') FROM world_draft_graph_application a WHERE operation_id=?", + application.operation().operationId())) + .get(0, byte[].class)); + } + + private WorldAuthoredGraphSnapshot.CaptureRequest changedSelection( + WorldAuthoredGraphSnapshot.CaptureRequest request, String publicationRequest, String digest) { + return new WorldAuthoredGraphSnapshot.CaptureRequest( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + request.publicationFence(), + publicationRequest, + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + digest, + request.digestSchemaVersion(), + request.suppliedOwnedAffectedTuples()); + } + + private WorldCanonicalFrozenTopologyRepository frozenRepository() { + return new WorldCanonicalFrozenTopologyRepository(dsl, snapshots, repository(), digestService); + } + + private WorldPublishedStartLocationRepository publishedSelectors() { + return new WorldPublishedStartLocationRepository(dsl, frozenRepository(), appliedRepository()); + } + + private WorldCanonicalFrozenTopology capture(WorldDraftTopologyCommitPlan plan) { + var owner = plan.ownerBinding(); + String publicationRequest = "selector-" + UUID.randomUUID(); + var evidence = + new WorldDesignPublicationFenceEvidence( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.versionIdentityOperationId(), + owner.gameDesignVersionId(), + owner.intakeRequestId(), + owner.intakeOperationId(), + owner.intakeRequestDigest(), + owner.sourceOperationId(), + owner.sourceEvidenceDigest(), + owner.intakeReceiptDigest(), + publicationRequest, + "a".repeat(64), + 1, + "publish:" + owner.canonicalTenantId() + ":publish-request:" + publicationRequest); + var attempt = + Objects.requireNonNull( + ownerTransaction() + .execute( + status -> + fence.claimFreeze( + evidence, + () -> { + var identity = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT local_tenant_key,local_version_key FROM world_authored_version_identity WHERE operation_id=?", + owner.versionIdentityOperationId())); + var digest = + digestService.getDraftDesignDigest( + identity.get("local_tenant_key", Long.class).toString(), + identity.get("local_version_key", Long.class).toString()); + return new WorldDesignPublicationFenceEvidence.Checkpoint( + plan.binding().commitId().toString(), digest.contentDigest(), 3); + }))); + var tuples = + plan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + var request = + new WorldAuthoredGraphSnapshot.CaptureRequest( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.intakeRequestId(), + attempt.publicationFence(), + publicationRequest, + evidence.requestDigest(), + evidence.versionStateEpoch(), + evidence.publishWorkflowId(), + attempt.checkpoint().appliedCommitId(), + attempt.checkpoint().contentDigest(), + attempt.checkpoint().digestSchemaVersion(), + tuples); + return new WorldCanonicalFrozenTopologyService(frozenRepository(), manager) + .capture(new WorldCanonicalFrozenTopology.Request(plan, request)); + } + @Test void freshApplicationRetainsCompleteExactGraphAndOriginalAccountReadbackAndRetriesAfterFreeze() { Fixture f = fixture(); @@ -486,7 +1295,7 @@ void extraRetainedOptionalFamilyRowDeniesFreshGraphApplication() { assertThat(component().store(priorPlan).status()).isEqualTo("STORED_PERMISSION_UNVERIFIED"); assertThatThrownBy(() -> appliedComponent().apply(application)) - .hasMessageContaining("extra or missing actual"); + .hasMessageContaining("Fresh World topology conflicts with retained region"); assertThat(appliedRepository().readCommitted(application)).isEmpty(); assertThat(count(f, "world_authored_topology_identity")).isEqualTo(4); assertThat(count(f, "world_draft_start_location_receipt")).isZero(); @@ -582,6 +1391,53 @@ void v39AppliedV1HistoryRemainsByteExactAndRetryableAfterV41() throws Exception assertThat(exact.canonicalBytes()).containsExactly(legacyResult.canonicalBytes()); assertThat(exact.graphBytes()).containsExactly(legacyResult.graphBytes()); assertThat(exact.startLocationReceipt()).isEmpty(); + // Negative source-reader proof uses real retained v1 APPLIED bytes, with a stipulated frozen + // selection only. This is not positive capture or publication-checkpoint proof for v1 history. + var historicalFreeze = + new WorldAuthoredGraphSnapshot.CaptureRequest( + NAMESPACE, + historicalPlan.ownerBinding().canonicalTenantId(), + historicalPlan.ownerBinding().canonicalVersionId(), + historicalPlan.ownerBinding().intakeRequestId(), + UUID.randomUUID(), + "historical-selector-denial", + "a".repeat(64), + 1, + "publish:" + + historicalPlan.ownerBinding().canonicalTenantId() + + ":publish-request:historical-selector-denial", + historicalPlan.binding().commitId().toString(), + "b".repeat(64), + 3, + historicalPlan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList()); + var historicalSelection = + new WorldCanonicalFrozenTopology( + UUID.randomUUID(), + new WorldCanonicalFrozenTopology.Request(historicalPlan, historicalFreeze), + f.version(), + new WorldCanonicalAuthoredGraphReader().read(historicalPlan, exact.graphBytes()), + exact.graphBytes(), + new byte[0], + new byte[0]); + var stipulatedFrozen = org.mockito.Mockito.mock(WorldCanonicalFrozenTopologyRepository.class); + org.mockito.Mockito.when(stipulatedFrozen.readCommitted(historicalFreeze)) + .thenReturn(java.util.Optional.of(historicalSelection)); + assertThatThrownBy( + () -> + new WorldPublishedStartLocationRepository( + retainedDsl, stipulatedFrozen, retainedApplications) + .readCommitted(historicalFreeze)) + .hasMessageContaining("lacks original selector receipt"); assertThat( retainedApplications .readCommitted(NAMESPACE, historicalApplication.operation().accountBindingBytes()) diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftStartLocationReceiptTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftStartLocationReceiptTest.java new file mode 100644 index 0000000000..b1599785f3 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftStartLocationReceiptTest.java @@ -0,0 +1,47 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.UUID; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import org.junit.jupiter.api.Test; + +class WorldDraftStartLocationReceiptTest { + @Test + void normalConstructionRetainsConstructorValuesAndSharedCanonicalBytes() { + var evidence = + WorldDraftStartLocationEvidence.create( + "test", + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + uuid("44444444-4444-4444-8444-444444444444"), + uuid("55555555-5555-4555-8555-555555555555"), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + "sha256:" + "0".repeat(64), + "sha256:" + "1".repeat(64), + new RoomTemplateRef( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + uuid("77777777-7777-4777-8777-777777777777")), + "sha256:" + "2".repeat(64)); + + var receipt = + new WorldDraftStartLocationReceipt( + evidence.targetNamespace(), + evidence.operationId(), + evidence.requestId(), + evidence.commitId(), + evidence.authorizationFenceId(), + evidence.accountBindingDigest(), + evidence.bindingDigest(), + evidence.startLocation(), + evidence.graphDigest(), + evidence.receiptDigest()); + + assertThat(receipt.canonicalBytes()).containsExactly(evidence.canonicalBytes()); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationReadGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationReadGrpcServiceTest.java new file mode 100644 index 0000000000..3369c919d2 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationReadGrpcServiceTest.java @@ -0,0 +1,159 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import net.firedevops.firemud.worldmanagement.tenant.WorldPublishedStartLocationReadGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldPublishedStartLocationRepository; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationResponse; +import org.junit.jupiter.api.Test; + +class WorldPublishedStartLocationReadGrpcServiceTest { + @Test + void rejectsMissingOrSubstitutedPeerBeforeDecodingOrStorageAccess() { + var repository = mock(WorldPublishedStartLocationRepository.class); + var service = new WorldPublishedStartLocationReadGrpcService(repository, "test"); + var malformed = + ReadWorldPublishedStartLocationRequest.newBuilder().setSchemaVersion(-1).build(); + + Collector missing = new Collector(); + service.readWorldPublishedStartLocation(malformed, missing); + assertThat(missing.error).isEqualTo(Status.Code.PERMISSION_DENIED); + + Collector wrongService = new Collector(); + Context context = + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer("account-service", "test")); + Context previous = context.attach(); + try { + service.readWorldPublishedStartLocation(malformed, wrongService); + } finally { + context.detach(previous); + } + assertThat(wrongService.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void rejectsAuthenticatedEndUserContextEvenWithCorrectWorkloadPeerBeforeDecoding() { + var repository = mock(WorldPublishedStartLocationRepository.class); + var service = new WorldPublishedStartLocationReadGrpcService(repository, "test"); + Collector response = new Collector(); + SessionContext.setContext("11111111-1111-4111-8111-111111111111", List.of(), Map.of()); + Context context = + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer("game-design-service", "test")); + Context previous = context.attach(); + try { + service.readWorldPublishedStartLocation( + ReadWorldPublishedStartLocationRequest.newBuilder().setSchemaVersion(-1).build(), + response); + } finally { + context.detach(previous); + SessionContext.clear(); + } + assertThat(response.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void wrongNamespaceIsDeniedBeforeOwnerRead() { + var repository = mock(WorldPublishedStartLocationRepository.class); + var service = new WorldPublishedStartLocationReadGrpcService(repository, "test"); + Collector result = callAsGameDesign(service, request("other")); + assertThat(result.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void missingSelectionAndConflictingSelectionFailClosed() { + var repository = mock(WorldPublishedStartLocationRepository.class); + var service = new WorldPublishedStartLocationReadGrpcService(repository, "test"); + var request = request("test"); + when(repository.readCommitted(any())) + .thenReturn(Optional.empty()) + .thenThrow(new ConflictException("changed frozen selection")); + + Collector missing = callAsGameDesign(service, request); + assertThat(missing.error).isEqualTo(Status.Code.NOT_FOUND); + Collector changed = callAsGameDesign(service, request); + assertThat(changed.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + verify(repository, org.mockito.Mockito.times(2)).readCommitted(any()); + } + + private static Collector callAsGameDesign( + WorldPublishedStartLocationReadGrpcService service, + ReadWorldPublishedStartLocationRequest request) { + Collector response = new Collector(); + Context context = + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer("game-design-service", "test")); + Context previous = context.attach(); + try { + service.readWorldPublishedStartLocation(request, response); + } finally { + context.detach(previous); + } + return response; + } + + private static ReadWorldPublishedStartLocationRequest request(String namespace) { + return ReadWorldPublishedStartLocationRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(namespace) + .setCanonicalTenantId("11111111-1111-4111-8111-111111111111") + .setCanonicalVersionId("22222222-2222-4222-8222-222222222222") + .setIntakeRequestId("33333333-3333-4333-8333-333333333333") + .setPublicationFence("44444444-4444-4444-8444-444444444444") + .setPublicationRequestId("publication-request") + .setRequestDigest("a".repeat(64)) + .setVersionStateEpoch(5L) + .setPublishWorkflowId("publish-workflow") + .setAppliedCommitId("55555555-5555-4555-8555-555555555555") + .setContentDigest("b".repeat(64)) + .setDigestSchemaVersion(3) + .build(); + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static final class Collector + implements StreamObserver { + private ReadWorldPublishedStartLocationResponse value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(ReadWorldPublishedStartLocationResponse next) { + value = next; + } + + @Override + public void onError(Throwable failure) { + assertThat(value).isNull(); + assertThat(completed).isFalse(); + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} From ec3bff6f3b1361cf56ad6450bc8fca983652f9e0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 03:14:33 +1300 Subject: [PATCH 02/13] Validate complete selector carrier fixtures and require exact PostgreSQL cases --- .github/workflows/ci.yml | 9 +++++++++ .../game-authoring-publishing-and-activation.md | 2 ++ .../world-runtime-and-movement.md | 2 ++ services/game-design-service/build.gradle.kts | 12 ++++++++++++ .../service/impl/PublishedWorldSelectorFixtures.java | 0 ...ishedReleaseCanonicalIdentityIntegrationTest.java | 11 ++++++----- ...DraftGraphApplicationPostgresIntegrationTest.java | 9 ++++++++- 7 files changed, 39 insertions(+), 6 deletions(-) rename services/game-design-service/src/{test/java/unit => sharedTest/java}/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java (100%) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 087f843294..8df5425a29 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -995,6 +995,9 @@ jobs: --require-case 'integration.net.firedevops.firemud.gamedesign.repository.PublishedReleaseCanonicalIdentityIntegrationTest#repositoryNestedTransactionRollsBackWithOuterSpringPublisherTransaction()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.PublishedReleaseCanonicalIdentityIntegrationTest#deniesWrongTenantNilAndSubstitutedCallerOrDatabaseIdentityWithoutGrowingBundles()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.PublishedReleaseCanonicalIdentityIntegrationTest#bundleIdentityIsImmutableRetainedNullCannotBeBackfilledAndMetadataCannotBeDeleted()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.PublishedReleaseCanonicalIdentityIntegrationTest#selectorV2RetainsCompleteOriginalEvidenceAndExactlyReplaysWithoutReplacingRelease()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.PublishedReleaseCanonicalIdentityIntegrationTest#concurrentExactSelectorRetriesCommitOneImmutableBundle()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.PublishedReleaseCanonicalIdentityIntegrationTest#sqlGuardRejectsMissingInjectedAndMismatchedSelectorBindingsWithoutAnyRelease()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepositoryIntegrationTest#v37LeavesRetainedVersionTupleAndXminUnchangedAndDeniesItsUnmappedIdentity()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepositoryIntegrationTest#freezesOnlyExactMappedBytesAndRetriesFromCommittedSnapshotAfterNewAssetAndServiceRestart()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepositoryIntegrationTest#durableHeaderDistinguishesProvedEmptySelectionFromMissingSnapshot()' \ @@ -2216,6 +2219,11 @@ jobs: bash dev-tools/validation/inspect-test-results.sh \ --strict \ --require-suite net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#releaseSelectorMaterializesItsOriginalRoomAndExactlyRetriesWithSeparateRuntimeMapping()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#releaseSelectorRejectsChangedFrozenRequestAndSqlSubstitutionWithoutRuntimeWrites()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#inertV1PreparationRetainsOriginalBytesAndCannotGainSelectorOnRetry()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#selectorPreparationLateFenceLossRollsBackSelectorRuntimeAndAssociationTogether()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#v41MaterializedV1HistoryRemainsByteExactAndRetryableAfterV42WithoutSelectorPromotion()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#publishedSelectorJoinsExactFrozenCheckpointToOriginalAppliedWithoutWrites()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#permissionUnverifiedGraphAndFrozenHistoryCannotSupplyPublishedSelector()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#freshApplicationRetainsCompleteExactGraphAndOriginalAccountReadbackAndRetriesAfterFreeze()' \ @@ -2368,6 +2376,7 @@ jobs: --strict \ --require-suite net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationPostgresIntegrationTest \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationPostgresIntegrationTest#v35PreservesReservedTenantDenialAndDoesNotExposePrepareFunctionToPublic()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationPostgresIntegrationTest#selectorGuardPreservesInertV1ShapeAndDeniesPromotionOrMissingV2BeforeAllocation()' \ world-management-service - name: Capture World legacy preparation PostgreSQL XML 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 35d4dc8c7a..5b1a40221e 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The release-carrier child of #3021 adds immutable full-Version bundle/v2 storage and independent readback of the complete protected World selector evidence, with V49 preserving all older bundle bytes and denying selector backfill. All five participant owners, their exact selected commit/digest/schema, complete artifact manifest and original Account/APPLIED bytes remain required. Publication retry/reconciliation and descriptor resolution consume the retained v2 evidence; later launch assembly reads the committed local release rather than calling World inside its snapshot. The separate version-2 release attestation binds the complete World evidence under its own domain while descriptor/v1 and retained attestation/v1 stay unchanged. Database definitions cover exact retry, concurrent duplicate insertion, changed fields, raw SQL substitution and retained-row preservation. Their component fixtures stipulate upstream authority; local PostgreSQL execution is unavailable without Docker. The protected current publication actor/role/party/terms producer, authenticated freeze acknowledgement and terminal delivery, actual five-owner publication and live release remain open and denied. Original Draft COMMIT_ORDER cannot authorize a subsequent publication. + Exact source `dadb6a813107fde95c73244a874fec2d13fc27f4` [CI37466228981](https://github.com/benhook1013/FireMUD/actions/runs/37466228981) executed nine selection/history PostgreSQL cases: six passed and three failed, with zero skips. Two complete retained coordinator snapshots used plain JDBC map equality despite binary-array values; the third pre-V48 conflict fixture still called the current terminal-journal-dependent writer. The bounded correction preserves all historical columns and original bytes through recursive comparison and uses the existing valid historical journal seeding rather than inventing an Account terminal result. All seven Account-bound terminal and both synchronized-visibility cases passed without skips at that source; the runner's exact base/head parents and head-identical tree were verified. Corrected migration-history execution remains required. The [World tracker](./world-runtime-and-movement.md#current-status) records the original-input start-selector and protected read components. The complete authenticated selector-to-immutable-release/attestation/preparation carrier remains work in progress, not actual publication, creator currentness or activation. Local Docker absence still prevents PostgreSQL execution. At exact published source `d87f9cc2d30e775ea1e0c31f98ddfc64ec28c5ec`, [CI37458361299](https://github.com/benhook1013/FireMUD/actions/runs/37458361299) executes all seven Game Design Account-bound terminal PostgreSQL cases cleanly with zero skips, closing the unresolved service-schema placeholder fixture failure. The wider Game Design job remains red: three older V43/V44/V45 selection-history fixtures invoke the current coordinator against a pre-V48 schema without its terminal journal. Their correction must preserve the actual historical migration boundaries and immutable retained rows rather than weakening production guards or fabricating that journal early. Terminal component execution does not authenticate creator permission, produce the actual release or establish live cross-owner settlement. Corrected migration-history execution remains required. 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 6d282cc6c0..e607bc1298 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,8 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +The release-carrier child of #3021 adds V42's independent complete selector-to-frozen-graph checks before allocation and replay, then atomically retains the authored RoomTemplateRef and its separate World-owned runtime room mapping with canonical preparation and association. Retained v1 preparation remains byte-exact, inert and selector-ineligible; the original V35/V40 writer guards, function identity and grants are preserved. New component definitions cover actual original APPLIED/frozen-journal join, a non-first authored ROOM, exact independent preparation readback, Java and raw SQL substitution denial, late held-authority rollback, and complete V41→V42 history preservation. Those definitions compile with the candidate but cannot execute locally without Docker; externally supplied currentness remains stipulated. Storage status remains MATERIALIZED_UNVERIFIED, not PREPARING or ACTIVE. The authenticated publication-freeze/terminal producers, complete protected current authorization and live lifecycle/Game Session handoff remain open. No activation or public canonical writer is enabled. + V40 joins the exact immutable release and frozen graph; V41 retains the original Account-digest-bound complete six-family declaration, typed ROOM selector and APPLIED-v2 result atomically. Declaration-less APPLIED-v1 history stays exact and receives no selector backfill. Exact source `dadb6a813107fde95c73244a874fec2d13fc27f4` [CI37466228981](https://github.com/benhook1013/FireMUD/actions/runs/37466228981) executed seventeen graph PostgreSQL cases: fifteen passed and two failed, with zero skips. The receiver rejected genuine original owner graph bytes because the consumer imposed an incompatible RFC 8785 ordering constraint; the extra-family test correctly denied the write but expected a different diagnostic. Twelve association, seven terminal, two synchronized selector and fourteen frozen-topology cases passed without skips. The tested runner has exact base/head parents and a head-identical source tree. Corrected-source execution remains required. The shared closed receipt representation and dedicated, unregistered Game Design selector-read candidate retain the original Account/APPLIED bytes and independently join the actual frozen checkpoint; they do not authenticate current creator authority or establish a completed release, `PREPARING`, ACTIVE or admission. Immutable Game Design release delivery and preparation-selector proof remain open. Local integration tests skip without Docker; transport doubles and injected peer contexts are not live workload proof. Exact published source `d87f9cc2d30e775ea1e0c31f98ddfc64ec28c5ec` [CI37458361299](https://github.com/benhook1013/FireMUD/actions/runs/37458361299) executes 35 scoped World PostgreSQL cases cleanly with zero skips: twelve original Account-bound graph applications, seven terminal outcomes, two synchronized reads and fourteen frozen-topology cases. Runner merge `4330dec5c6b55287821d602be1d964919e265e1f` has exact base/source parents and source-identical tree `15b546e3b96e63f9eb282fe8301f62e5a62a1a80`. This closes the retained-column fixture failures at that source, not protected creator/currentness or live application, release and ACTIVE delivery. The subsequently prepared exact release/frozen-graph join and original-input-bound start selector need their own corrected-source proof; this historical execution does not validate them. Their synthetic authorization fixtures do not complete any of Gameplay's four live owner handoffs. diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts index 01c20e0a94..aa210371ce 100644 --- a/services/game-design-service/build.gradle.kts +++ b/services/game-design-service/build.gradle.kts @@ -1,5 +1,6 @@ import org.gradle.api.attributes.LibraryElements +import org.gradle.api.plugins.jvm.JvmTestSuite apply(from = "${rootDir}/gradle/proto-convention.gradle") @@ -13,6 +14,17 @@ firemudJooq { packageName.set("net.firedevops.firemud.gamedesign.jooq") } +testing { + suites { + named("test") { + sources.java.srcDir("src/sharedTest/java") + } + named("integrationTest") { + sources.java.srcDir("src/sharedTest/java") + } + } +} + dependencies { compileOnly(libs.spotbugs.annotations) implementation(libs.aws.sdk.s3) diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java similarity index 100% rename from services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java rename to services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java index 0b7d6ce70b..657d894c23 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java @@ -142,11 +142,12 @@ void migrationLeavesRetainedReleaseTupleAndXminUnchangedAndUnmapped() { assertThat(retainedTuple(fixture.dsl(), retainedBundleId)).isEqualTo(retainedTupleBefore); assertThat(bundleXmin(fixture.dsl(), retainedBundleId)).isEqualTo(retainedXminBefore); assertThat( - fixture - .dsl() - .fetchOne( - "SELECT world_published_start_location_evidence_json FROM published_release_bundle WHERE id = ?", - retainedBundleId) + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT world_published_start_location_evidence_json FROM published_release_bundle WHERE id = ?", + retainedBundleId)) .get(0)) .isNull(); PublishedReleaseBundle retained = diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 2d99450abb..6bcca89710 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -696,7 +696,14 @@ private WorldCanonicalInstancePreparation.Input preparationInput( private WorldCanonicalInstancePreparationRepository preparationRepository() { return new WorldCanonicalInstancePreparationRepository( - dsl, manager, new WorldCanonicalInstanceAssociationRepository(dsl), frozenRepository()); + dsl, + manager, + new WorldCanonicalInstanceAssociationRepository( + dsl, + new WorldCompleteLaunchBindingRepository(dsl), + new WorldAuthoredSourceIntakeRepository(dsl), + new WorldAuthoredVersionIdentityRepository(dsl)), + frozenRepository()); } private WorldCanonicalInstancePreparationService preparationComponent( From 6867937ab446cf418b70467e30cf44077b25f81c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 04:21:21 +1300 Subject: [PATCH 03/13] Add exact canonical World lifecycle readback and repair release migrations --- .github/workflows/ci.yml | 1 + .../world-management-service/api-contracts.md | 4 + ...ame-authoring-publishing-and-activation.md | 6 +- .../realm-routing-and-playable-state.md | 2 + .../world-runtime-and-movement.md | 6 +- ...ld_canonical_instance_lifecycle_read.proto | 22 + ...WorldCanonicalInstanceLifecycleClient.java | 156 ++ ...rldCanonicalInstanceLifecycleEvidence.java | 475 ++++++ ...ldCanonicalInstanceLifecycleGrpcCodec.java | 69 + ...onicalInstanceLifecycleClientMtlsTest.java | 583 ++++++++ ...anonicalInstanceLifecycleEvidenceTest.java | 722 +++++++++ ...ublished_world_start_location_evidence.sql | 5 +- ...leaseCanonicalIdentityIntegrationTest.java | 21 + ...essionWorldCanonicalLifecycleVerifier.java | 343 +++++ ...onWorldCanonicalLifecycleVerifierTest.java | 1289 +++++++++++++++++ .../WorldAuthoredSourceIntakeRepository.java | 33 + ...orldAuthoredVersionIdentityRepository.java | 35 + ...anonicalInstanceAssociationRepository.java | 56 +- ...nicalInstanceLifecycleReadGrpcService.java | 117 ++ ...onicalInstanceLifecycleReadRepository.java | 625 ++++++++ ...anonicalInstancePreparationRepository.java | 2 +- .../WorldCompleteLaunchBindingRepository.java | 34 + ...release_start_location_materialization.sql | 43 +- ...aphApplicationPostgresIntegrationTest.java | 351 +++++ ...lInstanceLifecycleReadGrpcServiceTest.java | 162 +++ ...alInstanceLifecycleReadRepositoryTest.java | 54 + 26 files changed, 5187 insertions(+), 29 deletions(-) create mode 100644 protos/world-management/v1/world_canonical_instance_lifecycle_read.proto create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/WorldCanonicalInstanceLifecycleClientMtlsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionWorldCanonicalLifecycleVerifier.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionWorldCanonicalLifecycleVerifierTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8df5425a29..9f54f35291 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2219,6 +2219,7 @@ jobs: bash dev-tools/validation/inspect-test-results.sh \ --strict \ --require-suite net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#lifecycleReadFollowsCurrentWorldEpochAndReturnsExactCanonicalServiceEcho()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#releaseSelectorMaterializesItsOriginalRoomAndExactlyRetriesWithSeparateRuntimeMapping()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#releaseSelectorRejectsChangedFrozenRequestAndSqlSubstitutionWithoutRuntimeWrites()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#inertV1PreparationRetainsOriginalBytesAndCannotGainSelectorOnRetry()' \ diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 8c8a3b39b2..67db5cd9b1 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -316,6 +316,10 @@ The initial generation-free path may use explicitly authored empty optional fami Canonical preparation verifies Game Design's exact [authored-source-bound launch descriptor and its separately authenticated full release attestation](../game-design-service/api-contracts.md#authored-source-bound-launch-descriptor-and-exact-readback), then retains and reads back both together with the World lifecycle result before reporting `PREPARING`. World rejects either missing item and any swapped or mismatched pair, including disagreement in descriptor/source identity, canonical tenant/world scope, canonical UUID version, resolved release, or required release evidence. An exact retry returns the originally retained pair and lifecycle result; it cannot replace either item with newer owner state. The existing currentness and authorization checks still apply, and the pair and `PREPARING` result commit through the existing atomic workflow. A source selector receipt does not replace release attestation, and a private source key does not establish a World tenant association. Game Design's version-state epoch remains distinct from this owner's lifecycle epoch; descriptor recovery alone does not prove current ACTIVE eligibility. The separate closed evidence and exact authenticated read are owned by [Game Design's release-attestation contract](../game-design-service/api-contracts.md#separate-complete-release-attestation-evidence); World must retain both components rather than extending descriptor v1 or accepting descriptor-only fallback. Producer, consumer, local retention and negative runtime proof remain activation gates. +`ReadWorldCanonicalInstanceLifecycle` is a separate read-only World-to-Game Session owner handoff. World authenticates the exact same-namespace Game Session workload, without end-user context, before decoding or accessing owner storage. The closed versioned request binds its distinct read UUID, workload namespace, canonical tenant/world/instance/Version, playable namespace and scope, public-production qualification, control-plane request, and expected descriptor request/result and full release-attestation digests. One World read-only snapshot resolves the instance through its persisted canonical association and joins the complete original launch binding, preparation and typed start-room materialization with the actual current lifecycle row. The response echoes the complete request and retains the full descriptor/release pair, authored `RoomTemplateRef`, separately scoped runtime room identity, capture and graph/input digests, lifecycle state, World lifecycle epoch and owner row version. Its runtime room identity, lifecycle epoch and row version use canonical decimal strings on the wire to preserve exact signed-64-bit values. Private World storage selectors are not exposed as request or lifecycle identities; retained provenance in the unchanged complete Game Design evidence cannot substitute for the World association. Missing, mismatched, receipt-less or ambiguous evidence is denied; a read never repairs history, chooses a room or authorizes admission. + +Game Session must compare the complete returned binding with its original launch evidence. A transition from a durably proved `PREPARING` result to the initial `ACTIVE` result requires the same association, source/release, capture, graph/input and selector/runtime-room evidence, exactly the next World lifecycle epoch and an advanced owner row version; Game Design's version-state epoch is a separate token. An exact same-state replay may retain its row version, but a later current read cannot regress it. A historical materialization result cannot be used as a current lifecycle result, and an authenticated lifecycle read does not replace current Account authority or the initial-admission hold and pointer commit below. This handoff does not itself enable an activation writer. + [Versioning and Runtime](../../system-architecture-versioning-runtime.md#first-open-from-never-opened-authority) owns the first-OPEN transition and its tagged prior-pointer preconditions. World owns the durable initial-admission hold and authoritative target lifecycle proof. The hold binds one stable initial-admission request/digest, the complete canonical namespace/tenant/realm/playable-namespace/scope, exact target instance/version/ACTIVE epoch, and the precondition tag with its applicable pointer/catalog versions. Private World storage selectors do not replace those identities: any association must come from exact persisted authenticated owner evidence, never numeric equality, slugs or Account's migration manifest. Acquire locks and verifies the exact ACTIVE lifecycle row and commits one immutable hold identity/fence; an exact retry reuses it, and changed bindings conflict without another hold. A nonterminal hold blocks every applicable target termination CAS. World finalizes only from authenticated Game Session readback of the exact hold-bound pointer/audit/outcome commit, or terminalizes an abort only from positive proof that this operation did not commit and its expected prior routing authority remains intact. Missing, contradictory or unavailable evidence remains reconciliation-required and termination-blocking. Expiry is diagnostic input, never automatic release or proof of abort. 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 5b1a40221e..eb9bce257c 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,7 +6,11 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The release-carrier child of #3021 adds immutable full-Version bundle/v2 storage and independent readback of the complete protected World selector evidence, with V49 preserving all older bundle bytes and denying selector backfill. All five participant owners, their exact selected commit/digest/schema, complete artifact manifest and original Account/APPLIED bytes remain required. Publication retry/reconciliation and descriptor resolution consume the retained v2 evidence; later launch assembly reads the committed local release rather than calling World inside its snapshot. The separate version-2 release attestation binds the complete World evidence under its own domain while descriptor/v1 and retained attestation/v1 stay unchanged. Database definitions cover exact retry, concurrent duplicate insertion, changed fields, raw SQL substitution and retained-row preservation. Their component fixtures stipulate upstream authority; local PostgreSQL execution is unavailable without Docker. The protected current publication actor/role/party/terms producer, authenticated freeze acknowledgement and terminal delivery, actual five-owner publication and live release remain open and denied. Original Draft COMMIT_ORDER cannot authorize a subsequent publication. +The corrected #3029 candidate repairs two executed migration failures from [CI37477743875](https://github.com/benhook1013/FireMUD/actions/runs/37477743875): V42's reserved PL/pgSQL identifier and V49's rejection of the canonical decimal-string selector epoch. World also compares the retained full-release numeric epoch to that string without changing retained bytes, and uses the current room physical column. Local Core/Game Design/World/Game Session checks, schema generation, packaged builds and documentation validation pass; PostgreSQL cases still skip without Docker, so corrected-state runner execution remains required. The retained `AuthoredDraftPublishSelection.digest()` already binds all eight `PublishVersion` inputs and selected synchronized Draft evidence. The approved distinct publication-operation authorization and immutable no-publication readback must reuse that complete evidence where applicable while keeping preallocation inputs, later captures and allocated release/artifact results distinct. `publicationDigestRequest/v1` remains the narrower owner-read binding, not publication authorization. + +The release-carrier child #3029 of #3021 adds immutable full-Version bundle/v2 storage and independent readback of the complete protected World selector evidence, with V49 preserving all older bundle bytes and denying selector backfill. All five participant owners, their exact selected commit/digest/schema, complete artifact manifest and original Account/APPLIED bytes remain required. Publication retry/reconciliation and descriptor resolution consume the retained v2 evidence; later launch assembly reads the committed local release rather than calling World inside its snapshot. The separate version-2 release attestation binds the complete World evidence under its own domain while descriptor/v1 and retained attestation/v1 stay unchanged. Database definitions cover exact retry, concurrent duplicate insertion, changed fields, raw SQL substitution and retained-row preservation. Their component fixtures explicitly stipulate isolated upstream authority; local PostgreSQL execution is unavailable without Docker. The protected current publication actor/role/party/terms producer, authenticated freeze acknowledgement and terminal delivery, actual five-owner publication and live release remain open and denied. Original Draft COMMIT_ORDER cannot authorize a subsequent publication; a distinct Account-owned publication operation and exact current source participation are required. Production operative verification/terms/legal authority is a separate activation prerequisite, not assumed by the bounded isolated proof. + +Exact #3021 source `9f83e6dc24e23d99e8f9d20e6ea0dc87e505f5c7` [CI37474590468](https://github.com/benhook1013/FireMUD/actions/runs/37474590468) provides raw XML proof of 27 relevant Game Design PostgreSQL cases with no failures or skips: terminal seven, selection/history nine and commit coordinator eleven. The exact base/head runner merge has a source-identical tree. This closes the corrected-source selection-history fixture failures described below, not the child's V49 immutable-v2 bundle execution, authenticated current publication permission or live release. World independently proves 52 cases including both selector-join methods and Account adds 40 cases, giving 119 verified clean scoped executions. Local child checks pass with 1,237 clean Core/Game Design/World unit outcomes; all 319 integration cases skip without Docker. Exact source `dadb6a813107fde95c73244a874fec2d13fc27f4` [CI37466228981](https://github.com/benhook1013/FireMUD/actions/runs/37466228981) executed nine selection/history PostgreSQL cases: six passed and three failed, with zero skips. Two complete retained coordinator snapshots used plain JDBC map equality despite binary-array values; the third pre-V48 conflict fixture still called the current terminal-journal-dependent writer. The bounded correction preserves all historical columns and original bytes through recursive comparison and uses the existing valid historical journal seeding rather than inventing an Account terminal result. All seven Account-bound terminal and both synchronized-visibility cases passed without skips at that source; the runner's exact base/head parents and head-identical tree were verified. Corrected migration-history execution remains required. The [World tracker](./world-runtime-and-movement.md#current-status) records the original-input start-selector and protected read components. The complete authenticated selector-to-immutable-release/attestation/preparation carrier remains work in progress, not actual publication, creator currentness or activation. Local Docker absence still prevents PostgreSQL execution. diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index e4d3e9485a..1a7f4d105d 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for realm routing and playable st ## Current Status +The #3029 consumer prerequisite adds an unwired Game Session verifier and an explicit authenticated World lifecycle client. They compare the complete original launch binding and the World-owned capture, selector/runtime room, current epoch and row version rather than accepting historical preparation as current `ACTIVE`. The [World lifecycle handoff](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-hold-contract) owns those evidence rules. Local full checks pass, including the new verifier and physical mTLS transport-double cases; they do not establish live authenticated World delivery. Game Session launch orchestration, durable lifecycle association, canonical activation and usable Gameplay delivery are still open. No pointer or admission path consumes the new verifier yet. + The realm-catalog projection, exact `WORLDS`/`REALMS` ordinal snapshots, persisted-pointer reads, bootstrap/connect-scope flow, session-freshness normalization, and local runtime projections are implemented; this does not establish complete routing or live admission. `WORLDS` and its ordinal snapshot share one catalog read. Game Session retains caller-bound Account scopes and JOIN request IDs in bounded shared Redis state keyed by the stable numeric transport session; it binds world and realm ordinals to their exact response snapshots through the shared `DirectTextOrdinalSelectionResolver`, and stale or changed numeric selectors fail closed. Current text `JOIN` accepts the retained `WORLDS` ordinal or a uniquely resolving bare world slug; the latter is implementation drift. The pointer has no `tenantSlug`, so stable `tenantSlug/worldSlug` selection remains unavailable. Authority-backed discovery suppresses cross-tenant case-insensitive slug collisions without collapsing tenant-bound ordinal choices. Scope and selector snapshots expire; per-key compare-and-set protects retry binding and replacement. The source-YAML initializer proof reads shipped application YAML directly and proves source-configuration binding only; it is not packaged-artifact, fresh-boot, persisted-seed, or live-admission proof. Focused unit proof exists; Docker-gated Redis cross-instance/retry proof was skipped locally. Full direct-text/Telnet and first-party `Join & Play` end-to-end proof, PostgreSQL lost-acknowledgement/concurrency proof, and complete pending-operation recovery remain open. Account membership, entitlement, and grant readers fail closed before data access until typed caller/target binding is available, so there is no composed live admission proof; direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. `GetAdmissionPointer` preserves exactly-one-visible-public-production-realm cardinality from one authoritative snapshot; catalog-revision and pointer-read failures retain typed retryable unavailable outcomes instead of becoming missing selectors or generic failures. Duplicate public rows remain an activation/data-decision gap. The internal pointer authority locks an existing row, checks expected `pointerVersion` and `catalogRevision`, conditionally updates against both prior values, and commits pointer plus audit together. Public pointer mutation and cutover RPCs remain fail-closed; prepared-cutover execution, explicit `CLOSED`, complete revision-consumer convergence, canonical `{tenantId, realmId}` repository addressing and retained catalog mapping, hold/drain atomicity, and bounded active-session drain remain incomplete. Public/grant policy is also partial: lifecycle-bound grant expiry, monotonic mutation outcomes/tombstones, and tenant-admin management are absent; playtest initialization/reset, all-owner manifests, lifecycle generations, and close/expiry orchestration remain unimplemented or unproved. See [Authentication](../../architecture/system-architecture-authentication.md) and [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md) for canonical contracts. 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 e607bc1298..66e519a7e4 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,7 +6,11 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status -The release-carrier child of #3021 adds V42's independent complete selector-to-frozen-graph checks before allocation and replay, then atomically retains the authored RoomTemplateRef and its separate World-owned runtime room mapping with canonical preparation and association. Retained v1 preparation remains byte-exact, inert and selector-ineligible; the original V35/V40 writer guards, function identity and grants are preserved. New component definitions cover actual original APPLIED/frozen-journal join, a non-first authored ROOM, exact independent preparation readback, Java and raw SQL substitution denial, late held-authority rollback, and complete V41→V42 history preservation. Those definitions compile with the candidate but cannot execute locally without Docker; externally supplied currentness remains stipulated. Storage status remains MATERIALIZED_UNVERIFIED, not PREPARING or ACTIVE. The authenticated publication-freeze/terminal producers, complete protected current authorization and live lifecycle/Game Session handoff remain open. No activation or public canonical writer is enabled. +The #3029 lifecycle read candidate is an explicitly unregistered owner adapter over one read-only `REPEATABLE_READ` snapshot. It follows the persisted World association and revalidates the original source, complete launch binding, preparation, selector and actual room-to-region ownership before returning the current World lifecycle row. Its separate mTLS client and Game Session verifier preserve complete request echoes, exact long counters and immutable capture identity; same-state retry is distinct from the next-epoch transition with an advanced row version. The focused PostgreSQL definition uses the real `PREPARING` to `FAILED_PRE_ACTIVATION` mutation and unchanged preparation retry; it does not manufacture canonical `ACTIVE`. V42 and preparation readback also use V22's actual `room_instance_row_id` physical column. Local consolidated Core/Game Design/World/Game Session checks pass: 3,633 unit executions and 44 non-PostgreSQL Game Session integration/cross-service executions, with no failures. All 320 Game Design/World integration cases and 255 Docker-gated Game Session cases skip locally; PostgreSQL execution of the corrected V42/V49 and new lifecycle case remains required. Canonical activation, registration and live Game Session delivery remain open under the [World owner contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-hold-contract). + +The release-carrier child #3029 of #3021 adds V42's independent complete selector-to-frozen-graph checks before allocation and replay, then atomically retains the authored RoomTemplateRef and its separate World-owned runtime room mapping with canonical preparation and association. Retained v1 preparation remains byte-exact, inert and selector-ineligible; the original V35/V40 writer guards, function identity and grants are preserved. New component definitions cover actual original APPLIED/frozen-journal join, a non-first authored ROOM, exact independent preparation readback, Java and raw SQL substitution denial, late held-authority rollback, and complete V41→V42 history preservation. Those definitions compile with the candidate but cannot execute locally without Docker; externally supplied currentness remains explicitly stipulated isolated fixture authority. The preparation's storage result is MATERIALIZED_UNVERIFIED, while V35 also creates an owner lifecycle row at PREPARING/epoch one; neither alone is authenticated live PREPARING or ACTIVE handoff proof. The authenticated publication-freeze/terminal producers, complete protected current authorization and live lifecycle/Game Session handoff remain open. No activation or public canonical writer is enabled. + +Exact #3021 source `9f83e6dc24e23d99e8f9d20e6ea0dc87e505f5c7` [CI37474590468](https://github.com/benhook1013/FireMUD/actions/runs/37474590468) provides raw XML proof of 52 executed World PostgreSQL cases with zero failures or skips: terminal seven, frozen topology fourteen, canonical association twelve and graph application nineteen, including both new selector-join methods. Its exact base/head synthetic merge has a source-identical tree. This closes the corrected-source World receiver and selector fixture failures described below, not the child's V42 execution, live authenticated source/currentness or any of Gameplay's four handoffs. The Game Design portion independently proves 27 relevant cases and Account adds 40 cases, giving 119 verified clean scoped executions. This is component fixture proof, not activation. V40 joins the exact immutable release and frozen graph; V41 retains the original Account-digest-bound complete six-family declaration, typed ROOM selector and APPLIED-v2 result atomically. Declaration-less APPLIED-v1 history stays exact and receives no selector backfill. Exact source `dadb6a813107fde95c73244a874fec2d13fc27f4` [CI37466228981](https://github.com/benhook1013/FireMUD/actions/runs/37466228981) executed seventeen graph PostgreSQL cases: fifteen passed and two failed, with zero skips. The receiver rejected genuine original owner graph bytes because the consumer imposed an incompatible RFC 8785 ordering constraint; the extra-family test correctly denied the write but expected a different diagnostic. Twelve association, seven terminal, two synchronized selector and fourteen frozen-topology cases passed without skips. The tested runner has exact base/head parents and a head-identical source tree. Corrected-source execution remains required. The shared closed receipt representation and dedicated, unregistered Game Design selector-read candidate retain the original Account/APPLIED bytes and independently join the actual frozen checkpoint; they do not authenticate current creator authority or establish a completed release, `PREPARING`, ACTIVE or admission. Immutable Game Design release delivery and preparation-selector proof remain open. Local integration tests skip without Docker; transport doubles and injected peer contexts are not live workload proof. diff --git a/protos/world-management/v1/world_canonical_instance_lifecycle_read.proto b/protos/world-management/v1/world_canonical_instance_lifecycle_read.proto new file mode 100644 index 0000000000..2fe0c25a6b --- /dev/null +++ b/protos/world-management/v1/world_canonical_instance_lifecycle_read.proto @@ -0,0 +1,22 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Read-only complete canonical World lifecycle owner evidence for authenticated Game Session. +service WorldCanonicalInstanceLifecycleReadService { + rpc ReadWorldCanonicalInstanceLifecycle(ReadWorldCanonicalInstanceLifecycleRequest) + returns (ReadWorldCanonicalInstanceLifecycleResponse); +} + +message ReadWorldCanonicalInstanceLifecycleRequest { + // Complete closed versioned WorldCanonicalInstanceLifecycleEvidence.Request bytes. + bytes canonical_request_bytes = 1; +} + +message ReadWorldCanonicalInstanceLifecycleResponse { + // Complete closed evidence bytes, including the exact request echo and full launch binding. + bytes canonical_response_bytes = 1; +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java new file mode 100644 index 0000000000..33aef52809 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java @@ -0,0 +1,156 @@ +package net.firedevops.firemud.common.world; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInstanceLifecycleReadServiceGrpc; + +/** Explicit mTLS client for the exact World canonical instance lifecycle read. */ +public final class WorldCanonicalInstanceLifecycleClient + extends AbstractReloadingBlockingGrpcClient< + WorldCanonicalInstanceLifecycleReadServiceGrpc + .WorldCanonicalInstanceLifecycleReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldCanonicalInstanceLifecycleClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + WorldCanonicalInstanceLifecycleClient.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 Session service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("World canonical lifecycle client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("World canonical lifecycle client has no gRPC stub"); + } + initialized = true; + } + + /** Reads and validates World-owned lifecycle evidence for this exact canonical request. */ + public WorldCanonicalInstanceLifecycleEvidence read( + WorldCanonicalInstanceLifecycleEvidence.Request request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "World canonical lifecycle request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readWorldCanonicalInstanceLifecycle( + WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(request)); + try { + return WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid canonical instance lifecycle evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldCanonicalInstanceLifecycleReadServiceGrpc + .WorldCanonicalInstanceLifecycleReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldCanonicalInstanceLifecycleReadServiceGrpc.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 WorldCanonicalInstanceLifecycleReadServiceGrpc + .WorldCanonicalInstanceLifecycleReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "World canonical lifecycle client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("World canonical lifecycle read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "World canonical lifecycle read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World canonical lifecycle read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "World canonical lifecycle read " + label + " must be a readable file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World canonical lifecycle read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java new file mode 100644 index 0000000000..62750d0aa0 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java @@ -0,0 +1,475 @@ +package net.firedevops.firemud.common.world; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** + * Exact, non-admitting World lifecycle owner readback for an authenticated canonical caller. + * + *

Decoding this carrier does not authenticate World, establish current Account authority, or + * grant lifecycle activation or gameplay admission. The transport endpoint owns workload + * authentication; the consumer must keep admission and its current-authority checks separate. + */ +public record WorldCanonicalInstanceLifecycleEvidence( + Request request, + CompleteLaunchBindingEvidence launchBinding, + RoomTemplateRef startLocation, + long runtimeRoomInstanceId, + String lifecycleStatus, + long lifecycleEpoch, + long rowVersion, + UUID captureId, + String graphSha256, + String preparationInputDigest) { + public static final String SCHEMA = "world-canonical-instance-lifecycle-evidence/v1"; + public static final String REQUEST_SCHEMA = "world-canonical-instance-lifecycle-read-request/v1"; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern PREFIXED_SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern BARE_SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Set EVIDENCE_FIELDS = + Set.of( + "schema", + "request", + "launchBindingBytesBase64", + "startLocation", + "runtimeRoomInstanceId", + "lifecycleStatus", + "lifecycleEpoch", + "rowVersion", + "captureId", + "graphSha256", + "preparationInputDigest"); + private static final Set REQUEST_FIELDS = + Set.of( + "schemaVersion", + "readRequestId", + "targetNamespace", + "canonicalTenantId", + "worldSlug", + "canonicalGameInstanceId", + "playableStateNamespaceId", + "playableStateScope", + "publicProduction", + "controlPlaneRequestId", + "canonicalVersionId", + "expectedDescriptorRequestDigest", + "expectedDescriptorResultDigest", + "expectedReleaseAttestationDigest"); + private static final Set REQUEST_ENVELOPE_FIELDS = Set.of("schema", "request"); + private static final Set ROOM_TEMPLATE_REF_FIELDS = + Set.of("tenantId", "versionId", "roomTemplateId"); + private static final Set LIFECYCLE_STATUSES = + Set.of("PREPARING", "ACTIVE", "FAILED_PRE_ACTIVATION", "TERMINATING", "TERMINATED"); + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .build(); + + public WorldCanonicalInstanceLifecycleEvidence { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(launchBinding, "launchBinding"); + Objects.requireNonNull(startLocation, "startLocation"); + if (runtimeRoomInstanceId <= 0) { + throw new IllegalArgumentException("runtimeRoomInstanceId must be positive"); + } + if (lifecycleStatus == null || !LIFECYCLE_STATUSES.contains(lifecycleStatus)) { + throw new IllegalArgumentException("Unsupported World lifecycle status"); + } + if (lifecycleEpoch <= 0) { + throw new IllegalArgumentException("World lifecycleEpoch must be positive"); + } + if (rowVersion < 0) { + throw new IllegalArgumentException("World lifecycle rowVersion must be nonnegative"); + } + requireNonNil(captureId, "captureId"); + requireDigest(graphSha256, BARE_SHA256, "graphSha256"); + requireDigest(preparationInputDigest, PREFIXED_SHA256, "preparationInputDigest"); + requireExactBinding(request, launchBinding, startLocation, graphSha256); + } + + /** Closed canonical representation with the complete descriptor and separate attestation. */ + public byte[] canonicalBytes() { + Map value = new LinkedHashMap<>(); + value.put("schema", SCHEMA); + value.put("request", requestJson(request)); + value.put( + "launchBindingBytesBase64", + Base64.getEncoder().encodeToString(closedLaunchBindingBytes(launchBinding))); + value.put("startLocation", roomTemplateRefJson(startLocation)); + value.put("runtimeRoomInstanceId", Long.toString(runtimeRoomInstanceId)); + value.put("lifecycleStatus", lifecycleStatus); + value.put("lifecycleEpoch", Long.toString(lifecycleEpoch)); + value.put("rowVersion", Long.toString(rowVersion)); + value.put("captureId", captureId.toString()); + value.put("graphSha256", graphSha256); + value.put("preparationInputDigest", preparationInputDigest); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException( + "World canonical lifecycle evidence cannot be encoded", impossible); + } + } + + /** Decodes closed retained bytes; this does not authenticate the producing World workload. */ + public static WorldCanonicalInstanceLifecycleEvidence fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + JsonNode root = JSON.readTree(strictUtf8(stored)); + requireFields(root, EVIDENCE_FIELDS, "World canonical lifecycle evidence"); + if (!SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException("Unsupported World canonical lifecycle evidence schema"); + } + Request request = parseRequest(root.get("request")); + CompleteLaunchBindingEvidence launchBinding = + parseLaunchBinding(base64(root, "launchBindingBytesBase64")); + WorldCanonicalInstanceLifecycleEvidence evidence = + new WorldCanonicalInstanceLifecycleEvidence( + request, + launchBinding, + parseRoomTemplateRef(root.get("startLocation")), + positiveLong(text(root, "runtimeRoomInstanceId"), "runtimeRoomInstanceId"), + text(root, "lifecycleStatus"), + positiveLong(text(root, "lifecycleEpoch"), "lifecycleEpoch"), + nonNegativeLong(text(root, "rowVersion"), "rowVersion"), + parseUuid(text(root, "captureId"), "captureId"), + text(root, "graphSha256"), + text(root, "preparationInputDigest")); + if (!Arrays.equals(stored, evidence.canonicalBytes())) { + throw new IllegalArgumentException("World canonical lifecycle evidence is not canonical"); + } + return evidence; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("World canonical lifecycle evidence is invalid", invalid); + } + } + + private static void requireExactBinding( + Request request, + CompleteLaunchBindingEvidence binding, + RoomTemplateRef startLocation, + String graphSha256) { + AuthoredWorldLaunchDescriptorEvidence descriptor = binding.descriptor(); + AuthoredWorldReleaseAttestationEvidence release = binding.releaseAttestation(); + descriptor.requireValid(); + release.requireValid(descriptor); + if (!request.targetNamespace().equals(descriptor.targetNamespace()) + || !request.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !request.worldSlug().equals(descriptor.worldSlug()) + || !request.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId()) + || !request.expectedDescriptorRequestDigest().equals(descriptor.requestDigest()) + || !request.expectedDescriptorResultDigest().equals(descriptor.resultDigest()) + || !request.expectedReleaseAttestationDigest().equals(release.evidenceDigest()) + || !request.canonicalVersionId().equals(release.canonicalVersionId())) { + throw new IllegalArgumentException( + "World lifecycle request differs from the complete launch binding"); + } + if (release.schemaVersion() != AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION + || release.worldStartLocationEvidence() == null) { + throw new IllegalArgumentException( + "World lifecycle evidence requires the complete selector/v2 release attestation"); + } + WorldDraftStartLocationEvidence selectorReceipt = + WorldDraftStartLocationEvidence.fromStored( + release.worldStartLocationEvidence().selectorReceiptBytes()); + String selectedGraphSha256 = selectorReceipt.graphDigest().substring("sha256:".length()); + if (!selectorReceipt.startLocation().equals(startLocation) + || !selectedGraphSha256.equals(graphSha256)) { + throw new IllegalArgumentException( + "World lifecycle ROOM selector or graph digest differs from the complete release selector"); + } + } + + private static byte[] closedLaunchBindingBytes(CompleteLaunchBindingEvidence binding) { + try { + // Preserve every original descriptor/release value, including long numeric fields, inside + // the opaque outer base64 envelope instead of subjecting those owner bytes to RFC 8785's + // JavaScript-number range. + return JSON.writeValueAsString(binding).getBytes(StandardCharsets.UTF_8); + } catch (tools.jackson.core.JacksonException impossible) { + throw new IllegalStateException("Complete launch binding cannot be encoded", impossible); + } + } + + private static CompleteLaunchBindingEvidence parseLaunchBinding(byte[] stored) { + try { + JsonNode node = JSON.readTree(strictUtf8(stored)); + requireFields(node, Set.of("descriptor", "releaseAttestation"), "complete launch binding"); + CompleteLaunchBindingEvidence binding = + JSON.treeToValue(node, CompleteLaunchBindingEvidence.class); + if (!Arrays.equals(stored, closedLaunchBindingBytes(binding))) { + throw new IllegalArgumentException( + "Nested complete launch binding bytes are not canonical"); + } + return binding; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException( + "Nested complete launch binding bytes are invalid", invalid); + } + } + + private static Request parseRequest(JsonNode node) { + requireFields(node, REQUEST_FIELDS, "World canonical lifecycle request"); + JsonNode publicProduction = node.get("publicProduction"); + if (publicProduction == null || !publicProduction.isBoolean()) { + throw new IllegalArgumentException("publicProduction must be present as a boolean"); + } + return new Request( + intValue(node, "schemaVersion"), + parseUuid(text(node, "readRequestId"), "readRequestId"), + text(node, "targetNamespace"), + parseUuid(text(node, "canonicalTenantId"), "canonicalTenantId"), + text(node, "worldSlug"), + parseUuid(text(node, "canonicalGameInstanceId"), "canonicalGameInstanceId"), + parseUuid(text(node, "playableStateNamespaceId"), "playableStateNamespaceId"), + text(node, "playableStateScope"), + publicProduction.booleanValue(), + text(node, "controlPlaneRequestId"), + parseUuid(text(node, "canonicalVersionId"), "canonicalVersionId"), + text(node, "expectedDescriptorRequestDigest"), + text(node, "expectedDescriptorResultDigest"), + text(node, "expectedReleaseAttestationDigest")); + } + + private static RoomTemplateRef parseRoomTemplateRef(JsonNode node) { + requireFields(node, ROOM_TEMPLATE_REF_FIELDS, "World lifecycle startLocation"); + return new RoomTemplateRef( + parseUuid(text(node, "tenantId"), "startLocation.tenantId"), + parseUuid(text(node, "versionId"), "startLocation.versionId"), + parseUuid(text(node, "roomTemplateId"), "startLocation.roomTemplateId")); + } + + private static Map requestJson(Request request) { + Map value = new LinkedHashMap<>(); + value.put("schemaVersion", request.schemaVersion()); + value.put("readRequestId", request.readRequestId().toString()); + value.put("targetNamespace", request.targetNamespace()); + value.put("canonicalTenantId", request.canonicalTenantId().toString()); + value.put("worldSlug", request.worldSlug()); + value.put("canonicalGameInstanceId", request.canonicalGameInstanceId().toString()); + value.put("playableStateNamespaceId", request.playableStateNamespaceId().toString()); + value.put("playableStateScope", request.playableStateScope()); + value.put("publicProduction", request.publicProduction()); + value.put("controlPlaneRequestId", request.controlPlaneRequestId()); + value.put("canonicalVersionId", request.canonicalVersionId().toString()); + value.put("expectedDescriptorRequestDigest", request.expectedDescriptorRequestDigest()); + value.put("expectedDescriptorResultDigest", request.expectedDescriptorResultDigest()); + value.put("expectedReleaseAttestationDigest", request.expectedReleaseAttestationDigest()); + return value; + } + + private static Map roomTemplateRefJson(RoomTemplateRef reference) { + Map value = new LinkedHashMap<>(); + value.put("tenantId", reference.tenantId().toString()); + value.put("versionId", reference.versionId().toString()); + value.put("roomTemplateId", reference.roomTemplateId().toString()); + return value; + } + + private static byte[] base64(JsonNode node, String field) { + try { + return Base64.getDecoder().decode(text(node, field)); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Invalid base64 field " + field, invalid); + } + } + + private static String text(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual() || value.textValue().isBlank()) { + throw new IllegalArgumentException(field + " is required"); + } + return value.textValue(); + } + + private static int intValue(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) { + throw new IllegalArgumentException(field + " must be an integer"); + } + return value.intValue(); + } + + private static long positiveLong(String value, String field) { + if (value == null || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(field + " must be canonical positive decimal"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException(field + " exceeds the supported integer range", invalid); + } + } + + private static long nonNegativeLong(String value, String field) { + if (value == null || !value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException(field + " must be canonical nonnegative decimal"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException(field + " exceeds the supported integer range", invalid); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (java.nio.charset.CharacterCodingException invalid) { + throw new IllegalArgumentException( + "Canonical World lifecycle bytes are not strict UTF-8", invalid); + } + } + + private static UUID parseUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || NIL_UUID.equals(parsed)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID", invalid); + } + } + + 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, Pattern pattern, String label) { + if (value == null || !pattern.matcher(value).matches()) { + throw new IllegalArgumentException(label + " is not a canonical SHA-256 digest"); + } + } + + private static void requireFields(JsonNode object, Set fields, String label) { + if (object == null || !object.isObject()) { + throw new IllegalArgumentException(label + " must be an object"); + } + Set actual = new java.util.HashSet<>(); + object.propertyNames().forEach(actual::add); + if (!actual.equals(fields)) { + throw new IllegalArgumentException(label + " has missing or unsupported fields"); + } + } + + /** Exact shared request envelope for the read-only World lifecycle capture. */ + public record Request( + int schemaVersion, + UUID readRequestId, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID canonicalGameInstanceId, + UUID playableStateNamespaceId, + String playableStateScope, + boolean publicProduction, + String controlPlaneRequestId, + UUID canonicalVersionId, + String expectedDescriptorRequestDigest, + String expectedDescriptorResultDigest, + String expectedReleaseAttestationDigest) { + public static final int SCHEMA_VERSION = 1; + + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World canonical lifecycle read schema"); + } + requireNonNil(readRequestId, "readRequestId"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a canonical DNS label"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + if (!"SHARED".equals(playableStateScope)) { + throw new IllegalArgumentException( + "This lifecycle carrier accepts SHARED scope only; private/playtest proof is unavailable"); + } + if (!publicProduction) { + throw new IllegalArgumentException( + "This lifecycle carrier requires public-production evidence"); + } + requireText(controlPlaneRequestId, "controlPlaneRequestId", 128); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requireDigest( + expectedDescriptorRequestDigest, PREFIXED_SHA256, "expectedDescriptorRequestDigest"); + requireDigest( + expectedDescriptorResultDigest, PREFIXED_SHA256, "expectedDescriptorResultDigest"); + requireDigest( + expectedReleaseAttestationDigest, PREFIXED_SHA256, "expectedReleaseAttestationDigest"); + } + + /** Closed canonical request bytes used by the standalone World read RPC. */ + public byte[] canonicalBytes() { + Map value = new LinkedHashMap<>(); + value.put("schema", REQUEST_SCHEMA); + value.put("request", requestJson(this)); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException( + "World canonical lifecycle request cannot be encoded", impossible); + } + } + + /** Decodes only a complete closed request; this does not authenticate its sender. */ + public static Request fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + JsonNode root = JSON.readTree(strictUtf8(stored)); + requireFields(root, REQUEST_ENVELOPE_FIELDS, "World canonical lifecycle read request"); + if (!REQUEST_SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException( + "Unsupported World canonical lifecycle request schema"); + } + Request request = parseRequest(root.get("request")); + if (!Arrays.equals(stored, request.canonicalBytes())) { + throw new IllegalArgumentException("World canonical lifecycle request is not canonical"); + } + return request; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("World canonical lifecycle request is invalid", invalid); + } + } + + private static void requireText(String value, String label, int maxLength) { + if (value == null || value.isBlank() || value.length() > maxLength) { + throw new IllegalArgumentException(label + " is required and must fit its limit"); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleGrpcCodec.java new file mode 100644 index 0000000000..9caf305d68 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleGrpcCodec.java @@ -0,0 +1,69 @@ +package net.firedevops.firemud.common.world; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Objects; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.Request; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse; + +/** Closed byte-carrier mapping for the authenticated, read-only World lifecycle RPC. */ +public final class WorldCanonicalInstanceLifecycleGrpcCodec { + private WorldCanonicalInstanceLifecycleGrpcCodec() {} + + /** Encodes the complete closed request as one canonical byte value. */ + public static ReadWorldCanonicalInstanceLifecycleRequest toRequest(Request request) { + Objects.requireNonNull(request, "request"); + return ReadWorldCanonicalInstanceLifecycleRequest.newBuilder() + .setCanonicalRequestBytes(ByteString.copyFrom(request.canonicalBytes())) + .build(); + } + + /** Decodes only after the World receiver authenticates its exact same-namespace caller. */ + public static Request fromRequest(ReadWorldCanonicalInstanceLifecycleRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadWorldCanonicalInstanceLifecycleRequest"); + if (request.getCanonicalRequestBytes().isEmpty()) { + throw new IllegalArgumentException("World canonical lifecycle request bytes are required"); + } + return Request.fromStored(request.getCanonicalRequestBytes().toByteArray()); + } + + /** Encodes a complete response only when it contains the exact immutable caller request. */ + public static ReadWorldCanonicalInstanceLifecycleResponse toResponse( + Request request, WorldCanonicalInstanceLifecycleEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(evidence, "evidence"); + if (!request.equals(evidence.request())) { + throw new IllegalArgumentException( + "World lifecycle evidence differs from exact read request"); + } + return ReadWorldCanonicalInstanceLifecycleResponse.newBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(evidence.canonicalBytes())) + .build(); + } + + /** Validates the complete closed response and its exact request echo. */ + public static WorldCanonicalInstanceLifecycleEvidence fromResponse( + Request request, ReadWorldCanonicalInstanceLifecycleResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadWorldCanonicalInstanceLifecycleResponse"); + if (response.getCanonicalResponseBytes().isEmpty()) { + throw new IllegalArgumentException("World canonical lifecycle response bytes are required"); + } + WorldCanonicalInstanceLifecycleEvidence evidence = + WorldCanonicalInstanceLifecycleEvidence.fromStored( + response.getCanonicalResponseBytes().toByteArray()); + if (!request.equals(evidence.request())) { + throw new IllegalArgumentException("World lifecycle response changed exact read request"); + } + return evidence; + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/WorldCanonicalInstanceLifecycleClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/WorldCanonicalInstanceLifecycleClientMtlsTest.java new file mode 100644 index 0000000000..785ae148d6 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/WorldCanonicalInstanceLifecycleClientMtlsTest.java @@ -0,0 +1,583 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateEncodingException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInstanceLifecycleReadServiceGrpc; +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 for the explicit Game Session to World lifecycle-read transport only. */ +class WorldCanonicalInstanceLifecycleClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String WORLD_URI = "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String OTHER_WORLD_URI = + "spiffe://firemud/ns/other-test/sa/world-management-service"; + private static final String WRONG_WORKLOAD_URI = + "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + private static final UUID READ_REQUEST_ID = + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + + @TempDir static Path tempDirectory; + + private static TestPki pki; + private Server server; + private WorldCanonicalInstanceLifecycleClient client; + private AtomicInteger serverCallStarts; + private AtomicInteger applicationCalls; + private AtomicReference receivedPeerUri; + + @BeforeAll + static void createTrustedWorkloadCertificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void stopTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void exactWorldWorkloadPeerReadsTheCompleteEchoedCaptureOverPhysicalMtls() throws Exception { + WorldCanonicalInstanceLifecycleEvidence expected = + evidence("PREPARING", 7L, 10L, READ_REQUEST_ID); + startServer(pki.worldServer(), ResponseMode.EXACT, expected); + client = newClient(server); + client.init(); + + WorldCanonicalInstanceLifecycleEvidence actual = client.read(expected.request()); + + assertThat(actual.canonicalBytes()).containsExactly(expected.canonicalBytes()); + assertThat(serverCallStarts).hasValue(1); + assertThat(applicationCalls).hasValue(1); + assertThat(receivedPeerUri).hasValue(GAME_SESSION_URI); + } + + @Test + void trustedWrongWorldWorkloadAndNamespaceCannotSendRequestMetadataOrBody() throws Exception { + List wrongPeers = List.of(pki.wrongWorkloadServer(), pki.otherNamespaceServer()); + for (TestIdentity wrongPeer : wrongPeers) { + WorldCanonicalInstanceLifecycleEvidence expected = + evidence("PREPARING", 7L, 10L, READ_REQUEST_ID); + startServer(wrongPeer, ResponseMode.EXACT, expected); + client = newClient(server); + client.init(); + + assertThatThrownBy(() -> client.read(expected.request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(serverCallStarts).as(wrongPeer.alias()).hasValue(0); + assertThat(applicationCalls).as(wrongPeer.alias()).hasValue(0); + stopTransport(); + } + } + + @Test + void exactPeerResponseMustEchoTheRequestAndContainAValidCompleteCarrier() throws Exception { + WorldCanonicalInstanceLifecycleEvidence expected = + evidence("PREPARING", 7L, 10L, READ_REQUEST_ID); + + startServer(pki.worldServer(), ResponseMode.WRONG_READ_REQUEST_ID, expected); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.read(expected.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid canonical instance lifecycle evidence"); + assertThat(serverCallStarts).hasValue(1); + assertThat(applicationCalls).hasValue(1); + stopTransport(); + + startServer(pki.worldServer(), ResponseMode.MALFORMED_EVIDENCE, expected); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.read(expected.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid canonical instance lifecycle evidence"); + assertThat(serverCallStarts).hasValue(1); + assertThat(applicationCalls).hasValue(1); + } + + @Test + void refusesPlaintextClasspathFilesAndCallsBeforeExplicitInitialization() throws Exception { + serverCallStarts = new AtomicInteger(); + applicationCalls = new AtomicInteger(); + receivedPeerUri = new AtomicReference<>(); + var plaintext = pki.clientProperties(tempDirectory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldCanonicalInstanceLifecycleClient( + new ServiceEndpointsProperties(), + plaintext, + new GrpcChannelFactory(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + + var classpath = pki.clientProperties(tempDirectory); + classpath.setCaCert("classpath:ca.crt"); + assertThatThrownBy( + () -> + new WorldCanonicalInstanceLifecycleClient( + new ServiceEndpointsProperties(), + classpath, + new GrpcChannelFactory(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + WorldCanonicalInstanceLifecycleEvidence expected = + evidence("PREPARING", 7L, 10L, READ_REQUEST_ID); + startServer(pki.worldServer(), ResponseMode.EXACT, expected); + client = newClient(server); + assertThatThrownBy(() -> client.read(expected.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + assertThat(serverCallStarts).hasValue(0); + assertThat(applicationCalls).hasValue(0); + } + + private void startServer( + TestIdentity identity, + ResponseMode responseMode, + WorldCanonicalInstanceLifecycleEvidence expected) + throws Exception { + serverCallStarts = new AtomicInteger(); + applicationCalls = new AtomicInteger(); + receivedPeerUri = new AtomicReference<>(); + var service = + new WorldCanonicalInstanceLifecycleReadServiceGrpc + .WorldCanonicalInstanceLifecycleReadServiceImplBase() { + @Override + public void readWorldCanonicalInstanceLifecycle( + ReadWorldCanonicalInstanceLifecycleRequest request, + StreamObserver observer) { + applicationCalls.incrementAndGet(); + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + receivedPeerUri.set(peer == null ? null : peer.uri()); + WorldCanonicalInstanceLifecycleEvidence.Request decoded = + WorldCanonicalInstanceLifecycleGrpcCodec.fromRequest(request); + ReadWorldCanonicalInstanceLifecycleResponse response; + if (responseMode == ResponseMode.MALFORMED_EVIDENCE) { + response = + ReadWorldCanonicalInstanceLifecycleResponse.newBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(new byte[] {(byte) 0xff})) + .build(); + } else if (responseMode == ResponseMode.WRONG_READ_REQUEST_ID) { + var changedRequest = + withReadRequestId(decoded, uuid("ffffffff-ffff-4fff-8fff-ffffffffffff")); + var changedEvidence = withRequest(expected, changedRequest); + response = + WorldCanonicalInstanceLifecycleGrpcCodec.toResponse( + changedRequest, changedEvidence); + } else { + response = WorldCanonicalInstanceLifecycleGrpcCodec.toResponse(decoded, expected); + } + observer.onNext(response); + observer.onCompleted(); + } + }; + ServerInterceptor countApplicationHeaders = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + serverCallStarts.incrementAndGet(); + return next.startCall(call, headers); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, countApplicationHeaders, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private WorldCanonicalInstanceLifecycleClient newClient(Server target) + throws IOException, CertificateEncodingException { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("localhost:" + target.getPort()); + return new WorldCanonicalInstanceLifecycleClient( + endpoints, pki.clientProperties(tempDirectory), new GrpcChannelFactory(), NAMESPACE); + } + + private static WorldCanonicalInstanceLifecycleEvidence evidence( + String status, long epoch, long rowVersion, UUID readRequestId) throws Exception { + WorldPublishedStartLocationEvidence selector = + AuthoredWorldReleaseAttestationSelectorTest.selectorEvidence(); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldReleaseAttestationSelectorTest.descriptor(selector); + AuthoredWorldReleaseAttestationEvidence release = + AuthoredWorldReleaseAttestationSelectorTest.release(descriptor, selector); + CompleteLaunchBindingEvidence binding = new CompleteLaunchBindingEvidence(descriptor, release); + RoomTemplateRef startLocation = + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()).startLocation(); + var request = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + readRequestId, + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + "SHARED", + true, + descriptor.controlPlaneRequestId(), + release.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + return new WorldCanonicalInstanceLifecycleEvidence( + request, + binding, + startLocation, + 9_007_199_254_740_993L, + status, + epoch, + rowVersion, + uuid("33333333-3333-4333-8333-333333333333"), + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()) + .graphDigest() + .substring("sha256:".length()), + "sha256:" + "e".repeat(64)); + } + + private static WorldCanonicalInstanceLifecycleEvidence withRequest( + WorldCanonicalInstanceLifecycleEvidence evidence, + WorldCanonicalInstanceLifecycleEvidence.Request request) { + return new WorldCanonicalInstanceLifecycleEvidence( + request, + evidence.launchBinding(), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + evidence.graphSha256(), + evidence.preparationInputDigest()); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request withReadRequestId( + WorldCanonicalInstanceLifecycleEvidence.Request source, UUID readRequestId) { + return new WorldCanonicalInstanceLifecycleEvidence.Request( + source.schemaVersion(), + readRequestId, + source.targetNamespace(), + source.canonicalTenantId(), + source.worldSlug(), + source.canonicalGameInstanceId(), + source.playableStateNamespaceId(), + source.playableStateScope(), + source.publicProduction(), + source.controlPlaneRequestId(), + source.canonicalVersionId(), + source.expectedDescriptorRequestDigest(), + source.expectedDescriptorResultDigest(), + source.expectedReleaseAttestationDigest()); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private enum ResponseMode { + EXACT, + WRONG_READ_REQUEST_ID, + MALFORMED_EVIDENCE + } + + private record TestIdentity(String alias, PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity worldServer, + TestIdentity wrongWorkloadServer, + TestIdentity otherNamespaceServer, + TestIdentity gameSessionClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD lifecycle test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + X509Certificate caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "world-server", WORLD_URI, true), + issueIdentity( + directory, caStore, caFile, "wrong-workload-server", WRONG_WORKLOAD_URI, true), + issueIdentity( + directory, caStore, caFile, "wrong-namespace-server", OTHER_WORLD_URI, true), + issueIdentity( + directory, caStore, caFile, "game-session-client", GAME_SESSION_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory) + throws IOException, CertificateEncodingException { + Path clientCertificate = + writePem( + directory.resolve("game-session-client.crt"), + "CERTIFICATE", + gameSessionClient.certificate().getEncoded()); + Path clientPrivateKey = + writePem( + directory.resolve("game-session-client.key"), + "PRIVATE KEY", + gameSessionClient.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("client-trust-ca.crt"), "CERTIFICATE", caCertificate.getEncoded()); + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(clientCertificate.toString()); + properties.setPrivateKey(clientPrivateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + alias, + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new java.util.ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java new file mode 100644 index 0000000000..62af4d0284 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java @@ -0,0 +1,722 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.Request; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse; +import org.junit.jupiter.api.Test; + +class WorldCanonicalInstanceLifecycleEvidenceTest { + private static final UUID NIL = new UUID(0L, 0L); + + @Test + void completeOwnerCaptureAndExactRequestEchoRoundTrip() throws Exception { + WorldCanonicalInstanceLifecycleEvidence expected = evidence(); + Request request = expected.request(); + + assertThat(Request.fromStored(request.canonicalBytes())).isEqualTo(request); + var wireRequest = WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(request); + assertThat(WorldCanonicalInstanceLifecycleGrpcCodec.fromRequest(wireRequest)) + .isEqualTo(request); + + var firstResponse = WorldCanonicalInstanceLifecycleGrpcCodec.toResponse(request, expected); + var retryResponse = WorldCanonicalInstanceLifecycleGrpcCodec.toResponse(request, expected); + assertThat(retryResponse).isEqualTo(firstResponse); + var decoded = WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse(request, firstResponse); + var reread = WorldCanonicalInstanceLifecycleEvidence.fromStored(decoded.canonicalBytes()); + assertThat(decoded.canonicalBytes()).containsExactly(expected.canonicalBytes()); + assertThat(reread).isEqualTo(expected); + assertThat(reread.hashCode()).isEqualTo(expected.hashCode()); + } + + @Test + void rejectsChangedCanonicalIdentitiesAndEveryExpectedBindingDigest() throws Exception { + WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); + Request request = evidence.request(); + var changedInstance = + copyRequest( + request, + request.readRequestId(), + request.canonicalTenantId(), + request.worldSlug(), + uuid("99999999-9999-4999-8999-999999999999"), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.controlPlaneRequestId(), + request.canonicalVersionId(), + request.expectedDescriptorRequestDigest(), + request.expectedDescriptorResultDigest(), + request.expectedReleaseAttestationDigest()); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse( + changedInstance, + WorldCanonicalInstanceLifecycleGrpcCodec.toResponse(request, evidence))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed exact read request"); + + assertRejectedRequest( + evidence, + copyRequest( + request, + null, + null, + null, + null, + null, + null, + null, + null, + "sha256:" + "1".repeat(64), + null, + null), + "complete launch binding"); + assertRejectedRequest( + evidence, + copyRequest( + request, + null, + uuid("66666666-6666-4666-8666-666666666666"), + null, + null, + null, + null, + null, + null, + null, + null, + null), + "complete launch binding"); + assertRejectedRequest( + evidence, + copyRequest( + request, null, null, "another-world", null, null, null, null, null, null, null, null), + "complete launch binding"); + assertRejectedRequest( + evidence, + copyRequest( + request, + null, + null, + null, + null, + null, + null, + "other-control-request", + null, + null, + null, + null), + "complete launch binding"); + assertRejectedRequest( + evidence, + copyRequest( + request, + null, + null, + null, + null, + null, + null, + null, + uuid("88888888-8888-4888-8888-888888888888"), + null, + null, + null), + "complete launch binding"); + assertRejectedRequest( + evidence, + copyRequest( + request, + null, + null, + null, + null, + null, + null, + null, + null, + "sha256:" + "2".repeat(64), + null, + null), + "complete launch binding"); + assertRejectedRequest( + evidence, + copyRequest( + request, + null, + null, + null, + null, + null, + null, + null, + null, + null, + "sha256:" + "3".repeat(64), + null), + "complete launch binding"); + assertRejectedRequest( + evidence, + copyRequest( + request, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + "sha256:" + "4".repeat(64)), + "complete launch binding"); + + var changedSelector = + new RoomTemplateRef( + evidence.startLocation().tenantId(), + evidence.startLocation().versionId(), + uuid("66666666-6666-4666-8666-666666666666")); + assertThatThrownBy( + () -> + with( + evidence, + request, + evidence.launchBinding(), + changedSelector, + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + evidence.graphSha256(), + evidence.preparationInputDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("release selector"); + assertThatThrownBy( + () -> + with( + evidence, + request, + evidence.launchBinding(), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + "f".repeat(64), + evidence.preparationInputDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("graph digest"); + } + + @Test + void rejectsUnselectedV1ReleaseAndMalformedLifecycleCountersOrDigests() throws Exception { + WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); + var request = evidence.request(); + var descriptor = evidence.launchBinding().descriptor(); + var release = evidence.launchBinding().releaseAttestation(); + var v1Release = + AuthoredWorldReleaseAttestationEvidence.create( + release.targetNamespace(), + release.descriptorResultDigest(), + release.canonicalTenantId(), + release.canonicalVersionId(), + release.worldSlug(), + release.authoredWorldSourceOperationId(), + release.authoredWorldSourceEvidenceDigest(), + release.launchDescriptorId(), + release.publishedReleaseBundleRef(), + release.versionStateEpoch(), + release.publishWorkflowId(), + release.commitId(), + release.participantDigests(), + release.manifestHash(), + release.manifestSchemaVersion(), + release.requiredManifestAssetKeys(), + release.artifactDigests(), + release.commandDefinitions(), + release.generationConfigRevision()); + var v1Request = + copyRequest( + request, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + v1Release.evidenceDigest()); + assertThatThrownBy( + () -> + with( + evidence, + v1Request, + new CompleteLaunchBindingEvidence(descriptor, v1Release), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + evidence.graphSha256(), + evidence.preparationInputDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("selector/v2"); + + assertInvalid(evidence, evidence.runtimeRoomInstanceId(), evidence.lifecycleEpoch(), -1); + assertInvalid(evidence, evidence.runtimeRoomInstanceId(), 0, evidence.rowVersion()); + assertInvalid(evidence, 0, evidence.lifecycleEpoch(), evidence.rowVersion()); + assertThatThrownBy( + () -> + with( + evidence, + evidence.request(), + evidence.launchBinding(), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + NIL, + evidence.graphSha256(), + evidence.preparationInputDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("captureId"); + assertThatThrownBy( + () -> + with( + evidence, + evidence.request(), + evidence.launchBinding(), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + "A".repeat(64), + evidence.preparationInputDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("graphSha256"); + } + + @Test + void requestOnlyAcceptsProvedSharedPublicProductionIdentity() throws Exception { + Request request = evidence().request(); + assertThatThrownBy( + () -> + copyRequest( + request, NIL, null, null, null, null, null, null, null, null, null, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("readRequestId"); + assertThatThrownBy( + () -> + copyRequest( + request, + null, + null, + null, + null, + null, + "ISOLATED", + null, + null, + null, + null, + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("SHARED scope only"); + assertThatThrownBy( + () -> + new Request( + request.schemaVersion(), + request.readRequestId(), + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.canonicalGameInstanceId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + false, + request.controlPlaneRequestId(), + request.canonicalVersionId(), + request.expectedDescriptorRequestDigest(), + request.expectedDescriptorResultDigest(), + request.expectedReleaseAttestationDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("public-production evidence"); + assertThatThrownBy( + () -> + copyRequest( + request, + null, + null, + null, + null, + null, + null, + null, + null, + "not-a-digest", + null, + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("expectedDescriptorRequestDigest"); + } + + @Test + void preservesLongPrecisionAndRejectsOverflowOrNoncanonicalDecimalStrings() throws Exception { + WorldCanonicalInstanceLifecycleEvidence expected = evidence(); + long beyondJavaScriptInteger = 9_007_199_254_740_993L; + WorldCanonicalInstanceLifecycleEvidence precise = + with( + expected, + expected.request(), + expected.launchBinding(), + expected.startLocation(), + beyondJavaScriptInteger, + expected.lifecycleStatus(), + beyondJavaScriptInteger + 2, + beyondJavaScriptInteger + 4, + expected.captureId(), + expected.graphSha256(), + expected.preparationInputDigest()); + assertThat(WorldCanonicalInstanceLifecycleEvidence.fromStored(precise.canonicalBytes())) + .isEqualTo(precise); + + WorldCanonicalInstanceLifecycleEvidence maximum = + with( + expected, + expected.request(), + expected.launchBinding(), + expected.startLocation(), + Long.MAX_VALUE, + expected.lifecycleStatus(), + Long.MAX_VALUE, + Long.MAX_VALUE, + expected.captureId(), + expected.graphSha256(), + expected.preparationInputDigest()); + byte[] maxBytes = maximum.canonicalBytes(); + assertThat(WorldCanonicalInstanceLifecycleEvidence.fromStored(maxBytes)).isEqualTo(maximum); + String maxJson = new String(maxBytes, StandardCharsets.UTF_8); + String overflow = + maxJson.replace( + "\"runtimeRoomInstanceId\":\"" + Long.MAX_VALUE + "\"", + "\"runtimeRoomInstanceId\":\"9223372036854775808\""); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + overflow.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("supported integer range"); + String negative = + maxJson.replace( + "\"lifecycleEpoch\":\"" + Long.MAX_VALUE + "\"", "\"lifecycleEpoch\":\"-1\""); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + negative.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical positive decimal"); + String leadingZero = + maxJson.replace("\"rowVersion\":\"" + Long.MAX_VALUE + "\"", "\"rowVersion\":\"01\""); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + leadingZero.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical nonnegative decimal"); + } + + @Test + void rejectsClosedJsonAndProtobufUnknownOrDuplicateFields() throws Exception { + WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); + String stored = new String(evidence.canonicalBytes(), StandardCharsets.UTF_8); + String unknownField = stored.substring(0, 1) + "\"unsupported\":true," + stored.substring(1); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + unknownField.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + String duplicate = + stored.replace("\"schemaVersion\":1", "\"schemaVersion\":1,\"schemaVersion\":1"); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + duplicate.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> Request.fromStored(new byte[] {(byte) 0xc3, 0x28})) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("strict UTF-8"); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleEvidence.fromStored(new byte[] {(byte) 0xc3, 0x28})) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("strict UTF-8"); + + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + ReadWorldCanonicalInstanceLifecycleRequest request = + WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(evidence.request()).toBuilder() + .setUnknownFields(unknown) + .build(); + assertThatThrownBy(() -> WorldCanonicalInstanceLifecycleGrpcCodec.fromRequest(request)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + ReadWorldCanonicalInstanceLifecycleResponse response = + WorldCanonicalInstanceLifecycleGrpcCodec.toResponse(evidence.request(), evidence) + .toBuilder() + .setUnknownFields(unknown) + .build(); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse(evidence.request(), response)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse( + evidence.request(), + ReadWorldCanonicalInstanceLifecycleResponse.newBuilder() + .setCanonicalResponseBytes(ByteString.EMPTY) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("required"); + } + + private static void assertRejectedRequest( + WorldCanonicalInstanceLifecycleEvidence evidence, Request changed, String message) { + assertThatThrownBy( + () -> + with( + evidence, + changed, + evidence.launchBinding(), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + evidence.graphSha256(), + evidence.preparationInputDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(message); + } + + private static void assertInvalid( + WorldCanonicalInstanceLifecycleEvidence evidence, + long runtimeRoomInstanceId, + long lifecycleEpoch, + long rowVersion) { + assertThatThrownBy( + () -> + with( + evidence, + evidence.request(), + evidence.launchBinding(), + evidence.startLocation(), + runtimeRoomInstanceId, + evidence.lifecycleStatus(), + lifecycleEpoch, + rowVersion, + evidence.captureId(), + evidence.graphSha256(), + evidence.preparationInputDigest())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static WorldCanonicalInstanceLifecycleEvidence with( + WorldCanonicalInstanceLifecycleEvidence source, + Request request, + CompleteLaunchBindingEvidence launchBinding, + RoomTemplateRef startLocation, + long runtimeRoomInstanceId, + String lifecycleStatus, + long lifecycleEpoch, + long rowVersion, + UUID captureId, + String graphSha256, + String preparationInputDigest) { + return new WorldCanonicalInstanceLifecycleEvidence( + request, + launchBinding, + startLocation, + runtimeRoomInstanceId, + lifecycleStatus, + lifecycleEpoch, + rowVersion, + captureId, + graphSha256, + preparationInputDigest); + } + + private static Request copyRequest( + Request source, + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID canonicalGameInstanceId, + UUID playableStateNamespaceId, + String playableStateScope, + String controlPlaneRequestId, + UUID canonicalVersionId, + String expectedDescriptorRequestDigest, + String expectedDescriptorResultDigest, + String expectedReleaseAttestationDigest) { + return new Request( + Request.SCHEMA_VERSION, + readRequestId == null ? source.readRequestId() : readRequestId, + source.targetNamespace(), + canonicalTenantId == null ? source.canonicalTenantId() : canonicalTenantId, + worldSlug == null ? source.worldSlug() : worldSlug, + canonicalGameInstanceId == null + ? source.canonicalGameInstanceId() + : canonicalGameInstanceId, + playableStateNamespaceId == null + ? source.playableStateNamespaceId() + : playableStateNamespaceId, + playableStateScope == null ? source.playableStateScope() : playableStateScope, + source.publicProduction(), + controlPlaneRequestId == null ? source.controlPlaneRequestId() : controlPlaneRequestId, + canonicalVersionId == null ? source.canonicalVersionId() : canonicalVersionId, + expectedDescriptorRequestDigest == null + ? source.expectedDescriptorRequestDigest() + : expectedDescriptorRequestDigest, + expectedDescriptorResultDigest == null + ? source.expectedDescriptorResultDigest() + : expectedDescriptorResultDigest, + expectedReleaseAttestationDigest == null + ? source.expectedReleaseAttestationDigest() + : expectedReleaseAttestationDigest); + } + + private static WorldCanonicalInstanceLifecycleEvidence evidence() throws Exception { + WorldPublishedStartLocationEvidence selector = + WorldPublishedStartLocationGrpcCodecTest.evidence(); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + selector.request().targetNamespace(), + "world-lifecycle-control-request", + selector.request().canonicalTenantId(), + "synthetic-world", + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "sha256:" + "a".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "canonical-instance-launch-descriptor", + 42L, + false, + null, + "{}", + "generation-revision", + 9L, + 7L, + "release-bundle", + false, + null); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + selector.request().contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence release = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision(), + selector); + CompleteLaunchBindingEvidence binding = new CompleteLaunchBindingEvidence(descriptor, release); + WorldDraftStartLocationEvidence selectorReceipt = + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()); + RoomTemplateRef startLocation = selectorReceipt.startLocation(); + Request request = + new Request( + Request.SCHEMA_VERSION, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + "SHARED", + true, + descriptor.controlPlaneRequestId(), + release.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + return new WorldCanonicalInstanceLifecycleEvidence( + request, + binding, + startLocation, + 1042L, + "PREPARING", + 3L, + 0L, + uuid("33333333-3333-4333-8333-333333333333"), + selectorReceipt.graphDigest().substring("sha256:".length()), + "sha256:" + "e".repeat(64)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql b/services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql index 001c180d16..4b7d6eb4c7 100644 --- a/services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql +++ b/services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql @@ -100,7 +100,10 @@ BEGIN OR selection->>'requestDigest' !~ '^[0-9a-f]{64}$' OR selection->>'contentDigest' !~ '^[0-9a-f]{64}$' OR selection->>'versionStateEpoch' !~ '^[1-9][0-9]*$' - OR jsonb_typeof(selection->'versionStateEpoch') IS DISTINCT FROM 'number' + OR jsonb_typeof(selection->'versionStateEpoch') IS DISTINCT FROM 'string' + OR length(selection->>'versionStateEpoch') > 19 + OR (length(selection->>'versionStateEpoch') = 19 + AND selection->>'versionStateEpoch' > '9223372036854775807') OR jsonb_typeof(selection->'digestSchemaVersion') IS DISTINCT FROM 'number' OR selection->>'digestSchemaVersion' IS DISTINCT FROM '3' OR jsonb_typeof(selection->'worldAffectedTuples') IS DISTINCT FROM 'array' THEN diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java index 657d894c23..13dc87c86f 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java @@ -659,10 +659,31 @@ void sqlGuardRejectsMissingInjectedAndMismatchedSelectorBindingsWithoutAnyReleas String participants = json.writeValueAsString( PublishedWorldSelectorFixtures.participants(version.getId(), evidence)); + var originalRequest = json.readTree(original).path("request"); + assertThat(originalRequest.path("versionStateEpoch").isTextual()).isTrue(); + assertThat(originalRequest.path("versionStateEpoch").asText()).matches("[1-9][0-9]*"); assertThatThrownBy(() -> insertRawSelector(fixture, version, "v2", null, participants)) .isInstanceOf(DataAccessException.class); assertThatThrownBy(() -> insertRawSelector(fixture, version, "v1", original, participants)) .isInstanceOf(DataAccessException.class); + for (String invalidEpoch : List.of("0", "01", "-1", "9223372036854775808")) { + var root = (tools.jackson.databind.node.ObjectNode) json.readTree(original); + ((tools.jackson.databind.node.ObjectNode) root.get("request")) + .put("versionStateEpoch", invalidEpoch); + assertThatThrownBy( + () -> + insertRawSelector( + fixture, version, "v2", json.writeValueAsString(root), participants)) + .isInstanceOf(DataAccessException.class); + } + var numericEpoch = (tools.jackson.databind.node.ObjectNode) json.readTree(original); + ((tools.jackson.databind.node.ObjectNode) numericEpoch.get("request")) + .put("versionStateEpoch", 1L); + assertThatThrownBy( + () -> + insertRawSelector( + fixture, version, "v2", json.writeValueAsString(numericEpoch), participants)) + .isInstanceOf(DataAccessException.class); for (String field : List.of( "canonicalTenantId", diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionWorldCanonicalLifecycleVerifier.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionWorldCanonicalLifecycleVerifier.java new file mode 100644 index 0000000000..b39ae0bfcf --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionWorldCanonicalLifecycleVerifier.java @@ -0,0 +1,343 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Objects; +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.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; + +/** + * Validates complete authenticated World lifecycle reads against their exact launch binding. + * + *

This readback is owner evidence only. It does not decide current Account authority, create an + * admission, or make a lifecycle result current beyond the read that was verified. + */ +public final class GameSessionWorldCanonicalLifecycleVerifier { + private static final String PREPARING = "PREPARING"; + private static final String ACTIVE = "ACTIVE"; + private static final String SHARED = "SHARED"; + + /** Full request and complete source/release pair expected from this owner read. */ + public record Expected( + WorldCanonicalInstanceLifecycleEvidence.Request request, + CompleteLaunchBindingEvidence launchBinding) { + public Expected { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(launchBinding, "launchBinding"); + requireExpectedBinding(request, launchBinding); + } + } + + /** A PREPARING snapshot that has passed the exact request and complete-binding checks. */ + public static final class VerifiedPreparing { + private final Expected expected; + private final WorldCanonicalInstanceLifecycleEvidence evidence; + + private VerifiedPreparing(Expected expected, WorldCanonicalInstanceLifecycleEvidence evidence) { + this.expected = expected; + this.evidence = evidence; + } + + public Expected expected() { + return expected; + } + + public WorldCanonicalInstanceLifecycleEvidence evidence() { + return evidence; + } + + public RoomTemplateRef startLocation() { + return evidence.startLocation(); + } + + public long runtimeRoomInstanceId() { + return evidence.runtimeRoomInstanceId(); + } + + public long lifecycleEpoch() { + return evidence.lifecycleEpoch(); + } + + public long rowVersion() { + return evidence.rowVersion(); + } + } + + /** An ACTIVE snapshot tied to its verified PREPARING origin and World capture. */ + public static final class VerifiedActive { + private final Expected expected; + private final WorldCanonicalInstanceLifecycleEvidence evidence; + + private VerifiedActive(Expected expected, WorldCanonicalInstanceLifecycleEvidence evidence) { + this.expected = expected; + this.evidence = evidence; + } + + public Expected expected() { + return expected; + } + + public WorldCanonicalInstanceLifecycleEvidence evidence() { + return evidence; + } + + public RoomTemplateRef startLocation() { + return evidence.startLocation(); + } + + public long runtimeRoomInstanceId() { + return evidence.runtimeRoomInstanceId(); + } + + public long lifecycleEpoch() { + return evidence.lifecycleEpoch(); + } + + public long rowVersion() { + return evidence.rowVersion(); + } + } + + /** Verifies an exact World PREPARING read and returns typed evidence for the later CAS read. */ + public VerifiedPreparing verifyPreparing( + Expected expected, WorldCanonicalInstanceLifecycleEvidence observed) { + requireObserved(expected, observed); + if (!PREPARING.equals(observed.lifecycleStatus())) { + throw new IllegalArgumentException("World lifecycle read is not PREPARING"); + } + return new VerifiedPreparing(expected, observed); + } + + /** + * Rechecks a PREPARING read against a later owner read. Exact response replay is accepted, and + * the mutable current row version may advance but cannot move backwards. + */ + public VerifiedPreparing verifyCurrentPreparing( + VerifiedPreparing previous, + Expected currentRead, + WorldCanonicalInstanceLifecycleEvidence observed) { + Objects.requireNonNull(previous, "previous"); + requireSameRequestBinding(previous.expected.request(), currentRead.request()); + requireSameLaunchBinding(previous.expected.launchBinding(), currentRead.launchBinding()); + requireExpectedBinding(currentRead.request(), currentRead.launchBinding()); + requireObserved(currentRead, observed); + if (!PREPARING.equals(observed.lifecycleStatus())) { + throw new IllegalArgumentException("Current World lifecycle read is not PREPARING"); + } + requireSameCapture(previous.evidence, observed); + if (observed.lifecycleEpoch() != previous.lifecycleEpoch()) { + throw new IllegalArgumentException("Current World PREPARING lifecycle epoch changed"); + } + requireNondecreasingRowVersion(previous.rowVersion(), observed.rowVersion()); + return new VerifiedPreparing(currentRead, observed); + } + + /** + * Verifies the fenced PREPARING to ACTIVE readback for the same complete World capture. The + * lifecycle epoch is World-owned and is deliberately distinct from Game Design's version-state + * epoch carried by the immutable launch descriptor. + */ + public VerifiedActive verifyActiveAfterPreparing( + VerifiedPreparing preparing, + Expected activeRead, + WorldCanonicalInstanceLifecycleEvidence observed) { + Objects.requireNonNull(preparing, "preparing"); + requireSameRequestBinding(preparing.expected.request(), activeRead.request()); + requireSameLaunchBinding(preparing.expected.launchBinding(), activeRead.launchBinding()); + requireExpectedBinding(activeRead.request(), activeRead.launchBinding()); + requireObserved(activeRead, observed); + if (!ACTIVE.equals(observed.lifecycleStatus())) { + throw new IllegalArgumentException("World lifecycle read is not ACTIVE"); + } + long nextPreparingEpoch; + try { + nextPreparingEpoch = Math.addExact(preparing.lifecycleEpoch(), 1L); + } catch (ArithmeticException overflow) { + throw new IllegalArgumentException( + "World PREPARING lifecycle epoch cannot advance", overflow); + } + if (observed.lifecycleEpoch() != nextPreparingEpoch) { + throw new IllegalArgumentException( + "World ACTIVE lifecycle epoch does not immediately follow PREPARING"); + } + if (observed.rowVersion() <= preparing.rowVersion()) { + throw new IllegalArgumentException( + "World ACTIVE row version did not advance beyond PREPARING"); + } + requireSameCapture(preparing.evidence, observed); + requireNondecreasingRowVersion(preparing.rowVersion(), observed.rowVersion()); + return new VerifiedActive(activeRead, observed); + } + + /** + * Validates a later current ACTIVE read or exact replay against prior verified ACTIVE evidence. + * Row version is mutable current-state metadata: equality is a valid replay, advancement is + * valid, and regression is stale evidence. + */ + public VerifiedActive verifyCurrentActive( + VerifiedActive previous, + Expected currentRead, + WorldCanonicalInstanceLifecycleEvidence observed) { + Objects.requireNonNull(previous, "previous"); + requireSameRequestBinding(previous.expected.request(), currentRead.request()); + requireSameLaunchBinding(previous.expected.launchBinding(), currentRead.launchBinding()); + requireExpectedBinding(currentRead.request(), currentRead.launchBinding()); + requireObserved(currentRead, observed); + if (!ACTIVE.equals(observed.lifecycleStatus())) { + throw new IllegalArgumentException("Current World lifecycle read is not ACTIVE"); + } + if (observed.lifecycleEpoch() != previous.lifecycleEpoch()) { + throw new IllegalArgumentException("Current World ACTIVE lifecycle epoch changed"); + } + requireSameCapture(previous.evidence, observed); + requireNondecreasingRowVersion(previous.rowVersion(), observed.rowVersion()); + return new VerifiedActive(currentRead, observed); + } + + private static void requireObserved( + Expected expected, WorldCanonicalInstanceLifecycleEvidence observed) { + Objects.requireNonNull(expected, "expected"); + Objects.requireNonNull(observed, "observed"); + if (!expected.request().equals(observed.request())) { + throw new IllegalArgumentException("World lifecycle response changed the exact read request"); + } + if (!expected.launchBinding().equals(observed.launchBinding())) { + throw new IllegalArgumentException( + "World lifecycle response changed the complete launch binding"); + } + if (observed.lifecycleEpoch() <= 0L) { + throw new IllegalArgumentException("World lifecycle epoch must be positive"); + } + if (observed.rowVersion() < 0L) { + throw new IllegalArgumentException("World current row version must be nonnegative"); + } + if (observed.runtimeRoomInstanceId() <= 0L) { + throw new IllegalArgumentException("World runtime room instance id must be positive"); + } + if (!expectedSelector(expected.launchBinding()).equals(observed.startLocation())) { + throw new IllegalArgumentException( + "World lifecycle selector differs from the complete release attestation"); + } + } + + private static void requireExpectedBinding( + WorldCanonicalInstanceLifecycleEvidence.Request request, + CompleteLaunchBindingEvidence launchBinding) { + AuthoredWorldLaunchDescriptorEvidence descriptor = launchBinding.descriptor(); + AuthoredWorldReleaseAttestationEvidence release = launchBinding.releaseAttestation(); + descriptor.requireValid(); + release.requireValid(descriptor); + WorldPublishedStartLocationEvidence worldSelector = release.worldStartLocationEvidence(); + if (release.schemaVersion() != AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION + || worldSelector == null) { + throw new IllegalArgumentException( + "World lifecycle verification requires complete selector/v2 release evidence"); + } + WorldPublishedStartLocationEvidence.fromStored(worldSelector.canonicalBytes()); + if (!request.targetNamespace().equals(descriptor.targetNamespace()) + || !request.targetNamespace().equals(release.targetNamespace()) + || !request.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !request.canonicalTenantId().equals(release.canonicalTenantId()) + || !request.worldSlug().equals(descriptor.worldSlug()) + || !request.worldSlug().equals(release.worldSlug()) + || !request.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId()) + || !request.expectedDescriptorRequestDigest().equals(descriptor.requestDigest()) + || !request.expectedDescriptorResultDigest().equals(descriptor.resultDigest()) + || !request.expectedReleaseAttestationDigest().equals(release.evidenceDigest()) + || !request.canonicalVersionId().equals(release.canonicalVersionId()) + || !descriptor + .authoredWorldSourceOperationId() + .equals(release.authoredWorldSourceOperationId()) + || !descriptor + .authoredWorldSourceEvidenceDigest() + .equals(release.authoredWorldSourceEvidenceDigest()) + || !request.canonicalTenantId().equals(worldSelector.request().canonicalTenantId()) + || !request.canonicalVersionId().equals(worldSelector.request().canonicalVersionId()) + || !request.targetNamespace().equals(worldSelector.request().targetNamespace()) + || !request.publicProduction() + || !SHARED.equals(request.playableStateScope())) { + throw new IllegalArgumentException( + "World lifecycle request differs from the complete public shared launch binding"); + } + if (request.canonicalGameInstanceId() == null + || request.playableStateNamespaceId() == null + || isNil(request.canonicalGameInstanceId()) + || isNil(request.playableStateNamespaceId())) { + throw new IllegalArgumentException("Canonical World lifecycle request is incomplete"); + } + } + + private static RoomTemplateRef expectedSelector(CompleteLaunchBindingEvidence binding) { + WorldPublishedStartLocationEvidence selector = + binding.releaseAttestation().worldStartLocationEvidence(); + if (selector == null) { + throw new IllegalArgumentException("Complete release selector evidence is required"); + } + return WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()) + .startLocation(); + } + + private static void requireSameCapture( + WorldCanonicalInstanceLifecycleEvidence previous, + WorldCanonicalInstanceLifecycleEvidence current) { + if (!previous.launchBinding().equals(current.launchBinding()) + || !previous.startLocation().equals(current.startLocation()) + || previous.runtimeRoomInstanceId() != current.runtimeRoomInstanceId() + || !previous.captureId().equals(current.captureId()) + || !previous.graphSha256().equals(current.graphSha256()) + || !previous.preparationInputDigest().equals(current.preparationInputDigest())) { + throw new IllegalArgumentException( + "World lifecycle read changed its original preparation capture or selector"); + } + } + + private static void requireSameRequestBinding( + WorldCanonicalInstanceLifecycleEvidence.Request previous, + WorldCanonicalInstanceLifecycleEvidence.Request current) { + Objects.requireNonNull(current, "currentRead.request"); + if (previous.schemaVersion() != current.schemaVersion() + || !previous.targetNamespace().equals(current.targetNamespace()) + || !previous.canonicalTenantId().equals(current.canonicalTenantId()) + || !previous.worldSlug().equals(current.worldSlug()) + || !previous.canonicalGameInstanceId().equals(current.canonicalGameInstanceId()) + || !previous.playableStateNamespaceId().equals(current.playableStateNamespaceId()) + || !previous.playableStateScope().equals(current.playableStateScope()) + || previous.publicProduction() != current.publicProduction() + || !previous.controlPlaneRequestId().equals(current.controlPlaneRequestId()) + || !previous.canonicalVersionId().equals(current.canonicalVersionId()) + || !previous + .expectedDescriptorRequestDigest() + .equals(current.expectedDescriptorRequestDigest()) + || !previous + .expectedDescriptorResultDigest() + .equals(current.expectedDescriptorResultDigest()) + || !previous + .expectedReleaseAttestationDigest() + .equals(current.expectedReleaseAttestationDigest())) { + throw new IllegalArgumentException( + "World lifecycle read changed the complete canonical launch request binding"); + } + } + + private static void requireSameLaunchBinding( + CompleteLaunchBindingEvidence previous, CompleteLaunchBindingEvidence current) { + if (!previous.equals(current)) { + throw new IllegalArgumentException( + "World lifecycle read changed the complete immutable launch binding"); + } + } + + private static boolean isNil(UUID value) { + return new UUID(0L, 0L).equals(value); + } + + private static void requireNondecreasingRowVersion(long previous, long current) { + if (current < previous) { + throw new IllegalArgumentException("World current row version moved backwards"); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionWorldCanonicalLifecycleVerifierTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionWorldCanonicalLifecycleVerifierTest.java new file mode 100644 index 0000000000..7ca97825e2 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionWorldCanonicalLifecycleVerifierTest.java @@ -0,0 +1,1289 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodec; +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.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +class GameSessionWorldCanonicalLifecycleVerifierTest { + private static final UUID OPERATION_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID INTAKE_REQUEST_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID FENCE_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID ACTOR_ID = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID TENANT_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID REGION_TEMPLATE_ID = uuid("88888888-8888-4888-8888-888888888888"); + private static final UUID ZONE_TEMPLATE_ID = uuid("99999999-9999-4999-8999-999999999999"); + private static final UUID ROOM_TEMPLATE_ID = uuid("77777777-7777-4777-8777-777777777777"); + private static final UUID REGION_REVISION_ID = uuid("12345678-1234-4234-8234-123456789001"); + private static final UUID ZONE_REVISION_ID = uuid("12345678-1234-4234-8234-123456789002"); + private static final UUID ROOM_REVISION_ID = uuid("12345678-1234-4234-8234-123456789003"); + private static final ObjectMapper JSON = new ObjectMapper(); + + @Test + void acceptsCompletePreparingAndNextActiveCaptureIncludingExactRetriesAndRowVersionAdvance() + throws Exception { + Fixture preparing = + fixture("PREPARING", 41L, 60L, uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee")); + GameSessionWorldCanonicalLifecycleVerifier verifier = + new GameSessionWorldCanonicalLifecycleVerifier(); + + var verifiedPreparing = verifier.verifyPreparing(preparing.expected(), preparing.evidence()); + assertThat(verifiedPreparing.startLocation()).isEqualTo(preparing.evidence().startLocation()); + assertThat(verifiedPreparing.runtimeRoomInstanceId()) + .isEqualTo(preparing.evidence().runtimeRoomInstanceId()); + assertThat(verifiedPreparing.lifecycleEpoch()).isEqualTo(41L); + assertThat(verifiedPreparing.expected().launchBinding().descriptor().versionStateEpoch()) + .isNotEqualTo(verifiedPreparing.lifecycleEpoch()); + + var exactPreparingRetry = + verifier.verifyCurrentPreparing( + verifiedPreparing, preparing.expected(), preparing.evidence()); + assertThat(exactPreparingRetry.rowVersion()).isEqualTo(60L); + + Fixture currentPreparing = + rebind( + preparing, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeef"), + "PREPARING", + 41L, + 63L, + null, + null, + null, + null, + null); + var verifiedCurrentPreparing = + verifier.verifyCurrentPreparing( + verifiedPreparing, currentPreparing.expected(), currentPreparing.evidence()); + assertThat(verifiedCurrentPreparing.rowVersion()).isEqualTo(63L); + + Fixture active = + rebind( + preparing, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeed"), + "ACTIVE", + 42L, + 64L, + null, + null, + null, + null, + null); + var verifiedActive = + verifier.verifyActiveAfterPreparing( + verifiedCurrentPreparing, active.expected(), active.evidence()); + assertThat(verifiedActive.lifecycleEpoch()).isEqualTo(42L); + assertThat(verifiedActive.rowVersion()).isEqualTo(64L); + assertThat(verifiedActive.evidence().launchBinding()) + .isEqualTo(preparing.evidence().launchBinding()); + + var exactActiveRetry = + verifier.verifyCurrentActive(verifiedActive, active.expected(), active.evidence()); + assertThat(exactActiveRetry.rowVersion()).isEqualTo(64L); + Fixture newerCurrentActive = + rebind( + active, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeec"), + "ACTIVE", + 42L, + 70L, + null, + null, + null, + null, + null); + assertThat( + verifier + .verifyCurrentActive( + verifiedActive, newerCurrentActive.expected(), newerCurrentActive.evidence()) + .rowVersion()) + .isEqualTo(70L); + } + + @Test + void rejectsChangedCanonicalLaunchScopeAndCompleteReleaseAcrossReads() throws Exception { + Fixture preparing = + fixture("PREPARING", 41L, 60L, uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee")); + GameSessionWorldCanonicalLifecycleVerifier verifier = + new GameSessionWorldCanonicalLifecycleVerifier(); + var verified = verifier.verifyPreparing(preparing.expected(), preparing.evidence()); + var request = preparing.expected().request(); + var binding = preparing.expected().launchBinding(); + + var changedTargetNamespaceRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + request.schemaVersion(), + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeef"), + "another-test", + request.canonicalTenantId(), + request.worldSlug(), + request.canonicalGameInstanceId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.publicProduction(), + request.controlPlaneRequestId(), + request.canonicalVersionId(), + request.expectedDescriptorRequestDigest(), + request.expectedDescriptorResultDigest(), + request.expectedReleaseAttestationDigest()); + assertThatThrownBy( + () -> + new GameSessionWorldCanonicalLifecycleVerifier.Expected( + changedTargetNamespaceRequest, binding)) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + new GameSessionWorldCanonicalLifecycleVerifier.Expected( + copyRequest( + request, + null, + uuid("33333333-3333-4333-8333-333333333333"), + null, + null, + null, + null, + null, + null, + null, + null, + null, + null), + binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GameSessionWorldCanonicalLifecycleVerifier.Expected( + copyRequest( + request, + null, + null, + "another-world", + null, + null, + null, + null, + null, + null, + null, + null, + null), + binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GameSessionWorldCanonicalLifecycleVerifier.Expected( + copyRequest( + request, + null, + null, + null, + null, + null, + null, + null, + null, + uuid("33333333-3333-4333-8333-333333333333"), + null, + null, + null), + binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GameSessionWorldCanonicalLifecycleVerifier.Expected( + copyRequest( + request, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + "sha256:" + "0".repeat(64)), + binding)) + .isInstanceOf(IllegalArgumentException.class); + + var changedInstanceRequest = + copyRequest( + request, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeef"), + null, + null, + uuid("33333333-3333-4333-8333-333333333333"), + null, + null, + null, + null, + null, + null, + null, + null); + Fixture changedInstance = fixtureWith(preparing, changedInstanceRequest, preparing.evidence()); + assertThatThrownBy( + () -> + verifier.verifyCurrentPreparing( + verified, changedInstance.expected(), changedInstance.evidence())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical launch request binding"); + + var changedNamespaceRequest = + copyRequest( + request, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeef"), + null, + null, + null, + uuid("44444444-4444-4444-8444-444444444444"), + null, + null, + null, + null, + null, + null, + null); + Fixture changedNamespace = + fixtureWith(preparing, changedNamespaceRequest, preparing.evidence()); + assertThatThrownBy( + () -> + verifier.verifyCurrentPreparing( + verified, changedNamespace.expected(), changedNamespace.evidence())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical launch request binding"); + + var alteredRelease = changedRelease(binding); + var alteredReleaseRequest = + copyRequest( + request, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeef"), + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + alteredRelease.releaseAttestation().evidenceDigest()); + var alteredReleaseEvidence = + withBinding(preparing.evidence(), alteredReleaseRequest, alteredRelease); + Fixture changedRelease = + new Fixture( + new GameSessionWorldCanonicalLifecycleVerifier.Expected( + alteredReleaseRequest, alteredRelease), + alteredReleaseEvidence); + assertThatThrownBy( + () -> + verifier.verifyCurrentPreparing( + verified, changedRelease.expected(), changedRelease.evidence())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical launch request binding"); + + assertThatThrownBy( + () -> + new GameSessionWorldCanonicalLifecycleVerifier.Expected( + copyRequest( + request, + null, + null, + null, + null, + null, + "ISOLATED", + null, + null, + null, + null, + null, + null), + binding)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsChangedCaptureInputGraphSelectorRuntimeRoomAndStaleEpochOrRowVersion() + throws Exception { + Fixture preparing = + fixture("PREPARING", 41L, 60L, uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee")); + GameSessionWorldCanonicalLifecycleVerifier verifier = + new GameSessionWorldCanonicalLifecycleVerifier(); + var verifiedPreparing = verifier.verifyPreparing(preparing.expected(), preparing.evidence()); + Fixture active = + rebind( + preparing, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeed"), + "ACTIVE", + 42L, + 64L, + null, + null, + null, + null, + null); + var verifiedActive = + verifier.verifyActiveAfterPreparing( + verifiedPreparing, active.expected(), active.evidence()); + + assertCurrentActiveRejected( + verifier, + verifiedActive, + active, + withEvidence( + active.evidence(), + active.expected().request(), + "ACTIVE", + 42L, + 64L, + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + null, + null, + null, + null)); + assertThatThrownBy( + () -> + withEvidence( + active.evidence(), + active.expected().request(), + "ACTIVE", + 42L, + 64L, + null, + "a".repeat(64), + null, + null, + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("release selector"); + assertCurrentActiveRejected( + verifier, + verifiedActive, + active, + withEvidence( + active.evidence(), + active.expected().request(), + "ACTIVE", + 42L, + 64L, + null, + null, + "sha256:" + "0".repeat(64), + null, + null)); + assertCurrentActiveRejected( + verifier, + verifiedActive, + active, + withEvidence( + active.evidence(), + active.expected().request(), + "ACTIVE", + 42L, + 64L, + null, + null, + null, + null, + active.evidence().runtimeRoomInstanceId() + 1L)); + + assertThatThrownBy( + () -> + withEvidence( + active.evidence(), + active.expected().request(), + "ACTIVE", + 42L, + 64L, + null, + null, + null, + new RoomTemplateRef( + active.evidence().startLocation().tenantId(), + active.evidence().startLocation().versionId(), + uuid("66666666-6666-4666-8666-666666666666")), + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("release selector"); + + Fixture staleEpoch = + rebind( + preparing, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeed"), + "ACTIVE", + 43L, + 64L, + null, + null, + null, + null, + null); + assertThatThrownBy( + () -> + verifier.verifyActiveAfterPreparing( + verifiedPreparing, staleEpoch.expected(), staleEpoch.evidence())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("immediately follow PREPARING"); + + for (long unchangedOrRegressingRowVersion : List.of(60L, 59L)) { + Fixture staleTransitionRowVersion = + rebind( + preparing, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeed"), + "ACTIVE", + 42L, + unchangedOrRegressingRowVersion, + null, + null, + null, + null, + null); + assertThatThrownBy( + () -> + verifier.verifyActiveAfterPreparing( + verifiedPreparing, + staleTransitionRowVersion.expected(), + staleTransitionRowVersion.evidence())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("row version did not advance"); + } + + Fixture staleRowVersion = + rebind( + active, + active.expected().request().readRequestId(), + "ACTIVE", + 42L, + 63L, + null, + null, + null, + null, + null); + assertThatThrownBy( + () -> + verifier.verifyCurrentActive( + verifiedActive, staleRowVersion.expected(), staleRowVersion.evidence())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("moved backwards"); + + Fixture changedActiveEpoch = + rebind( + active, + active.expected().request().readRequestId(), + "ACTIVE", + 43L, + 65L, + null, + null, + null, + null, + null); + assertThatThrownBy( + () -> + verifier.verifyCurrentActive( + verifiedActive, changedActiveEpoch.expected(), changedActiveEpoch.evidence())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("lifecycle epoch changed"); + } + + @Test + void rejectsNonAdmissibleStatusesAndPreparingEpochOverflow() throws Exception { + Fixture preparing = + fixture("PREPARING", Long.MAX_VALUE, 60L, uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee")); + GameSessionWorldCanonicalLifecycleVerifier verifier = + new GameSessionWorldCanonicalLifecycleVerifier(); + var verifiedPreparing = verifier.verifyPreparing(preparing.expected(), preparing.evidence()); + + assertThatThrownBy( + () -> fixture("UNKNOWN", 42L, 61L, uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeed"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unsupported World lifecycle status"); + assertThatThrownBy(() -> fixture(null, 42L, 61L, uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeed"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unsupported World lifecycle status"); + + Fixture overflowActive = + rebind( + preparing, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeed"), + "ACTIVE", + 1L, + 61L, + null, + null, + null, + null, + null); + assertThatThrownBy( + () -> + verifier.verifyActiveAfterPreparing( + verifiedPreparing, overflowActive.expected(), overflowActive.evidence())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("cannot advance"); + + Fixture active = + rebind( + preparing, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeed"), + "ACTIVE", + Long.MAX_VALUE, + 61L, + null, + null, + null, + null, + null); + assertThatThrownBy(() -> verifier.verifyPreparing(active.expected(), active.evidence())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not PREPARING"); + + for (String status : List.of("FAILED_PRE_ACTIVATION", "TERMINATING", "TERMINATED")) { + Fixture unavailable = + rebind( + preparing, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeed"), + status, + 42L, + 61L, + null, + null, + null, + null, + null); + assertThatThrownBy( + () -> + verifier.verifyActiveAfterPreparing( + verifiedPreparing, unavailable.expected(), unavailable.evidence())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not ACTIVE"); + } + } + + private static void assertCurrentActiveRejected( + GameSessionWorldCanonicalLifecycleVerifier verifier, + GameSessionWorldCanonicalLifecycleVerifier.VerifiedActive previouslyVerified, + Fixture expected, + WorldCanonicalInstanceLifecycleEvidence observed) { + assertThatThrownBy( + () -> verifier.verifyCurrentActive(previouslyVerified, expected.expected(), observed)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static Fixture fixture(String status, long epoch, long rowVersion, UUID readRequestId) + throws Exception { + WorldPublishedStartLocationEvidence selector = selectorEvidence(); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + new AuthoredWorldLaunchDescriptorEvidence.Request( + "test", + "world-lifecycle-control-request", + selector.request().canonicalTenantId(), + "synthetic-world", + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "sha256:" + "a".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null), + "canonical-instance-launch-descriptor", + 42L, + false, + null, + "{}", + "generation-revision", + 9L, + 7L, + "release-bundle", + false, + null); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + selector.request().contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence release = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision(), + selector); + CompleteLaunchBindingEvidence binding = new CompleteLaunchBindingEvidence(descriptor, release); + RoomTemplateRef startLocation = + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()).startLocation(); + WorldCanonicalInstanceLifecycleEvidence.Request request = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + readRequestId, + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + "SHARED", + true, + descriptor.controlPlaneRequestId(), + release.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + var evidence = + new WorldCanonicalInstanceLifecycleEvidence( + request, + binding, + startLocation, + 9_007_199_254_740_993L, + status, + epoch, + rowVersion, + uuid("33333333-3333-4333-8333-333333333333"), + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()) + .graphDigest() + .substring("sha256:".length()), + "sha256:" + "e".repeat(64)); + return new Fixture( + new GameSessionWorldCanonicalLifecycleVerifier.Expected(request, binding), evidence); + } + + private static Fixture rebind( + Fixture original, + UUID readRequestId, + String status, + long lifecycleEpoch, + long rowVersion, + UUID captureId, + String graphSha256, + String preparationInputDigest, + RoomTemplateRef startLocation, + Long runtimeRoomInstanceId) { + var request = withReadRequestId(original.expected().request(), readRequestId); + var evidence = + withEvidence( + original.evidence(), + request, + status, + lifecycleEpoch, + rowVersion, + captureId, + graphSha256, + preparationInputDigest, + startLocation, + runtimeRoomInstanceId); + return fixtureWith(original, request, evidence); + } + + private static Fixture fixtureWith( + Fixture original, + WorldCanonicalInstanceLifecycleEvidence.Request request, + WorldCanonicalInstanceLifecycleEvidence evidence) { + return new Fixture( + new GameSessionWorldCanonicalLifecycleVerifier.Expected( + request, original.expected().launchBinding()), + evidence); + } + + private static WorldCanonicalInstanceLifecycleEvidence withBinding( + WorldCanonicalInstanceLifecycleEvidence evidence, + WorldCanonicalInstanceLifecycleEvidence.Request request, + CompleteLaunchBindingEvidence binding) { + return withEvidence( + evidence, + request, + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + evidence.graphSha256(), + evidence.preparationInputDigest(), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + binding); + } + + private static WorldCanonicalInstanceLifecycleEvidence withEvidence( + WorldCanonicalInstanceLifecycleEvidence original, + WorldCanonicalInstanceLifecycleEvidence.Request request, + String status, + long epoch, + long rowVersion, + UUID captureId, + String graphSha256, + String preparationInputDigest, + RoomTemplateRef startLocation, + Long runtimeRoomInstanceId) { + return withEvidence( + original, + request, + status, + epoch, + rowVersion, + captureId, + graphSha256, + preparationInputDigest, + startLocation, + runtimeRoomInstanceId, + original.launchBinding()); + } + + private static WorldCanonicalInstanceLifecycleEvidence withEvidence( + WorldCanonicalInstanceLifecycleEvidence original, + WorldCanonicalInstanceLifecycleEvidence.Request request, + String status, + long epoch, + long rowVersion, + UUID captureId, + String graphSha256, + String preparationInputDigest, + RoomTemplateRef startLocation, + Long runtimeRoomInstanceId, + CompleteLaunchBindingEvidence binding) { + return new WorldCanonicalInstanceLifecycleEvidence( + request, + binding, + startLocation == null ? original.startLocation() : startLocation, + runtimeRoomInstanceId == null ? original.runtimeRoomInstanceId() : runtimeRoomInstanceId, + status, + epoch, + rowVersion, + captureId == null ? original.captureId() : captureId, + graphSha256 == null ? original.graphSha256() : graphSha256, + preparationInputDigest == null + ? original.preparationInputDigest() + : preparationInputDigest); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request withReadRequestId( + WorldCanonicalInstanceLifecycleEvidence.Request source, UUID readRequestId) { + return new WorldCanonicalInstanceLifecycleEvidence.Request( + source.schemaVersion(), + readRequestId, + source.targetNamespace(), + source.canonicalTenantId(), + source.worldSlug(), + source.canonicalGameInstanceId(), + source.playableStateNamespaceId(), + source.playableStateScope(), + source.publicProduction(), + source.controlPlaneRequestId(), + source.canonicalVersionId(), + source.expectedDescriptorRequestDigest(), + source.expectedDescriptorResultDigest(), + source.expectedReleaseAttestationDigest()); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request copyRequest( + WorldCanonicalInstanceLifecycleEvidence.Request source, + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID canonicalGameInstanceId, + UUID playableStateNamespaceId, + String playableStateScope, + Boolean publicProduction, + String controlPlaneRequestId, + UUID canonicalVersionId, + String expectedDescriptorRequestDigest, + String expectedDescriptorResultDigest, + String expectedReleaseAttestationDigest) { + return new WorldCanonicalInstanceLifecycleEvidence.Request( + source.schemaVersion(), + readRequestId == null ? source.readRequestId() : readRequestId, + source.targetNamespace(), + canonicalTenantId == null ? source.canonicalTenantId() : canonicalTenantId, + worldSlug == null ? source.worldSlug() : worldSlug, + canonicalGameInstanceId == null + ? source.canonicalGameInstanceId() + : canonicalGameInstanceId, + playableStateNamespaceId == null + ? source.playableStateNamespaceId() + : playableStateNamespaceId, + playableStateScope == null ? source.playableStateScope() : playableStateScope, + publicProduction == null ? source.publicProduction() : publicProduction, + controlPlaneRequestId == null ? source.controlPlaneRequestId() : controlPlaneRequestId, + canonicalVersionId == null ? source.canonicalVersionId() : canonicalVersionId, + expectedDescriptorRequestDigest == null + ? source.expectedDescriptorRequestDigest() + : expectedDescriptorRequestDigest, + expectedDescriptorResultDigest == null + ? source.expectedDescriptorResultDigest() + : expectedDescriptorResultDigest, + expectedReleaseAttestationDigest == null + ? source.expectedReleaseAttestationDigest() + : expectedReleaseAttestationDigest); + } + + private static CompleteLaunchBindingEvidence changedRelease( + CompleteLaunchBindingEvidence binding) { + AuthoredWorldReleaseAttestationEvidence old = binding.releaseAttestation(); + AuthoredWorldReleaseAttestationEvidence changed = + AuthoredWorldReleaseAttestationEvidence.create( + old.targetNamespace(), + old.descriptorResultDigest(), + old.canonicalTenantId(), + old.canonicalVersionId(), + old.worldSlug(), + old.authoredWorldSourceOperationId(), + old.authoredWorldSourceEvidenceDigest(), + old.launchDescriptorId(), + old.publishedReleaseBundleRef(), + old.versionStateEpoch(), + old.publishWorkflowId(), + old.commitId(), + old.participantDigests(), + old.manifestHash(), + old.manifestSchemaVersion(), + old.requiredManifestAssetKeys(), + old.artifactDigests(), + List.of("LOOK", "SAY"), + old.generationConfigRevision(), + old.worldStartLocationEvidence()); + return new CompleteLaunchBindingEvidence(binding.descriptor(), changed); + } + + private static WorldPublishedStartLocationEvidence selectorEvidence() throws Exception { + DraftCommitBinding draft = freshGraphBinding(); + var terminalRequest = + new WorldDraftTerminalReadEvidence.Request( + WorldDraftTerminalReadEvidence.Request.SCHEMA_VERSION, + "test", + uuid("33333333-3333-4333-8333-333333333333"), + accountBinding(draft)); + DraftAuthorizationFenceBinding.OwnerReadback committed = + committedReadback(terminalRequest, draft); + List tuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + var request = + new WorldPublishedStartLocationEvidence.Request( + "test", + TENANT_ID, + VERSION_ID, + INTAKE_REQUEST_ID, + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "publication-request", + "a".repeat(64), + 5L, + "publish-workflow", + COMMIT_ID.toString(), + "b".repeat(64), + 3, + tuples); + var result = JSON.readTree(committed.result()); + return new WorldPublishedStartLocationEvidence( + request, + Base64.getDecoder().decode(result.get("startLocationReceiptBase64").textValue()), + committed.fullBinding(), + committed.result()); + } + + private static DraftCommitBinding freshGraphBinding() throws Exception { + String declaration = + JSON.writeValueAsString( + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "startLocation", + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "roomTemplateId", ROOM_TEMPLATE_ID.toString()), + "familyCounts", + List.of( + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_REGION", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT", "count", 0), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE", "count", 0), + Map.of( + "family", + "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING", + "count", + 0)))); + return DraftCommitBinding.create( + new TargetProof( + TENANT_ID, VERSION_ID, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + REQUEST_ID, + COMMIT_ID, + "base-1", + List.of( + new RevisionPayload( + "0", + REGION_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + REGION_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + REGION_TEMPLATE_ID, + declaration)), + new RevisionPayload( + "1", + ZONE_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ZONE_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", ZONE_TEMPLATE_ID, null)), + new RevisionPayload( + "2", + ROOM_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ROOM_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", ROOM_TEMPLATE_ID, null))), + List.of( + affected("REGION", REGION_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ZONE", ZONE_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ROOM", ROOM_TEMPLATE_ID, "ZONE_SUBTREE", ZONE_TEMPLATE_ID)) + .stream() + .flatMap(List::stream) + .toList()); + } + + private static String worldRevisionPayload( + UUID revisionId, String family, UUID templateId, String declaration) throws Exception { + var payload = new java.util.LinkedHashMap(); + payload.put("logicalRevisionId", revisionId.toString()); + payload.put("commitId", COMMIT_ID.toString()); + payload.put("aggregateType", family); + payload.put("aggregateId", templateId.toString()); + if (declaration != null) payload.put("freshGraphDeclaration", JSON.readTree(declaration)); + return JSON.writeValueAsString(payload); + } + + private static List affected( + String family, UUID templateId, String scopeType, UUID scopeId) { + return List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + "AGGREGATE", + templateId.toString(), + "0"), + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + scopeType, + scopeId.toString(), + "0")); + } + + private static byte[] accountBinding(DraftCommitBinding draft) { + byte[] draftBytes = draft.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + OPERATION_ID, + REQUEST_ID, + COMMIT_ID, + FENCE_ID, + ACTOR_ID, + TENANT_ID, + VERSION_ID, + "base-1", + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd").toString(), + null, + "1", + null, + null, + new byte[] {4, 5}))) + .canonicalBytes(); + } + + private static DraftAuthorizationFenceBinding.OwnerReadback committedReadback( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft) throws Exception { + var account = request.accountBinding(); + var operation = new ByteArrayOutputStream(); + var frames = new java.io.DataOutputStream(operation); + java.util.function.Consumer frame = + bytes -> { + try { + frames.writeInt(bytes.length); + frames.write(bytes); + } catch (java.io.IOException impossible) { + throw new AssertionError(impossible); + } + }; + java.util.function.Consumer text = + value -> frame.accept(value.getBytes(StandardCharsets.UTF_8)); + text.accept("world-draft-terminal-operation/v1"); + for (UUID id : + List.of( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId())) text.accept(id.toString()); + frame.accept(draft.canonicalBytes()); + for (String value : + List.of( + request.targetNamespace(), + account.tenantId().toString(), + account.versionId().toString(), + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + Long.toString(draft.target().gameDesignVersionRowId()), + INTAKE_REQUEST_ID.toString(), + "cccccccc-cccc-4ccc-8ccc-cccccccccccc", + "a".repeat(64), + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + "b".repeat(64), + "c".repeat(64))) text.accept(value); + text.accept(sha256(account.canonicalBytes())); + frame.accept(account.canonicalBytes()); + byte[] graph = graphBytes(request, draft); + String graphDigest = sha256(graph); + var receipt = receipt(request, draft, graphDigest); + byte[] receiptBytes = canonical(receipt); + var result = new java.util.LinkedHashMap(); + result.put("schema", "world-draft-graph-applied/v2"); + result.put("status", "APPLIED"); + result.put("operationBytesBase64", Base64.getEncoder().encodeToString(operation.toByteArray())); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(graph)); + result.put("graphDigest", graphDigest); + result.put("startLocationReceiptBase64", Base64.getEncoder().encodeToString(receiptBytes)); + result.put("startLocationReceiptDigest", receipt.get("receiptDigest").textValue()); + result.put( + "appliedEpochs", + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + Map.of( + "aggregateType", + unit.aggregateType(), + "aggregateId", + unit.aggregateId(), + "scopeType", + unit.scopeType(), + "scopeId", + unit.scopeId(), + "expectedEpoch", + unit.expectedEpoch(), + "resultingEpoch", + new java.math.BigInteger(unit.expectedEpoch()) + .add(java.math.BigInteger.ONE) + .toString())) + .toList()); + var ownerReadback = + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + account.operationId(), + account.commitId(), + account.fenceId(), + account.inputDigest(), + account.canonicalBytes(), + canonical(JSON.valueToTree(result))); + return WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(ownerReadback))) + .ownerReadback() + .orElseThrow(); + } + + private static byte[] graphBytes( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft) throws Exception { + var root = new java.util.LinkedHashMap(); + root.put("schemaVersion", "2"); + root.put("canonicalTenantId", draft.target().canonicalTenantId().toString()); + root.put("canonicalVersionId", draft.target().canonicalVersionId().toString()); + var rows = new java.util.ArrayList>(); + int mappingId = 1; + long privateRowKey = 101; + for (RevisionPayload revision : draft.revisions()) { + if (revision.owner() != DraftCommitBinding.Owner.WORLD_MANAGEMENT) continue; + var mutation = JSON.readTree(revision.payload()); + String family = + mutation.get("aggregateType").textValue().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + var mapping = new java.util.LinkedHashMap(); + mapping.put("id", mappingId++); + mapping.put("target_namespace", request.targetNamespace()); + mapping.put("canonical_tenant_id", draft.target().canonicalTenantId().toString()); + mapping.put("canonical_version_id", draft.target().canonicalVersionId().toString()); + mapping.put("family", family); + mapping.put("template_id", mutation.get("aggregateId").textValue()); + mapping.put("private_row_key", privateRowKey++); + mapping.put("tenant_id", 11); + mapping.put("version_id", 19); + mapping.put("version_identity_operation_id", OPERATION_ID.toString()); + mapping.put("request_id", draft.requestId().toString()); + mapping.put("commit_id", draft.commitId().toString()); + mapping.put("revision_id", revision.revisionId().toString()); + mapping.put("revision_order", revision.revisionOrder()); + rows.add(Map.of("mapping", mapping, "content", Map.of())); + } + root.put("rows", rows); + return JSON.writeValueAsBytes(root); + } + + private static tools.jackson.databind.node.ObjectNode receipt( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft, String graphDigest) + throws Exception { + var account = request.accountBinding(); + var selector = + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "roomTemplateId", ROOM_TEMPLATE_ID.toString()); + String accountBindingDigest = sha256(request.originalAccountBinding()); + String receiptDigest = + startLocationReceiptDigest( + request.targetNamespace(), + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + accountBindingDigest, + draft.digest(), + TENANT_ID, + VERSION_ID, + ROOM_TEMPLATE_ID, + graphDigest); + var value = new java.util.LinkedHashMap(); + value.put("schema", "world-draft-start-location-receipt/v1"); + value.put("targetNamespace", request.targetNamespace()); + value.put("operationId", account.operationId().toString()); + value.put("requestId", account.requestId().toString()); + value.put("commitId", account.commitId().toString()); + value.put("authorizationFenceId", account.fenceId().toString()); + value.put("accountBindingDigest", accountBindingDigest); + value.put("bindingDigest", draft.digest()); + value.put("startLocation", selector); + value.put("graphDigest", graphDigest); + value.put("receiptDigest", receiptDigest); + return (tools.jackson.databind.node.ObjectNode) JSON.valueToTree(value); + } + + private static String startLocationReceiptDigest( + String targetNamespace, + UUID operationId, + UUID requestId, + UUID commitId, + UUID fenceId, + String accountBindingDigest, + String bindingDigest, + UUID tenantId, + UUID versionId, + UUID roomTemplateId, + String graphDigest) + throws Exception { + var framed = new ByteArrayOutputStream(); + for (String value : + List.of( + "world-draft-start-location-receipt/v1", + targetNamespace, + operationId.toString(), + requestId.toString(), + commitId.toString(), + fenceId.toString(), + accountBindingDigest, + bindingDigest, + tenantId.toString(), + versionId.toString(), + roomTemplateId.toString(), + graphDigest)) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + framed.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); + framed.writeBytes(bytes); + } + return sha256(framed.toByteArray()); + } + + private static byte[] canonical(Object value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static String sha256(byte[] bytes) throws Exception { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture( + GameSessionWorldCanonicalLifecycleVerifier.Expected expected, + WorldCanonicalInstanceLifecycleEvidence evidence) {} +} 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 index a2a0ccff36..3f9247068d 100644 --- 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 @@ -193,6 +193,18 @@ public Optional read(String namespace, UUID in 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); + } + + private Optional readValidated( + String namespace, UUID intakeRequestId) { validateReadKey(namespace, intakeRequestId); Record record = findByRequest(namespace, intakeRequestId); if (record == null) { @@ -485,6 +497,27 @@ private void requireActiveOwnerTransaction() { } } + 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 requireWritableReadCommittedOwnerTransaction() { if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { throw new IllegalStateException( 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 index 94902a39ef..22a745a934 100644 --- 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 @@ -81,6 +81,20 @@ public WorldAuthoredVersionIdentityRepository(DSLContext dsl) { 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); + } + + private Optional readByCanonicalVersionValidated( + String namespace, UUID canonicalTenantId, String worldSlug, UUID canonicalVersionId) { validateIdentityKey(namespace, canonicalTenantId, worldSlug); requireNonNil(canonicalVersionId, "canonicalVersionId"); Record row = @@ -351,6 +365,27 @@ private static void requireNoActiveTransaction(String label) { } } + 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 static void requireWritableReadCommittedOwnerTransaction() { if (!TransactionSynchronizationManager.isActualTransactionActive()) { throw new IllegalStateException( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java index 826fce30ef..53f96728ac 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java @@ -369,15 +369,27 @@ public void retainClaimInOwnerTransaction(WorldCanonicalInstanceAssociation.Clai public Optional readOwnerAssociation( UUID canonicalGameInstanceId) { requireNoActiveTransaction("World canonical instance association read"); + return readOwnerAssociation(canonicalGameInstanceId, false); + } + + /** Reconstructs the association without leaving the lifecycle owner's verified snapshot. */ + Optional readOwnerAssociationInOwnerTransaction( + UUID canonicalGameInstanceId) { + requireReadOnlyRepeatableReadOwnerTransaction(); + return readOwnerAssociation(canonicalGameInstanceId, true); + } + + private Optional readOwnerAssociation( + UUID canonicalGameInstanceId, boolean inOwnerSnapshot) { requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); Record row = findByCanonicalGameInstance(canonicalGameInstanceId); if (row == null) { return Optional.empty(); } - return Optional.of(toAssociation(row)); + return Optional.of(toAssociation(row, inOwnerSnapshot)); } - private WorldCanonicalInstanceAssociation toAssociation(Record row) { + private WorldCanonicalInstanceAssociation toAssociation(Record row, boolean inOwnerSnapshot) { try { short schemaVersion = required(row, SCHEMA_VERSION); if (schemaVersion != 1) { @@ -391,8 +403,10 @@ private WorldCanonicalInstanceAssociation toAssociation(Record row) { UUID bindingOperationId = required(row, LAUNCH_BINDING_OPERATION_ID); UUID intakeRequestId = required(row, INTAKE_REQUEST_ID); WorldCompleteLaunchBindingRepository.StoredBinding storedBinding = - launchBindingRepository - .read(namespace, tenantId, controlRequestId) + (inOwnerSnapshot + ? launchBindingRepository.readInOwnerReadOnlyRepeatableRead( + namespace, tenantId, controlRequestId) + : launchBindingRepository.read(namespace, tenantId, controlRequestId)) .orElseThrow( () -> new InvalidAssociationEvidenceException( @@ -402,8 +416,10 @@ private WorldCanonicalInstanceAssociation toAssociation(Record row) { "World canonical association substituted its complete launch binding"); } WorldAuthoredSourceIntakeReceipt sourceReceipt = - sourceIntakeRepository - .read(namespace, intakeRequestId) + (inOwnerSnapshot + ? sourceIntakeRepository.readInOwnerReadOnlyRepeatableRead( + namespace, intakeRequestId) + : sourceIntakeRepository.read(namespace, intakeRequestId)) .orElseThrow( () -> new InvalidAssociationEvidenceException( @@ -412,8 +428,11 @@ private WorldCanonicalInstanceAssociation toAssociation(Record row) { launchBindingRepository.toReceipt(storedBinding, sourceReceipt); UUID canonicalVersionId = required(row, CANONICAL_VERSION_ID); WorldAuthoredVersionIdentityReceipt versionIdentity = - versionIdentityRepository - .readByCanonicalVersion(namespace, tenantId, worldSlug, canonicalVersionId) + (inOwnerSnapshot + ? versionIdentityRepository.readByCanonicalVersionInOwnerReadOnlyRepeatableRead( + namespace, tenantId, worldSlug, canonicalVersionId) + : versionIdentityRepository.readByCanonicalVersion( + namespace, tenantId, worldSlug, canonicalVersionId)) .orElseThrow( () -> new InvalidAssociationEvidenceException( @@ -813,6 +832,27 @@ private static void requireNoActiveTransaction(String label) { } } + private void requireReadOnlyRepeatableReadOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World canonical association 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 canonical association snapshot read requires a read-only REPEATABLE READ owner transaction"); + } + } + private static void requireWritableReadCommittedOwnerTransaction() { if (!TransactionSynchronizationManager.isActualTransactionActive()) { throw new IllegalStateException( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcService.java new file mode 100644 index 0000000000..4a09c56c48 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcService.java @@ -0,0 +1,117 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInstanceLifecycleReadServiceGrpc; +import org.jooq.exception.DataAccessException; +import org.springframework.dao.TransientDataAccessException; + +/** Standalone exact authenticated read adapter; intentionally not registered as a runtime RPC. */ +public final class WorldCanonicalInstanceLifecycleReadGrpcService + extends WorldCanonicalInstanceLifecycleReadServiceGrpc + .WorldCanonicalInstanceLifecycleReadServiceImplBase { + private final WorldCanonicalInstanceLifecycleReadRepository repository; + private final String trustedNamespace; + + public WorldCanonicalInstanceLifecycleReadGrpcService( + WorldCanonicalInstanceLifecycleReadRepository repository, String trustedNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void readWorldCanonicalInstanceLifecycle( + ReadWorldCanonicalInstanceLifecycleRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedGameSessionPeer(responseObserver)) return; + + WorldCanonicalInstanceLifecycleEvidence.Request readRequest; + try { + readRequest = WorldCanonicalInstanceLifecycleGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException invalid) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("A complete canonical World lifecycle read request is required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(readRequest.targetNamespace())) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("World lifecycle namespace must match the authenticated peer") + .asRuntimeException()); + return; + } + + WorldCanonicalInstanceLifecycleEvidence evidence; + try { + evidence = repository.read(readRequest).orElse(null); + } catch ( + WorldCanonicalInstanceLifecycleReadRepository.InvalidLifecycleEvidenceException + inconsistent) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Canonical World lifecycle source evidence is inconsistent") + .asRuntimeException()); + return; + } catch (TransientDataAccessException | DataAccessException unavailable) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Canonical World lifecycle storage is temporarily unavailable") + .asRuntimeException()); + return; + } catch (RuntimeException failure) { + responseObserver.onError( + Status.INTERNAL + .withDescription("Canonical World lifecycle read failed") + .asRuntimeException()); + return; + } + if (evidence == null) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No exact materialized canonical World instance matches the request") + .asRuntimeException()); + return; + } + + ReadWorldCanonicalInstanceLifecycleResponse response; + try { + response = WorldCanonicalInstanceLifecycleGrpcCodec.toResponse(readRequest, evidence); + } catch (IllegalArgumentException | IllegalStateException invalidEvidence) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Canonical World lifecycle response evidence is inconsistent") + .asRuntimeException()); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + private boolean requireAuthenticatedGameSessionPeer(StreamObserver responseObserver) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer != null + && peer.isService("game-session-service") + && peer.isInNamespace(trustedNamespace) + && !SessionContext.hasAuthenticatedCallerContext()) { + return true; + } + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "Only the verified same-namespace Game Session workload without end-user context is allowed") + .asRuntimeException()); + return false; + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java new file mode 100644 index 0000000000..e9f204c8f4 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java @@ -0,0 +1,625 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.exception.DataAccessException; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Reconstructs a current canonical World lifecycle snapshot from one owner-local MVCC snapshot. + * + *

This repository is intentionally not registered as a Spring component. A positive result is + * exact World-owned evidence, not current Account authority, an activation command, or gameplay + * admission permission. + */ +public final class WorldCanonicalInstanceLifecycleReadRepository { + private static final Set INPUT_FIELDS = + Set.of( + "schemaVersion", + "identity", + "gameSessionReadRequest", + "gameSessionReadEvidence", + "launchBinding", + "versionIdentity", + "sourceIntake", + "topology", + "worldStartLocationEvidenceBase64"); + private static final JsonMapper CLOSED_JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + private final DSLContext dsl; + private final TransactionTemplate transaction; + private final WorldCanonicalInstanceAssociationRepository associationRepository; + + public WorldCanonicalInstanceLifecycleReadRepository( + DSLContext dsl, + PlatformTransactionManager transactionManager, + WorldCanonicalInstanceAssociationRepository associationRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.associationRepository = + Objects.requireNonNull(associationRepository, "associationRepository"); + transaction = + new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + transaction.setReadOnly(true); + } + + /** + * Reads only the exact canonical association requested, then follows its private World row key. + * Missing association or not-yet-materialized preparation is an ordinary empty read. + */ + public Optional read( + WorldCanonicalInstanceLifecycleEvidence.Request request) { + Objects.requireNonNull(request, "request"); + requireNoActiveTransaction("World canonical lifecycle read"); + return Optional.ofNullable( + transaction.execute( + status -> { + requireReadOnlyRepeatableReadOwnerTransaction(); + try { + Optional maybeAssociation = + associationRepository.readOwnerAssociationInOwnerTransaction( + request.canonicalGameInstanceId()); + if (maybeAssociation.isEmpty()) return null; + WorldCanonicalInstanceAssociation association = maybeAssociation.orElseThrow(); + if (!matchesRequest(request, association)) return null; + + Record preparation = + dsl.fetchOne( + "SELECT canonical_game_instance_id, capture_id, graph_sha256, input_digest, input_json, " + + "graph_bytes, world_instance_id, private_game_instance_key, region_count, zone_count, " + + "room_count, exit_count, storage_status " + + "FROM world_canonical_instance_preparation WHERE canonical_game_instance_id = ?", + request.canonicalGameInstanceId()); + if (preparation == null) return null; + return readMaterialized(request, association, preparation); + } catch (TransientDataAccessException | DataAccessException unavailable) { + throw unavailable; + } catch ( + WorldCanonicalInstanceAssociationRepository.InvalidAssociationEvidenceException + inconsistent) { + throw new InvalidLifecycleEvidenceException( + "Canonical World association source evidence is inconsistent", inconsistent); + } + })); + } + + private WorldCanonicalInstanceLifecycleEvidence readMaterialized( + WorldCanonicalInstanceLifecycleEvidence.Request request, + WorldCanonicalInstanceAssociation association, + Record preparation) { + try { + UUID canonicalGameInstanceId = request.canonicalGameInstanceId(); + UUID captureId = required(preparation, "capture_id", UUID.class); + String graphSha256 = required(preparation, "graph_sha256", String.class); + String inputDigest = required(preparation, "input_digest", String.class); + String inputJson = required(preparation, "input_json", String.class); + byte[] graphBytes = required(preparation, "graph_bytes", byte[].class); + if (!canonicalGameInstanceId.equals( + required(preparation, "canonical_game_instance_id", UUID.class)) + || required(preparation, "world_instance_id", Long.class) != association.worldInstanceId() + || required(preparation, "private_game_instance_key", Long.class) + != association.worldPrepareFields().privateGameInstanceKey() + || !"MATERIALIZED_UNVERIFIED" + .equals(required(preparation, "storage_status", String.class))) { + throw invalid( + "Retained World preparation differs from its immutable canonical association"); + } + String retainedGraphSha = HexFormat.of().formatHex(sha256(graphBytes)); + String retainedInputDigest = digest(inputJson.getBytes(StandardCharsets.UTF_8)); + if (!retainedGraphSha.equals(graphSha256) || !retainedInputDigest.equals(inputDigest)) { + throw invalid("Retained World preparation bytes differ from their immutable digests"); + } + + JsonNode input = parseInput(inputJson); + requireInputIdentity(input, request, association, captureId); + requirePreparationCounts(input, preparation); + + var release = association.completeLaunchBinding().evidence().releaseAttestation(); + if (release.schemaVersion() + != net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence + .SELECTOR_SCHEMA_VERSION + || release.worldStartLocationEvidence() == null) { + throw invalid("Receipt-less retained V1 preparation cannot produce lifecycle evidence"); + } + WorldPublishedStartLocationEvidence selector = release.worldStartLocationEvidence(); + byte[] selectorBytes = selector.canonicalBytes(); + if (!input.has("worldStartLocationEvidenceBase64") + || !java.util.Base64.getEncoder() + .encodeToString(selectorBytes) + .equals(input.get("worldStartLocationEvidenceBase64").textValue())) { + throw invalid( + "Retained V2 preparation selector differs from its complete release evidence"); + } + WorldDraftStartLocationEvidence receipt = + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()); + RoomTemplateRef startLocation = receipt.startLocation(); + if (!request.canonicalTenantId().equals(startLocation.tenantId()) + || !request.canonicalVersionId().equals(startLocation.versionId())) { + throw invalid("Original World ROOM selector differs from the requested canonical Version"); + } + requireOriginalSelector(selector, receipt, graphBytes); + RoomMapping mapping = requireMappedRoom(association, startLocation, selectorBytes); + Record lifecycle = readLifecycleRow(association, request); + + return new WorldCanonicalInstanceLifecycleEvidence( + request, + association.completeLaunchBinding().evidence(), + startLocation, + mapping.runtimeRoomInstanceId(), + required(lifecycle, "status", String.class), + required(lifecycle, "lifecycle_epoch", Long.class), + required(lifecycle, "row_version", Long.class), + captureId, + graphSha256, + inputDigest); + } catch (InvalidLifecycleEvidenceException invalid) { + throw invalid; + } catch (TransientDataAccessException | DataAccessException unavailable) { + throw unavailable; + } catch (RuntimeException invalid) { + throw new InvalidLifecycleEvidenceException( + "Retained canonical World lifecycle source evidence is inconsistent", invalid); + } + } + + private void requireInputIdentity( + JsonNode input, + WorldCanonicalInstanceLifecycleEvidence.Request request, + WorldCanonicalInstanceAssociation association, + UUID captureId) { + JsonNode identity = requiredObject(input, "identity"); + requireText(identity, "canonicalGameInstanceId", request.canonicalGameInstanceId().toString()); + requireText(identity, "targetNamespace", request.targetNamespace()); + requireText(identity, "canonicalTenantId", request.canonicalTenantId().toString()); + requireText(identity, "worldSlug", request.worldSlug()); + requireText( + identity, "playableStateNamespaceId", request.playableStateNamespaceId().toString()); + requireText(identity, "playableStateScope", request.playableStateScope()); + requireBoolean(identity, "publicProduction", request.publicProduction()); + requireText(identity, "controlPlaneRequestId", request.controlPlaneRequestId()); + + JsonNode gsRequest = requiredObject(input, "gameSessionReadRequest"); + requireText(gsRequest, "targetNamespace", request.targetNamespace()); + requireText(gsRequest, "canonicalTenantId", request.canonicalTenantId().toString()); + requireText(gsRequest, "worldSlug", request.worldSlug()); + requireText(gsRequest, "canonicalGameInstanceId", request.canonicalGameInstanceId().toString()); + requireText(gsRequest, "controlPlaneRequestId", request.controlPlaneRequestId()); + requireText( + gsRequest, "expectedDescriptorRequestDigest", request.expectedDescriptorRequestDigest()); + requireText( + gsRequest, "expectedDescriptorResultDigest", request.expectedDescriptorResultDigest()); + requireText( + gsRequest, + "expectedReleaseAttestationEvidenceDigest", + request.expectedReleaseAttestationDigest()); + var descriptor = association.completeLaunchBinding().descriptor(); + requireText(gsRequest, "launchDescriptorId", descriptor.launchDescriptorId()); + + JsonNode gsEvidence = requiredObject(input, "gameSessionReadEvidence"); + requireText(gsEvidence, "targetNamespace", request.targetNamespace()); + requireText(gsEvidence, "canonicalTenantId", request.canonicalTenantId().toString()); + requireText(gsEvidence, "worldSlug", request.worldSlug()); + requireText( + gsEvidence, "canonicalGameInstanceId", request.canonicalGameInstanceId().toString()); + requireText(gsEvidence, "controlPlaneRequestId", request.controlPlaneRequestId()); + requireText( + gsEvidence, "playableStateNamespaceId", request.playableStateNamespaceId().toString()); + requireText(gsEvidence, "playableStateScope", request.playableStateScope()); + requireBoolean(gsEvidence, "publicProduction", request.publicProduction()); + requireText(gsEvidence, "descriptorRequestDigest", request.expectedDescriptorRequestDigest()); + requireText(gsEvidence, "descriptorResultDigest", request.expectedDescriptorResultDigest()); + requireText( + gsEvidence, "releaseAttestationEvidenceDigest", request.expectedReleaseAttestationDigest()); + requireText(gsEvidence, "launchDescriptorId", descriptor.launchDescriptorId()); + requireText(gsEvidence, "descriptorJson", writeClosedEvidenceJson(descriptor)); + requireText( + gsEvidence, + "releaseAttestationJson", + writeClosedEvidenceJson( + association.completeLaunchBinding().evidence().releaseAttestation())); + + var binding = association.completeLaunchBinding(); + JsonNode launch = requiredObject(input, "launchBinding"); + requireInteger(launch, "schemaVersion", binding.schemaVersion()); + requireText(launch, "operationId", binding.operationId().toString()); + requireText(launch, "targetNamespace", request.targetNamespace()); + requireText(launch, "canonicalTenantId", request.canonicalTenantId().toString()); + requireText(launch, "worldSlug", request.worldSlug()); + requireText(launch, "controlPlaneRequestId", request.controlPlaneRequestId()); + requireText(launch, "descriptorRequestDigest", request.expectedDescriptorRequestDigest()); + requireText(launch, "descriptorResultDigest", request.expectedDescriptorResultDigest()); + requireText(launch, "releaseAttestationDigest", request.expectedReleaseAttestationDigest()); + requireText(launch, "canonicalVersionId", request.canonicalVersionId().toString()); + requireText( + launch, "intakeRequestId", binding.sourceIntakeReceipt().intakeRequestId().toString()); + requireInteger(launch, "localTenantKey", binding.sourceIntakeReceipt().localTenantKey()); + requireText( + launch, "intakeOperationId", binding.sourceIntakeReceipt().operationId().toString()); + requireText( + launch, "sourceOperationId", binding.sourceIntakeReceipt().sourceOperationId().toString()); + requireText( + launch, "sourceEvidenceDigest", binding.sourceIntakeReceipt().sourceEvidenceDigest()); + requireText(launch, "intakeRequestDigest", binding.sourceIntakeReceipt().requestDigest()); + requireText(launch, "intakeReceiptDigest", binding.sourceIntakeReceipt().receiptDigest()); + + var version = association.versionIdentity(); + JsonNode versionJson = requiredObject(input, "versionIdentity"); + requireInteger(versionJson, "schemaVersion", version.schemaVersion()); + requireText(versionJson, "operationId", version.operationId().toString()); + requireText(versionJson, "canonicalVersionId", request.canonicalVersionId().toString()); + requireInteger(versionJson, "localVersionKey", version.localVersionKey()); + requireInteger(versionJson, "gameDesignVersionId", version.gameDesignVersionId()); + requireInteger( + versionJson, "versionStateEpoch", version.versionStateEvidence().versionStateEpoch()); + requireText(versionJson, "versionState", version.versionStateEvidence().versionState().name()); + requireText(versionJson, "evidenceDigest", version.versionStateEvidence().evidenceDigest()); + + JsonNode source = requiredObject(input, "sourceIntake"); + requireInteger(source, "schemaVersion", binding.sourceIntakeReceipt().schemaVersion()); + requireText(source, "targetNamespace", request.targetNamespace()); + requireText( + source, "intakeRequestId", binding.sourceIntakeReceipt().intakeRequestId().toString()); + requireText(source, "operationId", binding.sourceIntakeReceipt().operationId().toString()); + requireText(source, "canonicalTenantId", request.canonicalTenantId().toString()); + requireText(source, "worldSlug", request.worldSlug()); + requireText( + source, "sourceOperationId", binding.sourceIntakeReceipt().sourceOperationId().toString()); + requireText( + source, "sourceEvidenceDigest", binding.sourceIntakeReceipt().sourceEvidenceDigest()); + requireText(source, "receiptDigest", binding.sourceIntakeReceipt().receiptDigest()); + requireText(source, "requestDigest", binding.sourceIntakeReceipt().requestDigest()); + requireInteger(source, "localTenantKey", binding.sourceIntakeReceipt().localTenantKey()); + requireText( + source, "sourceEvidence", writeClosedEvidenceJson(binding.sourceIntakeReceipt().source())); + + JsonNode topology = requiredObject(input, "topology"); + requireText(topology, "captureId", captureId.toString()); + requireText(topology, "targetNamespace", request.targetNamespace()); + requireText(topology, "canonicalTenantId", request.canonicalTenantId().toString()); + requireText(topology, "canonicalVersionId", request.canonicalVersionId().toString()); + requireText(topology, "versionIdentityOperationId", version.operationId().toString()); + } + + private void requirePreparationCounts(JsonNode input, Record preparation) { + JsonNode topology = requiredObject(input, "topology"); + requireInteger(topology, "regionCount", required(preparation, "region_count", Integer.class)); + requireInteger(topology, "zoneCount", required(preparation, "zone_count", Integer.class)); + requireInteger(topology, "roomCount", required(preparation, "room_count", Integer.class)); + requireInteger(topology, "exitCount", required(preparation, "exit_count", Integer.class)); + if (required(preparation, "region_count", Integer.class) <= 0 + || required(preparation, "zone_count", Integer.class) < 0 + || required(preparation, "room_count", Integer.class) < 0 + || required(preparation, "exit_count", Integer.class) < 0) { + throw invalid("Retained World preparation topology counts are invalid"); + } + } + + private void requireOriginalSelector( + WorldPublishedStartLocationEvidence selector, + WorldDraftStartLocationEvidence receipt, + byte[] graphBytes) { + Record original = + dsl.fetchOne( + "SELECT s.receipt_bytes,s.account_binding_bytes,s.graph_digest,a.result_bytes,g.graph_bytes " + + "FROM world_draft_start_location_receipt s JOIN world_draft_graph_application a " + + "ON a.operation_id=s.operation_id AND a.request_id=s.request_id AND a.commit_id=s.commit_id " + + "AND a.authorization_fence_id=s.authorization_fence_id " + + "JOIN world_topology_draft_commit g ON g.request_id=s.request_id AND g.commit_id=s.commit_id " + + "WHERE s.operation_id=? AND s.target_namespace=? AND s.canonical_tenant_id=? " + + "AND s.canonical_version_id=? AND s.room_template_id=?", + receipt.operationId(), + receipt.targetNamespace(), + receipt.startLocation().tenantId(), + receipt.startLocation().versionId(), + receipt.startLocation().roomTemplateId()); + if (original == null + || !Arrays.equals( + selector.selectorReceiptBytes(), required(original, "receipt_bytes", byte[].class)) + || !Arrays.equals( + selector.originalAccountBindingBytes(), + required(original, "account_binding_bytes", byte[].class)) + || !Arrays.equals( + selector.appliedResultBytes(), required(original, "result_bytes", byte[].class)) + || !Arrays.equals(graphBytes, required(original, "graph_bytes", byte[].class)) + || !receipt.graphDigest().equals(digest(graphBytes)) + || !receipt.graphDigest().equals(required(original, "graph_digest", String.class))) { + throw invalid("Canonical preparation selector differs from original World source evidence"); + } + } + + private RoomMapping requireMappedRoom( + WorldCanonicalInstanceAssociation association, + RoomTemplateRef startLocation, + byte[] selectorBytes) { + Record selected = + dsl.fetchOne( + "SELECT s.world_instance_id,s.canonical_tenant_id,s.canonical_version_id,s.room_template_id, " + + "s.runtime_room_instance_id,s.receipt_digest,s.graph_digest,s.evidence_bytes, " + + "m.runtime_room_instance_id AS mapped_room_instance_id,m.runtime_row_id AS mapped_room_row_id, " + + "m.template_id AS mapped_template_id,r.room_instance_row_id AS actual_room_instance_id, " + + "r.tenant_id AS room_tenant_key,r.game_instance_id AS room_game_instance_key, " + + "ri.tenant_id AS region_tenant_key,ri.game_instance_id AS region_game_instance_key, " + + "ri.world_instance_id AS room_world_instance_id " + + "FROM world_canonical_preparation_start_location s " + + "JOIN world_canonical_instance_topology_identity m ON m.world_instance_id=s.world_instance_id " + + "AND m.canonical_game_instance_id=s.canonical_game_instance_id AND m.family='ROOM' " + + "AND m.template_id=s.room_template_id " + + "JOIN room_instance r ON r.id=m.runtime_row_id " + + "JOIN region_instance ri ON ri.id=r.region_instance_id " + + "WHERE s.canonical_game_instance_id=?", + association.identity().canonicalGameInstanceId()); + if (selected == null + || required(selected, "world_instance_id", Long.class) != association.worldInstanceId() + || !association + .identity() + .canonicalTenantId() + .equals(required(selected, "canonical_tenant_id", UUID.class)) + || !association + .canonicalVersionId() + .equals(required(selected, "canonical_version_id", UUID.class)) + || !startLocation + .roomTemplateId() + .equals(required(selected, "room_template_id", UUID.class)) + || required(selected, "runtime_room_instance_id", Long.class) + != required(selected, "mapped_room_instance_id", Long.class) + || required(selected, "runtime_room_instance_id", Long.class) + != required(selected, "mapped_room_row_id", Long.class) + || required(selected, "runtime_room_instance_id", Long.class) + != required(selected, "actual_room_instance_id", Long.class) + || !startLocation + .roomTemplateId() + .equals(required(selected, "mapped_template_id", UUID.class)) + || !Arrays.equals(selectorBytes, required(selected, "evidence_bytes", byte[].class)) + || !receiptDigestFromEvidence(selectorBytes) + .equals(required(selected, "receipt_digest", String.class)) + || !WorldDraftStartLocationEvidence.fromStored( + WorldPublishedStartLocationEvidence.fromStored(selectorBytes) + .selectorReceiptBytes()) + .graphDigest() + .equals(required(selected, "graph_digest", String.class)) + || required(selected, "room_tenant_key", Long.class) + != association.worldPrepareFields().privateTenantKey() + || required(selected, "room_game_instance_key", Long.class) + != association.worldPrepareFields().privateGameInstanceKey() + || required(selected, "region_tenant_key", Long.class) + != association.worldPrepareFields().privateTenantKey() + || required(selected, "region_game_instance_key", Long.class) + != association.worldPrepareFields().privateGameInstanceKey() + || required(selected, "room_world_instance_id", Long.class) + != association.worldInstanceId()) { + throw invalid("Canonical ROOM selector is not the exact mapped scoped World runtime room"); + } + return new RoomMapping(required(selected, "runtime_room_instance_id", Long.class)); + } + + private Record readLifecycleRow( + WorldCanonicalInstanceAssociation association, + WorldCanonicalInstanceLifecycleEvidence.Request request) { + Record row = + dsl.fetchOne("SELECT * FROM world_instance WHERE id=?", association.worldInstanceId()); + if (row == null + || required(row, "id", Long.class) != association.worldInstanceId() + || !request + .canonicalGameInstanceId() + .equals(required(row, "canonical_game_instance_id", UUID.class)) + || !request + .targetNamespace() + .equals(required(row, "canonical_target_namespace", String.class)) + || !request.canonicalTenantId().equals(required(row, "canonical_tenant_id", UUID.class)) + || !request.worldSlug().equals(required(row, "canonical_world_slug", String.class)) + || !request + .playableStateNamespaceId() + .equals(required(row, "playable_state_namespace_id", UUID.class)) + || !request.playableStateScope().equals(required(row, "playable_state_scope", String.class)) + || request.publicProduction() != required(row, "public_production", Boolean.class) + || !request + .controlPlaneRequestId() + .equals(required(row, "control_plane_request_id", String.class)) + || !association + .launchBindingOperationId() + .equals(required(row, "canonical_launch_binding_operation_id", UUID.class)) + || required(row, "tenant_id", Long.class) + != association.worldPrepareFields().privateTenantKey() + || required(row, "game_instance_id", Long.class) + != association.worldPrepareFields().privateGameInstanceKey() + || required(row, "version_id", Long.class) + != association.worldPrepareFields().localVersionKey()) { + throw invalid( + "Current World lifecycle row differs from its exact canonical owner association"); + } + long lifecycleEpoch = required(row, "lifecycle_epoch", Long.class); + long rowVersion = required(row, "row_version", Long.class); + if (lifecycleEpoch <= 0 || rowVersion < 0) { + throw invalid("Current World lifecycle row has an invalid epoch or row version"); + } + return row; + } + + private static boolean matchesRequest( + WorldCanonicalInstanceLifecycleEvidence.Request request, + WorldCanonicalInstanceAssociation association) { + var identity = association.identity(); + var binding = association.completeLaunchBinding(); + var release = binding.evidence().releaseAttestation(); + return request.canonicalGameInstanceId().equals(identity.canonicalGameInstanceId()) + && request.targetNamespace().equals(identity.targetNamespace()) + && request.canonicalTenantId().equals(identity.canonicalTenantId()) + && request.worldSlug().equals(identity.worldSlug()) + && request.playableStateNamespaceId().equals(identity.playableStateNamespaceId()) + && request.playableStateScope().equals(identity.playableStateScope()) + && request.publicProduction() == identity.publicProduction() + && request.controlPlaneRequestId().equals(identity.controlPlaneRequestId()) + && request.canonicalVersionId().equals(association.canonicalVersionId()) + && request.expectedDescriptorRequestDigest().equals(binding.descriptor().requestDigest()) + && request.expectedDescriptorResultDigest().equals(binding.descriptor().resultDigest()) + && request.expectedReleaseAttestationDigest().equals(release.evidenceDigest()); + } + + private static JsonNode parseInput(String inputJson) { + try { + JsonNode input = CLOSED_JSON.readTree(inputJson); + requireFields(input, INPUT_FIELDS, "Retained World preparation input"); + if (intValue(input, "schemaVersion") != 2) { + throw invalid("Receipt-less retained V1 preparation cannot produce lifecycle evidence"); + } + if (!CLOSED_JSON.writeValueAsString(input).equals(inputJson)) { + throw invalid("Retained World preparation input is not in its original closed form"); + } + return input; + } catch (tools.jackson.core.JacksonException invalidJson) { + throw new InvalidLifecycleEvidenceException( + "Retained World preparation input is not closed JSON", invalidJson); + } + } + + private static void requireFields(JsonNode value, Set expected, String label) { + if (value == null || !value.isObject()) throw invalid(label + " must be an object"); + Set actual = new java.util.HashSet<>(); + value.propertyNames().forEach(actual::add); + if (!actual.equals(expected)) throw invalid(label + " has missing or unsupported fields"); + } + + private static JsonNode requiredObject(JsonNode parent, String field) { + JsonNode value = parent.get(field); + if (value == null || !value.isObject()) throw invalid(field + " must be an object"); + return value; + } + + private static void requireText(JsonNode parent, String field, String expected) { + JsonNode value = parent.get(field); + if (value == null || !value.isTextual() || !expected.equals(value.textValue())) { + throw invalid("Retained World preparation " + field + " differs from its exact owner input"); + } + } + + private static void requireBoolean(JsonNode parent, String field, boolean expected) { + JsonNode value = parent.get(field); + if (value == null || !value.isBoolean() || expected != value.booleanValue()) { + throw invalid("Retained World preparation " + field + " differs from its exact owner input"); + } + } + + private static void requireInteger(JsonNode parent, String field, long expected) { + JsonNode value = parent.get(field); + if (value == null + || !value.isIntegralNumber() + || !value.canConvertToLong() + || expected != value.longValue()) { + throw invalid("Retained World preparation " + field + " differs from its exact owner input"); + } + } + + private static int intValue(JsonNode parent, String field) { + JsonNode value = parent.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) { + throw invalid("Retained World preparation " + field + " must be an integer"); + } + return value.intValue(); + } + + private static String receiptDigestFromEvidence(byte[] selectorBytes) { + return WorldDraftStartLocationEvidence.fromStored( + WorldPublishedStartLocationEvidence.fromStored(selectorBytes).selectorReceiptBytes()) + .receiptDigest(); + } + + private static String digest(byte[] bytes) { + return "sha256:" + HexFormat.of().formatHex(sha256(bytes)); + } + + private static String writeClosedEvidenceJson(Object value) { + try { + return CLOSED_JSON.writeValueAsString(Objects.requireNonNull(value, "value")); + } catch (tools.jackson.core.JacksonException invalid) { + throw new InvalidLifecycleEvidenceException( + "Original World evidence cannot be encoded for exact preparation comparison", invalid); + } + } + + private static byte[] sha256(byte[] bytes) { + try { + return MessageDigest.getInstance("SHA-256").digest(bytes); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private static T required(Record row, String field, Class type) { + return Objects.requireNonNull(row.get(field, type), "Persisted " + field + " is null"); + } + + private static void requireNoActiveTransaction(String label) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException(label + " must not join an ambient transaction"); + } + } + + private void requireReadOnlyRepeatableReadOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World lifecycle 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 lifecycle read requires a read-only REPEATABLE READ owner transaction"); + } + } + + private static InvalidLifecycleEvidenceException invalid(String message) { + return new InvalidLifecycleEvidenceException(message); + } + + private record RoomMapping(long runtimeRoomInstanceId) { + private RoomMapping { + if (runtimeRoomInstanceId <= 0) throw invalid("Runtime room instance ID must be positive"); + } + } + + public static final class InvalidLifecycleEvidenceException extends IllegalStateException { + public InvalidLifecycleEvidenceException(String message) { + super(message); + } + + public InvalidLifecycleEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java index d14c9aa0c1..9d480111e0 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java @@ -231,7 +231,7 @@ public Optional readOwnerPreparation(Input input) { Record selected = dsl.fetchOne( "SELECT s.*, m.runtime_room_instance_id AS mapped_room_instance_id, " - + "r.room_instance_id AS actual_room_instance_id,r.tenant_id AS room_tenant_key,r.game_instance_id AS room_game_instance_key " + + "r.room_instance_row_id AS actual_room_instance_id,r.tenant_id AS room_tenant_key,r.game_instance_id AS room_game_instance_key " + "FROM world_canonical_preparation_start_location s " + "JOIN world_canonical_instance_topology_identity m ON m.world_instance_id=s.world_instance_id " + "AND m.canonical_game_instance_id=s.canonical_game_instance_id AND m.family='ROOM' " 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 index 79abf22cb8..e967e16b8c 100644 --- 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 @@ -1,6 +1,7 @@ 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; @@ -75,6 +76,18 @@ public WorldCompleteLaunchBindingRepository(DSLContext dsl) { 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); + } + + 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)); @@ -374,6 +387,27 @@ private static void requireNoActiveTransaction(String label) { } } + 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 static void requireWritableReadCommittedOwnerTransaction() { if (!TransactionSynchronizationManager.isActualTransactionActive()) { throw new IllegalStateException( diff --git a/services/world-management-service/src/main/resources/db/migration/V42__world_release_start_location_materialization.sql b/services/world-management-service/src/main/resources/db/migration/V42__world_release_start_location_materialization.sql index 626ea1831f..108d82c335 100644 --- a/services/world-management-service/src/main/resources/db/migration/V42__world_release_start_location_materialization.sql +++ b/services/world-management-service/src/main/resources/db/migration/V42__world_release_start_location_materialization.sql @@ -27,8 +27,9 @@ DECLARE graph "${serviceSchema}".world_topology_draft_commit%ROWTYPE; evidence JSONB; selected JSONB; - freeze JSONB; + publication_request JSONB; retained JSONB; + retained_version_state_epoch BIGINT; expected_tuples JSONB; BEGIN IF input->>'schemaVersion' = '1' THEN @@ -46,28 +47,36 @@ BEGIN evidence := convert_from(decode(input->>'worldStartLocationEvidenceBase64', 'base64'), 'UTF8')::JSONB; selected := evidence->'request'; retained := binding->'worldStartLocationEvidence'; + IF jsonb_typeof(retained->'request') IS DISTINCT FROM 'object' + OR jsonb_typeof(retained->'request'->'versionStateEpoch') IS DISTINCT FROM 'number' + OR retained->'request'->>'versionStateEpoch' !~ '^[1-9][0-9]*$' THEN + RAISE EXCEPTION 'Retained full release selector epoch must be a canonical positive JSON number' + USING ERRCODE = '23514'; + END IF; + retained_version_state_epoch := (retained->'request'->>'versionStateEpoch')::BIGINT; SELECT * INTO STRICT frozen FROM "${serviceSchema}".world_canonical_frozen_topology WHERE capture_id=capture; - freeze := frozen.freeze_request_json::JSONB; + publication_request := frozen.freeze_request_json::JSONB; SELECT coalesce(jsonb_agg(value ORDER BY value->>'owner',value->>'aggregateType',value->>'aggregateId', value->>'scopeType',value->>'scopeId',value->>'expectedEpoch'), '[]'::JSONB) - INTO expected_tuples FROM jsonb_array_elements(freeze->'suppliedOwnedAffectedTuples'); + INTO expected_tuples FROM jsonb_array_elements(publication_request->'suppliedOwnedAffectedTuples'); IF evidence->>'schema' IS DISTINCT FROM 'world-published-start-location-evidence/v1' OR (SELECT count(*) FROM jsonb_object_keys(evidence)) <> 5 - OR selected IS DISTINCT FROM retained->'request' + OR selected IS DISTINCT FROM jsonb_set( + retained->'request', '{versionStateEpoch}', to_jsonb(retained_version_state_epoch::TEXT), FALSE) OR (SELECT count(*) FROM jsonb_object_keys(selected)) <> 13 - OR selected->>'targetNamespace' IS DISTINCT FROM freeze->>'targetNamespace' - OR selected->>'canonicalTenantId' IS DISTINCT FROM freeze->>'canonicalTenantId' - OR selected->>'canonicalVersionId' IS DISTINCT FROM freeze->>'canonicalVersionId' - OR selected->>'intakeRequestId' IS DISTINCT FROM freeze->>'intakeRequestId' - OR selected->>'publicationFence' IS DISTINCT FROM freeze->>'publicationFence' - OR selected->>'publicationRequestId' IS DISTINCT FROM freeze->>'publicationRequestId' - OR selected->>'requestDigest' IS DISTINCT FROM freeze->>'requestDigest' - OR selected->>'versionStateEpoch' IS DISTINCT FROM freeze->>'versionStateEpoch' - OR selected->>'publishWorkflowId' IS DISTINCT FROM freeze->>'publishWorkflowId' - OR selected->>'appliedCommitId' IS DISTINCT FROM freeze->>'appliedCommitId' - OR selected->>'contentDigest' IS DISTINCT FROM freeze->>'contentDigest' + OR selected->>'targetNamespace' IS DISTINCT FROM publication_request->>'targetNamespace' + OR selected->>'canonicalTenantId' IS DISTINCT FROM publication_request->>'canonicalTenantId' + OR selected->>'canonicalVersionId' IS DISTINCT FROM publication_request->>'canonicalVersionId' + OR selected->>'intakeRequestId' IS DISTINCT FROM publication_request->>'intakeRequestId' + OR selected->>'publicationFence' IS DISTINCT FROM publication_request->>'publicationFence' + OR selected->>'publicationRequestId' IS DISTINCT FROM publication_request->>'publicationRequestId' + OR selected->>'requestDigest' IS DISTINCT FROM publication_request->>'requestDigest' + OR selected->>'versionStateEpoch' IS DISTINCT FROM publication_request->>'versionStateEpoch' + OR selected->>'publishWorkflowId' IS DISTINCT FROM publication_request->>'publishWorkflowId' + OR selected->>'appliedCommitId' IS DISTINCT FROM publication_request->>'appliedCommitId' + OR selected->>'contentDigest' IS DISTINCT FROM publication_request->>'contentDigest' OR selected->>'digestSchemaVersion' IS DISTINCT FROM '3' - OR selected->>'digestSchemaVersion' IS DISTINCT FROM freeze->>'digestSchemaVersion' + OR selected->>'digestSchemaVersion' IS DISTINCT FROM publication_request->>'digestSchemaVersion' OR selected->'worldAffectedTuples' IS DISTINCT FROM expected_tuples OR decode(evidence->>'selectorReceiptBytesBase64','base64') IS DISTINCT FROM decode(retained->>'selectorReceiptBytes','base64') OR decode(evidence->>'originalAccountBindingBytesBase64','base64') IS DISTINCT FROM decode(retained->>'originalAccountBindingBytes','base64') @@ -201,7 +210,7 @@ BEGIN JOIN "${serviceSchema}".world_instance w ON w.id=m.world_instance_id WHERE m.world_instance_id=prepared.world_instance_id AND m.canonical_game_instance_id=NEW.canonical_game_instance_id AND m.family='ROOM' AND m.template_id=NEW.room_template_id - AND m.runtime_room_instance_id=NEW.runtime_room_instance_id AND r.room_instance_id=NEW.runtime_room_instance_id + AND m.runtime_room_instance_id=NEW.runtime_room_instance_id AND r.room_instance_row_id=NEW.runtime_room_instance_id AND r.tenant_id=w.tenant_id AND r.game_instance_id=w.game_instance_id) THEN RAISE EXCEPTION 'Original preparation selector differs from exact authored/runtime ROOM mapping' USING ERRCODE='23514'; END IF; diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 6bcca89710..7db8596706 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -5,6 +5,9 @@ import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.util.JsonFormat; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.LinkedHashMap; @@ -24,8 +27,12 @@ import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; 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.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; @@ -35,6 +42,7 @@ 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.service.WorldLifecycleCommandService; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; import net.firedevops.firemud.worldmanagement.v1.GenerationRuleDesignMutation; @@ -108,6 +116,7 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private WorldDesignPublicationFenceRepository fence; @Autowired private ObjectMapper mapper; @Autowired private WorldAuthoredGraphSnapshotRepository snapshots; + @Autowired private WorldLifecycleCommandService lifecycleCommandService; @Autowired private net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService @@ -142,6 +151,22 @@ void releaseSelectorMaterializesItsOriginalRoomAndExactlyRetriesWithSeparateRunt publishedEvidence( publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); var input = preparationInput(f, frozen, selector); + var retainedEpoch = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT jsonb_typeof(release_attestation_json::jsonb->'worldStartLocationEvidence'->'request'->'versionStateEpoch') AS epoch_type," + + "release_attestation_json::jsonb->'worldStartLocationEvidence'->'request'->>'versionStateEpoch' AS epoch_value " + + "FROM world_complete_launch_binding WHERE target_namespace=? AND canonical_tenant_id=? AND control_plane_request_id=?", + input.gameSessionReadEvidence().targetNamespace(), + input.gameSessionReadEvidence().canonicalTenantId(), + input.gameSessionReadEvidence().controlPlaneRequestId())); + assertThat(retainedEpoch.get("epoch_type", String.class)).isEqualTo("number"); + String retainedEpochValue = retainedEpoch.get("epoch_value", String.class); + assertThat(retainedEpochValue).isEqualTo(Long.toString(selector.request().versionStateEpoch())); + var selectorRequestJson = mapper.readTree(selector.canonicalBytes()).get("request"); + assertThat(selectorRequestJson.get("versionStateEpoch").isTextual()).isTrue(); + assertThat(selectorRequestJson.get("versionStateEpoch").textValue()) + .isEqualTo(retainedEpochValue); var repository = preparationRepository(); var service = preparationComponent(repository); var result = service.prepare(input); @@ -178,6 +203,209 @@ void releaseSelectorMaterializesItsOriginalRoomAndExactlyRetriesWithSeparateRunt assertOrigin(); } + @Test + void lifecycleReadFollowsCurrentWorldEpochAndReturnsExactCanonicalServiceEcho() { + Fixture f = fixture(); + var original = application(generationFreePlan(f)); + var roomTemplateId = + original.plan().graph().nodes().stream() + .filter( + node -> + node.mutation().getAggregateType() + == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .map(node -> node.templateId()) + .toList() + .getLast(); + var application = withStartRoom(original, roomTemplateId); + appliedComponent().apply(application); + var frozen = capture(application.plan()); + var selector = + publishedEvidence( + publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + var input = preparationInput(f, frozen, selector); + var preparation = preparationComponent(preparationRepository()); + var materialized = preparation.prepare(input); + var associationRepository = associationRepository(); + var lifecycleRepository = + new WorldCanonicalInstanceLifecycleReadRepository(dsl, manager, associationRepository); + var request = lifecycleReadRequest(input); + + var preparing = lifecycleRepository.read(request).orElseThrow(); + assertThat(preparing.request()).isEqualTo(request); + assertThat(preparing.startLocation()) + .isEqualTo( + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()) + .startLocation()); + assertThat(preparing.startLocation().roomTemplateId()).isEqualTo(roomTemplateId); + assertThat(preparing.runtimeRoomInstanceId()).isEqualTo(materialized.runtimeRoomInstanceId()); + var mappedRoomOwnership = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT r.tenant_id AS room_tenant_id,r.game_instance_id AS room_game_instance_id," + + "ri.tenant_id AS region_tenant_id,ri.game_instance_id AS region_game_instance_id," + + "ri.world_instance_id FROM world_canonical_instance_topology_identity m " + + "JOIN room_instance r ON r.id=m.runtime_row_id " + + "JOIN region_instance ri ON ri.id=r.region_instance_id " + + "WHERE m.world_instance_id=? AND m.canonical_game_instance_id=? AND m.family='ROOM' AND m.template_id=?", + materialized.association().worldInstanceId(), + input.canonicalGameInstanceId(), + roomTemplateId)); + assertThat(mappedRoomOwnership.get("room_tenant_id", Long.class)) + .isEqualTo(materialized.association().worldPrepareFields().privateTenantKey()); + assertThat(mappedRoomOwnership.get("room_game_instance_id", Long.class)) + .isEqualTo(materialized.association().worldPrepareFields().privateGameInstanceKey()); + assertThat(mappedRoomOwnership.get("region_tenant_id", Long.class)) + .isEqualTo(materialized.association().worldPrepareFields().privateTenantKey()); + assertThat(mappedRoomOwnership.get("region_game_instance_id", Long.class)) + .isEqualTo(materialized.association().worldPrepareFields().privateGameInstanceKey()); + assertThat(mappedRoomOwnership.get("world_instance_id", Long.class)) + .isEqualTo(materialized.association().worldInstanceId()); + assertThat(preparing.lifecycleStatus()).isEqualTo("PREPARING"); + assertThat(preparing.lifecycleEpoch()).isEqualTo(1L); + assertThat(preparing.captureId()).isEqualTo(input.captureId()); + assertThat(preparing.graphSha256()).isEqualTo(materialized.graphSha256()); + assertThat(preparing.preparationInputDigest()).isEqualTo(materialized.inputDigest()); + + TransactionTemplate ownerSnapshot = new TransactionTemplate(manager); + ownerSnapshot.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerSnapshot.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + ownerSnapshot.setReadOnly(true); + ownerSnapshot.execute( + status -> { + assertThatThrownBy( + () -> + associationRepository.readOwnerAssociation(request.canonicalGameInstanceId())) + .hasMessageContaining("independent committed owner read"); + assertThatThrownBy( + () -> + new WorldCompleteLaunchBindingRepository(dsl) + .read( + input.gameSessionReadEvidence().targetNamespace(), + input.gameSessionReadEvidence().canonicalTenantId(), + input.gameSessionReadEvidence().controlPlaneRequestId())) + .hasMessageContaining("independent committed owner read"); + assertThatThrownBy( + () -> + new WorldAuthoredSourceIntakeRepository(dsl) + .read( + input.gameSessionReadEvidence().targetNamespace(), + input.versionIdentity().sourceIntakeReceipt().intakeRequestId())) + .hasMessageContaining("committed-outcome owner read"); + assertThatThrownBy( + () -> + new WorldAuthoredVersionIdentityRepository(dsl) + .readByCanonicalVersion( + input.gameSessionReadEvidence().targetNamespace(), + input.gameSessionReadEvidence().canonicalTenantId(), + input.gameSessionReadEvidence().worldSlug(), + input.versionIdentity().canonicalVersionId())) + .hasMessageContaining("independent committed owner read"); + assertThat( + associationRepository.readOwnerAssociationInOwnerTransaction( + request.canonicalGameInstanceId())) + .isPresent(); + return null; + }); + + assertThat( + lifecycleRepository + .read( + lifecycleReadRequest( + input, + "other", + request.canonicalTenantId(), + request.canonicalVersionId(), + request.expectedDescriptorRequestDigest())) + .isEmpty()) + .isTrue(); + assertThat( + lifecycleRepository + .read( + lifecycleReadRequest( + input, + NAMESPACE, + UUID.randomUUID(), + request.canonicalVersionId(), + request.expectedDescriptorRequestDigest())) + .isEmpty()) + .isTrue(); + assertThat( + lifecycleRepository + .read( + lifecycleReadRequest( + input, + NAMESPACE, + request.canonicalTenantId(), + UUID.randomUUID(), + request.expectedDescriptorRequestDigest())) + .isEmpty()) + .isTrue(); + assertThat( + lifecycleRepository + .read( + lifecycleReadRequest( + input, + NAMESPACE, + request.canonicalTenantId(), + request.canonicalVersionId(), + "sha256:" + "d".repeat(64))) + .isEmpty()) + .isTrue(); + assertThat( + lifecycleRepository + .read( + lifecycleReadRequest( + input, + NAMESPACE, + request.canonicalTenantId(), + request.canonicalVersionId(), + request.expectedDescriptorRequestDigest(), + "sha256:" + "e".repeat(64))) + .isEmpty()) + .isTrue(); + + var prepareFields = materialized.association().worldPrepareFields(); + lifecycleCommandService.failPreparedWorldInstance( + prepareFields.privateTenantKey(), + prepareFields.privateGameInstanceKey(), + preparing.lifecycleEpoch(), + "integration lifecycle read movement"); + var failedCurrent = lifecycleRepository.read(request).orElseThrow(); + assertThat(failedCurrent.lifecycleStatus()).isEqualTo("FAILED_PRE_ACTIVATION"); + assertThat(failedCurrent.lifecycleEpoch()).isEqualTo(2L); + assertThat(failedCurrent.rowVersion()).isGreaterThan(preparing.rowVersion()); + + // The real V35 retry preserves immutable preparation history and does not rewrite lifecycle. + assertThat(preparation.prepare(input)).isEqualTo(materialized); + var afterRetry = lifecycleRepository.read(request).orElseThrow(); + assertThat(afterRetry).isEqualTo(failedCurrent); + + // Explicitly injected peer identity is a transport double; this does not prove production mTLS. + var adapter = + new WorldCanonicalInstanceLifecycleReadGrpcService(lifecycleRepository, NAMESPACE); + var response = new LifecycleReadCollector(); + Context context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service", + NAMESPACE, + "game-session-service")); + Context previous = context.attach(); + try { + adapter.readWorldCanonicalInstanceLifecycle( + WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(request), response); + } finally { + context.detach(previous); + } + assertThat(response.error).isNull(); + assertThat(response.completed).isTrue(); + assertThat(WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse(request, response.value)) + .isEqualTo(afterRetry); + assertOrigin(); + } + @Test void releaseSelectorRejectsChangedFrozenRequestAndSqlSubstitutionWithoutRuntimeWrites() { Fixture f = fixture(); @@ -228,6 +456,44 @@ void releaseSelectorRejectsChangedFrozenRequestAndSqlSubstitutionWithoutRuntimeW WorldDraftGraphAppliedResult.digest( substituted.getBytes(StandardCharsets.UTF_8))))) .hasMessageContaining("complete frozen request"); + + var changedEpoch = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + selected.targetNamespace(), + selected.canonicalTenantId(), + selected.canonicalVersionId(), + selected.intakeRequestId(), + selected.publicationFence(), + selected.publicationRequestId(), + selected.requestDigest(), + selected.versionStateEpoch() + 1L, + selected.publishWorkflowId(), + selected.appliedCommitId(), + selected.contentDigest(), + selected.digestSchemaVersion(), + selected.worldAffectedTuples()), + selector.selectorReceiptBytes(), + selector.originalAccountBindingBytes(), + selector.appliedResultBytes()); + var changedEpochInput = + (tools.jackson.databind.node.ObjectNode) + mapper.readTree(WorldCanonicalInstancePreparationRepository.inputJson(input)); + changedEpochInput.put( + "worldStartLocationEvidenceBase64", + java.util.Base64.getEncoder().encodeToString(changedEpoch.canonicalBytes())); + String substitutedEpoch = mapper.writeValueAsString(changedEpochInput); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> + dsl.fetchOne( + "SELECT * FROM world_prepare_canonical_instance(?,?)", + substitutedEpoch, + WorldDraftGraphAppliedResult.digest( + substitutedEpoch.getBytes(StandardCharsets.UTF_8))))) + .hasMessageContaining("complete frozen request"); assertThat( Objects.requireNonNull( dsl.fetchOne( @@ -706,6 +972,65 @@ private WorldCanonicalInstancePreparationRepository preparationRepository() { frozenRepository()); } + private WorldCanonicalInstanceAssociationRepository associationRepository() { + return new WorldCanonicalInstanceAssociationRepository( + dsl, + new WorldCompleteLaunchBindingRepository(dsl), + new WorldAuthoredSourceIntakeRepository(dsl), + new WorldAuthoredVersionIdentityRepository(dsl)); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleReadRequest( + WorldCanonicalInstancePreparation.Input input) { + return lifecycleReadRequest( + input, + NAMESPACE, + input.gameSessionReadEvidence().canonicalTenantId(), + input.completeLaunchBinding().evidence().releaseAttestation().canonicalVersionId(), + input.completeLaunchBinding().descriptor().requestDigest()); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleReadRequest( + WorldCanonicalInstancePreparation.Input input, + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + String descriptorRequestDigest) { + return lifecycleReadRequest( + input, + targetNamespace, + canonicalTenantId, + canonicalVersionId, + descriptorRequestDigest, + input.completeLaunchBinding().evidence().releaseAttestation().evidenceDigest()); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleReadRequest( + WorldCanonicalInstancePreparation.Input input, + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + String descriptorRequestDigest, + String expectedReleaseAttestationDigest) { + var gameSession = input.gameSessionReadEvidence(); + var descriptor = input.completeLaunchBinding().descriptor(); + return new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + UUID.randomUUID(), + targetNamespace, + canonicalTenantId, + gameSession.worldSlug(), + gameSession.canonicalGameInstanceId(), + gameSession.playableStateNamespaceId(), + gameSession.playableStateScope(), + gameSession.publicProduction(), + gameSession.controlPlaneRequestId(), + canonicalVersionId, + descriptorRequestDigest, + descriptor.resultDigest(), + expectedReleaseAttestationDigest); + } + private WorldCanonicalInstancePreparationService preparationComponent( WorldCanonicalInstancePreparationRepository repository) { // Stipulated local verifier only: no production producer, currentness, lifecycle or admission @@ -2515,6 +2840,32 @@ private static void await(CountDownLatch latch) { } } + private static final class LifecycleReadCollector + implements StreamObserver< + net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse> { + private net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse + value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext( + net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse + response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } + private record Fixture( WorldAuthoredSourceIntakeReceipt intake, WorldAuthoredVersionIdentityReceipt version, diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcServiceTest.java new file mode 100644 index 0000000000..f006b176a2 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcServiceTest.java @@ -0,0 +1,162 @@ +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 com.google.protobuf.ByteString; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +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.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadRepository; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse; +import org.junit.jupiter.api.Test; + +class WorldCanonicalInstanceLifecycleReadGrpcServiceTest { + @Test + void rejectsWrongServiceOrNamespaceBeforeDecodingAndStorageAccess() { + var repository = mock(WorldCanonicalInstanceLifecycleReadRepository.class); + var service = new WorldCanonicalInstanceLifecycleReadGrpcService(repository, "test"); + var malformed = + ReadWorldCanonicalInstanceLifecycleRequest.newBuilder() + .setCanonicalRequestBytes(ByteString.copyFromUtf8("not-json")) + .build(); + + Collector wrongService = call(service, malformed, peer("account-service", "test")); + Collector wrongNamespace = call(service, malformed, peer("game-session-service", "other")); + Collector wrongRequestNamespace = + call( + service, + WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(request("other")), + peer("game-session-service", "test")); + assertThat(wrongService.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongRequestNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void rejectsAuthenticatedEndUserContextBeforeDecodingOrStorageAccess() { + var repository = mock(WorldCanonicalInstanceLifecycleReadRepository.class); + var service = new WorldCanonicalInstanceLifecycleReadGrpcService(repository, "test"); + SessionContext.setContext("11111111-1111-4111-8111-111111111111", List.of(), Map.of()); + Collector result; + try { + result = + call( + service, + ReadWorldCanonicalInstanceLifecycleRequest.getDefaultInstance(), + peer("game-session-service", "test")); + } finally { + SessionContext.clear(); + } + assertThat(result.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void exactSameNamespaceGameSessionPeerReachesOnlyExactLifecycleRequest() { + var repository = mock(WorldCanonicalInstanceLifecycleReadRepository.class); + var service = new WorldCanonicalInstanceLifecycleReadGrpcService(repository, "test"); + var read = request("test"); + when(repository.read(read)).thenReturn(Optional.empty()); + + Collector result = + call( + service, + WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(read), + peer("game-session-service", "test")); + + assertThat(result.error).isEqualTo(Status.Code.NOT_FOUND); + verify(repository).read(read); + } + + @Test + void authenticatedPeerWithMalformedRequestFailsBeforeStorageAccess() { + var repository = mock(WorldCanonicalInstanceLifecycleReadRepository.class); + var service = new WorldCanonicalInstanceLifecycleReadGrpcService(repository, "test"); + var malformed = + ReadWorldCanonicalInstanceLifecycleRequest.newBuilder() + .setCanonicalRequestBytes(ByteString.copyFromUtf8("not-json")) + .build(); + + Collector result = call(service, malformed, peer("game-session-service", "test")); + + assertThat(result.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(repository); + } + + private static Collector call( + WorldCanonicalInstanceLifecycleReadGrpcService service, + ReadWorldCanonicalInstanceLifecycleRequest request, + GrpcPeerIdentity peer) { + Collector response = new Collector(); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + service.readWorldCanonicalInstanceLifecycle(request, response); + } finally { + context.detach(previous); + } + return response; + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request request(String namespace) { + return new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + UUID.fromString("11111111-1111-4111-8111-111111111111"), + namespace, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "starter-world", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "SHARED", + true, + "control-request", + UUID.fromString("55555555-5555-4555-8555-555555555555"), + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64)); + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static final class Collector + implements StreamObserver { + private ReadWorldCanonicalInstanceLifecycleResponse value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(ReadWorldCanonicalInstanceLifecycleResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + assertThat(value).isNull(); + assertThat(completed).isFalse(); + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java new file mode 100644 index 0000000000..6fed725aeb --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java @@ -0,0 +1,54 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadRepository; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldCanonicalInstanceLifecycleReadRepositoryTest { + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Test + void rejectsAmbientTransactionBeforeOpeningIndependentOwnerSnapshot() { + var dsl = mock(DSLContext.class); + var manager = mock(PlatformTransactionManager.class); + var association = mock(WorldCanonicalInstanceAssociationRepository.class); + var repository = new WorldCanonicalInstanceLifecycleReadRepository(dsl, manager, association); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> repository.read(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("must not join an ambient transaction"); + verifyNoInteractions(dsl, manager, association); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request request() { + return new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + UUID.fromString("11111111-1111-4111-8111-111111111111"), + "test", + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "starter-world", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "SHARED", + true, + "control-request", + UUID.fromString("55555555-5555-4555-8555-555555555555"), + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64)); + } +} From 741c65d342d6497a43833444f0137430a79892f8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 05:32:49 +1300 Subject: [PATCH 04/13] Bind publication authorization and immutable owner terminal outcomes --- .github/workflows/ci.yml | 50 ++ .../account-service/api-contracts.md | 8 + .../game-design-service/operations.md | 14 +- .../game-design-service/version-control.md | 6 +- ...ame-authoring-publishing-and-activation.md | 2 + .../player-access-and-session.md | 2 + .../DraftAuthorizationFenceRepository.java | 5 +- ...blicationAuthorizationFenceRepository.java | 274 ++++++++ ...ublication_authorization_participation.sql | 220 ++++++ ...orizationFencePostgresIntegrationTest.java | 633 ++++++++++++++++++ ...ationAuthorizationFenceRepositoryTest.java | 47 ++ ...ccountPublicationAuthorizationBinding.java | 150 +++++ .../AuthoredDraftPublishSelectionBinding.java | 359 ++++++++++ ...ntPublicationAuthorizationBindingTest.java | 141 ++++ ...horedDraftPublishSelectionBindingTest.java | 168 +++++ .../draft/AuthoredDraftPublishSelection.java | 360 ++-------- .../gamedesign/entity/PublishAttempt.java | 1 + .../GameDesignPublicationOperation.java | 67 ++ ...eDesignPublicationOperationRepository.java | 120 ++++ ...GameDesignPublicationOperationService.java | 46 ++ .../repository/PublishAttemptRepository.java | 50 +- .../impl/PublishAttemptServiceImpl.java | 9 +- ...ersionAssetExportCandidateServiceImpl.java | 26 + .../VersionPublishCommandServiceImpl.java | 31 +- ...0__publication_operation_terminal_seal.sql | 180 +++++ .../draft/IsolatedPublicationOwnerSetup.java | 97 +++ .../IsolatedPublicationOperationFixtures.java | 67 ++ ...ationOperationPostgresIntegrationTest.java | 213 ++++++ ...leaseCanonicalIdentityIntegrationTest.java | 48 +- ...emptServiceTransactionIntegrationTest.java | 104 +-- ...blicationMinioPostgresIntegrationTest.java | 2 + ...ExportCandidateServiceIntegrationTest.java | 7 +- .../AuthoredDraftPublishSelectionTest.java | 32 +- .../GameDesignPublicationOperationTest.java | 69 ++ .../PublishAttemptRepositoryTest.java | 2 +- ...onAssetExportCandidateServiceImplTest.java | 6 + .../VersionPublishCommandServiceImplTest.java | 15 +- ...onicalInstanceLifecycleReadRepository.java | 36 +- ...aphApplicationPostgresIntegrationTest.java | 2 +- 39 files changed, 3236 insertions(+), 433 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/authorpublication/PublicationAuthorizationFenceRepository.java create mode 100644 services/account-service/src/main/resources/db/migration/V79__publication_authorization_participation.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authorpublication/PublicationAuthorizationFencePostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authorpublication/PublicationAuthorizationFenceRepositoryTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBinding.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBinding.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBindingTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBindingTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperation.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationService.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V50__publication_operation_terminal_seal.sql create mode 100644 services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java create mode 100644 services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9f54f35291..4f57e4e0d3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2204,6 +2204,35 @@ jobs: --require-case 'net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalOutcomePostgresIntegrationTest#migrationDoesNotInventAccountOutcomesForRetainedStatusOnlyRows()' \ game-design-service + - name: Capture Account publication participation PostgreSQL raw XML + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-publication-participation-postgresql-proof-${{ github.sha }}-${{ github.run_id }}-${{ github.run_attempt }} + path: services/account-service/build/test-results/integrationTest/TEST-*PublicationAuthorizationFencePostgresIntegrationTest.xml + if-no-files-found: error + retention-days: 7 + + - name: Verify Account publication participation PostgreSQL execution + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest \ + --require-case 'net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#exactReserveOrderAndRestartReadbackPreserveOriginalBytes()' \ + --require-case 'net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#changedRequestCaptureActorOrAllocatedIdentityCannotReplaceOriginal()' \ + --require-case 'net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#sourceChangeRevokesReservedPublicationButCannotCommitOrAbortWithoutItsOwnTerminalContract()' \ + --require-case 'net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#publicationOrderRemainsUnresolvedAfterOriginalDraftTerminalResults()' \ + --require-case 'net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#waitingChangeDeniesNewReservationAndUnrelatedScopeStillProceeds()' \ + --require-case 'net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#concurrentPublicationClaimAndSourceChangeChooseOneDurableOrder()' \ + --require-case 'net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#rawSqlCannotReplaceOriginalSourceBindingOrOrderOrTruncateEvidence()' \ + --require-case 'net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#failedOwnerTransactionRollsBackReservationAndParticipation()' \ + --require-case 'net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#concurrentExactReservationReturnsOneImmutableOperation()' \ + --require-case 'net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#rawSqlCannotReserveIncompleteSourceParticipationOrSubstituteRequestIdentity()' \ + --require-case 'net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#sqlPreservesJavaSourceLockOrderingForSupplementaryUnicodeScopes()' \ + --require-case 'net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#missingCurrentSchemaFailsClosedAndUpgradePreservesOriginalDraftEvidence()' \ + account-service + - name: Capture World Account-bound graph application PostgreSQL raw XML if: ${{ always() && matrix.module == 'world-management-service' }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 @@ -2273,6 +2302,27 @@ jobs: if-no-files-found: error retention-days: 7 + - name: Capture Game Design publication operation PostgreSQL XML + if: ${{ always() && matrix.module == 'game-design-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: game-design-publication-operation-postgresql-proof-${{ github.sha }}-${{ github.run_attempt }} + path: services/game-design-service/build/test-results/integrationTest/TEST-*GameDesignPublicationOperationPostgresIntegrationTest.xml + if-no-files-found: error + retention-days: 7 + + - name: Verify Game Design publication operation PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'game-design-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest \ + --require-case 'net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#noPublicationReceiptReplaysAfterLostResponseAndExcludesDelayedFinalizerAndRawInsert()' \ + --require-case 'net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#publishedReceiptCannotBeDemotedByStaleFailureAndRetainsOriginalFreezeEpoch()' \ + --require-case 'net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#failedAtomicCommitLeavesAttemptOperationVersionAndReleasePendingForExactRetry()' \ + --require-case 'net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#noPublicationSerializesAgainstAnAlreadyScheduledLatePublisher()' \ + game-design-service + - name: Capture World authored-graph snapshot PostgreSQL XML if: ${{ always() && matrix.module == 'world-management-service' }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 65c3efb03f..b4bcee2920 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -70,6 +70,14 @@ A disclosed terms effective date is never delayed by unresolved owner work and n Account recovery reads the original durable operation rather than recapturing sources or replacing its binding. The [World terminal readback](../world-management-service/api-contracts.md#exact-authored-draft-terminal-readback) and [Game Design terminal readback](../game-design-service/api-contracts.md#exact-authored-draft-terminal-readback) run outside the Account transaction; only independently authenticated, exact terminal results may be recorded in a subsequent short owner transaction. Recovery rechecks the original operation and ordering at that transaction boundary. A stored World-only result must not skip the missing Game Design read, and `UNKNOWN` stores no invented outcome. This readback grants no authorization or source-mutation permission beyond the definitive settlement predicate above. +### Account-Owned Publication Authorization Fence + +Publishing a selected synchronized Draft is a distinct Account-authorized operation, not a reuse of the earlier Draft `COMMIT_ORDER`, creator qualification or source receipt. Its stable preallocation input binds the authenticated acting Account and the complete [Game Design publication selection](../game-design-service/api-contracts.md#draft-commit-and-proposal-semantics-target-state), including all eight original `PublishVersion` inputs and retained synchronized-Draft evidence. Account allocates one operation and fence, captures every applicable independently current source, and durably orders that exact publication against source changes using the same source-lock ordering as other covered creator mutations. Allocated release/artifact identities and subsequent World captures are result evidence; they do not replace or rewrite the original selection digest. `publicationDigestRequest/v1` remains the owner-to-owner digest-read binding, not publication permission. + +The versioned `account-publication-authorization/v1` binding retains the original actor/selection input separately from the allocated operation/fence and sorted source vector. Reservation grants no permission; a publication order alone does not authenticate the actor, establish operative terms or satisfy either owner's commit checks. Every owner retains and verifies this exact operation together with its publication-specific evidence. Original Draft results cannot settle publication. Account accepts only authenticated exact definitive Game Design and World publication outcomes bound to the same operation, request/selection digest and owner fence; unknown, missing or contradictory evidence remains unresolved and source-blocking. In particular, immutable Game Design no-publication evidence must prevent delayed finalization; an absent release, `FAILED` status or timeout is insufficient. Remote owner reads happen outside Account's short settlement transaction, which rechecks the original immutable binding and ordering before recording results. + +Implementation and proof status belongs to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). The publication operation does not waive [hosted-terms currentness](#account-owned-hosted-terms-and-creator-party), its disclosed effective date, the mandatory participant artifacts or either owner's protected commit boundary. + ### Account-Owned Playtest Grant Contract Account is the sole writer and read authority for non-public realm grants under [ADR 0138 (PLAYTEST-01)](../../decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md). The canonical grant identity is `{accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId}`, with `playtestLifecycleId` immutable for the lifecycle; the record carries active/revoked state, monotonic `grantRevision`, `grantExpiresAt`, grantor/audit metadata, and the stable `requestId` outcome. `tenantAdmin` may create, extend, list, and revoke grants only within the exact tenant it administers. Authenticated `platformAdmin` may create, extend, revoke, or deliberately re-grant only through a distinct reasoned and audited `privileged_control`/break-glass grant-mutation branch governed by [Operator Authorization References](#operator-authorization-references) and [operator delegation](../../system-architecture-authz-route-matrix.md#operator-delegation). The branch requires an Account-issued authorization reference bound to the typed grant action, exact target and current playtest lifecycle, canonical `mutationDigest/v1` digest, live `platformAdmin` role, exact target-tenant generation, and `privileged_control` evidence. The grant's stable `requestId` remains the domain idempotency identity; the operator flow's `controlPlaneRequestId` is a separate correlation identity, and the reference binds both. The branch carries an explicit reason and audit attribution, is distinct from `tenantAdmin`, and is not tenant impersonation or a gameplay grant. Both paths validate the exact tenant, world, realm, account, and current playtest lifecycle; a slug or caller-supplied tenant identifier is not proof. diff --git a/design/architecture/microservices/game-design-service/operations.md b/design/architecture/microservices/game-design-service/operations.md index 63de588fa5..075ff65367 100644 --- a/design/architecture/microservices/game-design-service/operations.md +++ b/design/architecture/microservices/game-design-service/operations.md @@ -4,27 +4,29 @@ - Runs as a Kubernetes Deployment (Docker Compose for local dev) with `/actuator/health/readiness` and `/actuator/health/liveness` probes. See [Deployment Environments](../../infrastructure/deployment-environments.md). - Logging, metrics, and tracing follow the standard [Logging & Monitoring](../../system-architecture-logging-monitoring.md) pipeline. -- Publishing a game version is coordinated through the Temporal-backed `publish` workflow family. The synchronous `PublishVersion` API now requires a stable `publish_request_id`, while the durable workflow performs version metadata creation, participant digest gating, release attestation, and publish reconciliation under one caller-visible workflow identity. See [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md) for the overall flow. +- Full-version publication of an existing authored Draft is coordinated through the Temporal-backed `publish` workflow family. `PublishVersion` requires a stable `publish_request_id`; the durable workflow gates the selected Draft, commits release evidence, and reconciles the outcome under one caller-visible workflow identity. See [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md) for the overall flow. ### Publish request identity and digest binding -The target publish contract binds the stable `publish_request_id` to one canonical request digest. Game Design normalizes the complete preallocation caller intent, including `tenantId`, publish type, `notes`, and any other actual request inputs, before computing and durably recording that digest with the workflow/attempt identity. The owner-allocated `versionId` is not an input to that original digest because it does not exist at request admission; after allocation, it is immutable attempt/result evidence bound durably to the same workflow identity and exact replay/readback. A retry with the same `publish_request_id` and the same preallocation-intent digest may attach to or replay the existing workflow and recorded outcome. Reuse of that identity with a different digest is an identity conflict: it must fail closed without executing the new request or returning the prior outcome as though the requests matched. This is the Game Design adopter mapping of [ADR 0078](../../decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md). +Full-version `PublishVersion` selects an existing authored Draft. The immutable `AuthoredDraftPublishSelection` is the canonical binding for the complete caller selection and the synchronized Draft evidence; its `versionId` is supplied at request admission, and reservation does not allocate a replacement Version. Exact retries retain that first selection, while changed or omitted selection input conflicts before workflow attachment. The [Game Design API contract](./api-contracts.md#draft-commit-and-proposal-semantics-target-state) owns the selection fields and evidence. The separate, approved Account publication authorization and complete publication-operation identity must bind to that selection without replacing it; Account's [hosted-terms and creator-party contract](../account-service/api-contracts.md#account-owned-hosted-terms-and-creator-party) owns currentness authority, and World Management's [publication freeze and terminal handoff](../world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state) owns the World fence. These publication-level bindings remain unimplemented. This adopter behavior follows [ADR 0078](../../decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md). -**Current implementation status:** the full-version `publish_attempt` stores and exact-validates `publicationDigestRequest/v1`, binding tenant, allocated version scope, stable publish request, and derived workflow identity. That is the owner-to-owner publication-read binding and intentionally excludes notes and content. Game Design does not yet persist and compare the separate preallocation control-plane content digest that binds notes and every other caller input before version allocation. Temporal `AlreadyStarted` handling can therefore attach a changed-notes request to the same workflow identity even though its publication-read digest still matches. The current implementation proves the scoped owner-read binding, not the target different-control-plane-content conflict behavior. +**Current implementation status:** the selected full-version `publish_attempt` stores and exact-validates `AuthoredDraftPublishSelection.digest()`, which binds the complete caller selection together with its retained target and synchronized-Draft evidence. The selection and its canonical bytes are stored separately and immutably. This is distinct from `publicationDigestRequest/v1`, which remains the owner-to-owner digest-read request binding and does not replace the selected attempt digest. Public full-version publication still denies before workflow dispatch when Account authorization is unavailable; the separate Account publication operation and complete publication-operation identity are not implemented. ### Publication terminality and attempt ownership The publication artifact/release-bundle state, allocated version state, participant/release evidence, and publish-attempt terminal state must commit atomically in one Game Design owner-local transaction. If the workflow boundary cannot provide that transaction, the adopter must use an explicit durable state machine with readback reconciliation; it must never expose `SUCCEEDED` until the artifact and version commit is durably readable and bound to the same immutable request and attempt evidence. A terminal attempt is therefore not an acknowledgement that a separate transaction was started: it is the commit/readback proof of the publication state. -**Current implementation status:** full-version publication reserves its Draft version and PENDING attempt in one owner-local transaction. After participant reads and object export, its final owner-local transaction records participant evidence, artifact state, release bundle, Published version, verified digests, and the SUCCEEDED attempt together. An ambiguous final commit is resolved by exact attempt/version/bundle/artifact readback rather than an independent terminal-success transaction. This implemented success path is behind the required participant digest gate: ordinary full-version requests currently cannot reach it because Game Logic rejects the required full-version participant request without an owner-local manifest/provenance digest. The canonical participant gate and current availability are documented in [Version Control](./version-control.md#owner-to-owner-digest-authorization-and-tenant-identity); script-patch publication does not require the Game Logic participant. The remaining gap is the external phase: participant collection and mutable object-key export occur before that final transaction without a durable external-phase owner, private candidate namespace, or export deduplication. Same-request retries can therefore race before the final Game row lock; a late exporter can overwrite bytes after another attempt's release attestation, while definite-failure cleanup can race an active exporter. The final local transaction does not prove safe external-write ownership, cleanup, or ambiguous object-store recovery. +**Current implementation status:** full-version publication reserves the selected existing Draft and PENDING attempt in one owner-local transaction. After participant reads and object export, its final owner-local transaction records participant evidence, artifact state, release bundle, Published version, verified digests, and the SUCCEEDED attempt together. An ambiguous final commit is resolved by exact attempt/version/bundle/artifact readback rather than an independent terminal-success transaction. This success path is behind the required participant digest gate: ordinary full-version requests currently cannot reach it because Game Logic rejects the required full-version participant request without an owner-local manifest/provenance digest. The canonical participant gate and current availability are documented in [Version Control](./version-control.md#owner-to-owner-digest-authorization-and-tenant-identity); script-patch publication does not require the Game Logic participant. The ordinary-byte exporter now commits and independently reads its exact private candidate before conditional content-addressed writes and byte readback. This does not prove complete publication-attempt ownership, authenticated terminal settlement, abandonment or cleanup; those gates remain separately open in [Asset Storage](./asset-storage.md#implementation-status). -The target attempt record must immutably bind the normalized preallocation request digest, workflow/request identity, allocated version, artifact/release identity, and owner evidence. Every attempt transition must CAS both the expected status and monotonic attempt revision; only the still-current attempt owner may publish a terminal result. Failure cleanup may delete or mark provisional state only when it conditionally owns the same still-current nonterminal attempt and the target has not been won or published. Same-identity/same-digest retries must read back and replay the existing state; a different digest, stale revision/status, or contradictory artifact/version readback fails closed. Focused proof must cover crashes before and after each commit/readback boundary, concurrent exact retries, different-digest reuse, and a losing failure cleanup racing a winning publisher. +The existing attempt `FAILED` status and a read showing no release evidence are not immutable publication no-publication proof. Game Design has no publication-specific authenticated terminal readback that fences a delayed finalizer; its [authored-Draft terminal readback](./api-contracts.md#exact-authored-draft-terminal-readback) covers Draft commits, not publication. A missing row or artifact, a `FAILED` status, or a Temporal timeout must therefore remain pending/reconciliation evidence and must not authorize World Management's `ABORTED` handoff. The required publication-specific readback and full-operation binding remain owner-contract and implementation gaps; see the [World publication handoff](../world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state) and the [Account hosted-creator authority contract](../account-service/api-contracts.md#account-owned-hosted-terms-and-creator-party). + +The target publication operation must retain the exact selected-Draft binding and keep its Account authorization and World freeze identity bound to the same stable workflow/request. Allocated artifact/release identity, participant evidence, and the final owner outcome are result evidence for that operation, not replacement caller-input digests; the selected existing Version remains part of the original input. Every attempt transition must CAS the expected status and monotonic attempt revision; only the still-current attempt owner may publish a terminal result. Failure cleanup must conditionally own the same nonterminal attempt and prove the target has not been won or published. Every transition must prevent a delayed finalizer from publishing after an immutable no-publication outcome is recorded. That outcome requires authenticated Game Design owner evidence for the exact operation and World fence; failed status, absent evidence, or timeout alone is never terminal. Same-identity exact retries read back the original selection and operation outcome; changed binding, stale attempt status/revision or contradictory release/Version readback fails closed. Focused proof must cover crashes before and after each commit/readback boundary, concurrent exact retries, changed selection, a losing failure cleanup racing a winning publisher, and a no-publication outcome racing a delayed finalizer. ### External artifact recovery The target publication boundary treats object-store export as a durable candidate operation: persist `STAGED` export intent before any write, retain a deterministic candidate manifest or incremental durable key evidence, make writes and deletes idempotent, and use a durable cleanup retry/outbox with exact object/readback verification. An ambiguous external result remains nonterminal and reconciliation-required until the candidate and release state are proven; it must not be reported as terminal `FAILED` merely because a storage call timed out. `version_asset_artifact` and the immutable release attestation remain the Game Design authorities; object-store listings alone cannot authorize publication or purge. -**Current implementation gap:** `AssetExportServiceImpl` writes directly to S3-compatible storage before the artifact row receives the exported manifest. If an asset or manifest write fails, `VersionPublishCommandServiceImpl` has no manifest to record or clean up; if later cleanup fails, it is only logged. `VersionPublishCommandServiceImpl` normally records terminal `FAILED` and returns the attempt snapshot for publication failures; `TemporalVersionPublishActivitiesImpl` catches only `PendingReconciliationException` and returns `PENDING`. A partial export before manifest persistence can therefore lack durable cleanup and failure evidence. The current direct-prefix implementation is not proof of the target `STAGED`/candidate/reconciliation contract described in [Asset Storage](./asset-storage.md). +**Current implementation boundary:** `AssetExportServiceImpl` selects owner-retained ordinary bytes, records and reads the durable candidate, then uses conditional immutable object puts and exact byte readback. Uncertain export outcomes remain PENDING for reconciliation; final publication readback is separate. A no-publication seal must exclude a delayed release finalizer, but it is not cancellation or deletion proof for an already-running private candidate put. Late private objects remain quarantine/cleanup work and cannot establish release reachability, abandonment or purge eligibility. The [Asset Storage owner contract](./asset-storage.md) and [publishing tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) retain the distinct current producer boundary and remaining gates. ## Local Development Notes diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 81c4233db9..8c59373d3f 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -66,7 +66,11 @@ Game Design owns the durable, creator-visible coordination record for every shar The synchronized Draft fence is also the lifecycle handoff into publication. Before collecting the World Management participant digest, reading the final release state, or committing `published_release_bundle` and `PUBLISHED` metadata, Game Design must obtain and retain the exact WMS owner-freeze acknowledgement, then complete or abort that same owner operation after reconciling its publication outcome. The canonical WMS operations, fields, phase transitions, exact replay/conflict behavior, and current implementation/proof boundary are defined in [World Management API Contracts](../world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state). This is one owner-local freeze protocol, not a distributed transaction: the freeze serializes WMS Draft writes, while Game Design remains the lifecycle and final-attestation authority. Focused proof must interleave a WMS mutation with freeze acquisition, publication, retry, abort, and lost-response reconciliation and prove that no post-freeze Draft row or digest can become part of a Published release. -**Current implementation gap:** World Management currently lacks the durable owner-local publication freeze and exact Game Design version-state epoch/fence enforcement required by this target contract. Its live handoff checks the authoritative remote Game Design `DRAFT` state before its own transaction, but that check does not prove that a WMS mutation cannot commit after publication; current status and evidence remain in [World Management Runtime and Data](../world-management-service/runtime-and-data.md#implementation-status). +The complete publication operation is distinct from the [publication digest read](#owner-to-owner-digest-authorization-and-tenant-identity). `game-design-publication-operation/v1` retains the complete original [Account publication authorization binding](../account-service/api-contracts.md#account-owned-publication-authorization-fence) together with the unchanged complete World published start-location/freeze evidence. The bindings must identify the same canonical tenant and Version, stable publish request, complete selected Draft input/digest and derived workflow; the World checkpoint retains its original expected Draft epoch. Publication advances Game Design's Version epoch separately and must not rewrite the frozen input to that later epoch. Later captures and allocated release/artifact results are evidence for this operation, not replacements for the original preallocation authorization input. + +Game Design returns definitive publication or no-publication only from immutable owner readback bound to that exact operation. A `NO_PUBLICATION` result requires a durable seal serialized with every authoritative finalizer and retry/reconciliation path; neither absent bundle rows, a `FAILED` attempt nor timeout is enough. The owner transaction commits the terminal receipt and corresponding attempt outcome together. A `PUBLISHED` result additionally binds the complete immutable bundle and its atomic Version/artifact consequences. Exact historical recovery preserves those bytes; changed operation evidence conflicts, and a stale failure cannot demote a committed release. A no-publication seal excludes delayed release finalization and new candidate admission, not physical cancellation or deletion of already in-flight private content-addressed puts; those objects remain non-authoritative quarantine/cleanup state under [Asset Storage](asset-storage.md). Account independently verifies both required publication-owner outcomes before settlement; an earlier Draft outcome cannot settle this later operation. + +**Current implementation gap:** World has durable owner-local freeze/capture storage, but its authenticated normal freeze/terminal producers and complete current authorization composition remain unavailable. A remote Game Design `DRAFT` preflight cannot replace the shared owner commit fence. The local Game Design terminal-operation component and isolated database definitions do not authenticate Account publication currentness or complete the World terminal handoff; current status and executed proof remain in the [Game Design tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) and [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). The Game Design Service tracks a derived `designSyncStatus` for each `(tenantId, versionId)`. It is `IN_SYNC` only when the durable commit record, every required owner result, and the synchronized commit fence agree on the exact commit and digest. The `PublishVersion` workflow must verify this state before starting durable publication. The coordinator may use the canonical durable workflow substrate and transactional outbox delivery where appropriate, but it must not claim cross-database atomicity or expose partial application as accepted Draft state. 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 eb9bce257c..7b6852fb34 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The unpublished #3029 integration adds V50's exact publication-operation retention, attempt revision CAS and immutable terminal seal beside the actual full-Version finalizer, reconciliation and failure paths. The original eight-input selected-Draft digest is reused unchanged; Account preallocation authorization and later World freeze/selector evidence remain separate. Four new PostgreSQL definitions exercise owner storage, atomic release/Version/artifact/attempt consequences, stale failure, rollback and no-publication exclusion of delayed publication. Their upstream authority is explicitly isolated; they are not authenticated current Account permission or a live five-owner release. Local combined validation and corrected-state PostgreSQL execution remain pending. Public publication, the World authenticated freeze/terminal delivery and Account both-owner settlement stay denied/open under the [canonical owner contract](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff-target-state). + The corrected #3029 candidate repairs two executed migration failures from [CI37477743875](https://github.com/benhook1013/FireMUD/actions/runs/37477743875): V42's reserved PL/pgSQL identifier and V49's rejection of the canonical decimal-string selector epoch. World also compares the retained full-release numeric epoch to that string without changing retained bytes, and uses the current room physical column. Local Core/Game Design/World/Game Session checks, schema generation, packaged builds and documentation validation pass; PostgreSQL cases still skip without Docker, so corrected-state runner execution remains required. The retained `AuthoredDraftPublishSelection.digest()` already binds all eight `PublishVersion` inputs and selected synchronized Draft evidence. The approved distinct publication-operation authorization and immutable no-publication readback must reuse that complete evidence where applicable while keeping preallocation inputs, later captures and allocated release/artifact results distinct. `publicationDigestRequest/v1` remains the narrower owner-read binding, not publication authorization. The release-carrier child #3029 of #3021 adds immutable full-Version bundle/v2 storage and independent readback of the complete protected World selector evidence, with V49 preserving all older bundle bytes and denying selector backfill. All five participant owners, their exact selected commit/digest/schema, complete artifact manifest and original Account/APPLIED bytes remain required. Publication retry/reconciliation and descriptor resolution consume the retained v2 evidence; later launch assembly reads the committed local release rather than calling World inside its snapshot. The separate version-2 release attestation binds the complete World evidence under its own domain while descriptor/v1 and retained attestation/v1 stay unchanged. Database definitions cover exact retry, concurrent duplicate insertion, changed fields, raw SQL substitution and retained-row preservation. Their component fixtures explicitly stipulate isolated upstream authority; local PostgreSQL execution is unavailable without Docker. The protected current publication actor/role/party/terms producer, authenticated freeze acknowledgement and terminal delivery, actual five-owner publication and live release remain open and denied. Original Draft COMMIT_ORDER cannot authorize a subsequent publication; a distinct Account-owned publication operation and exact current source participation are required. Production operative verification/terms/legal authority is a separate activation prerequisite, not assumed by the bounded isolated proof. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 7dc468b9e0..2331947679 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The current #3029 local candidate adds unwired Account V79 publication participation and the shared exact selected-Draft codec. The existing Game Design adapter preserves its original eight-input selection bytes/digest. Publication reservations and immutable publication/revocation orders share the existing source locks and WAITING journal; source changes cannot finish while any affected publication lacks its own authenticated terminal results. Earlier Draft outcomes cannot satisfy this predicate. Twelve new PostgreSQL definitions cover replay/restart, source races, rollback, direct-SQL guards and retained V78 history, but have not executed locally without Docker. The current authority producer, Game Design no-publication seal, both-owner terminal verification and settlement remain required; nothing here enables publication or creator authority. See [Account's publication authorization owner contract](../../architecture/microservices/account-service/api-contracts.md#account-owned-publication-authorization-fence). + Exact source `d87f9cc2d30e775ea1e0c31f98ddfc64ec28c5ec` [CI37458361299](https://github.com/benhook1013/FireMUD/actions/runs/37458361299) executes nineteen Draft authorization-fence PostgreSQL cases with eighteen passes, one failure and zero skips. Stable unresolved pagination fails because its plain-SQL timestamp cursor is bound as varchar; the correction explicitly casts the original timestamp/UUID cursor without changing ordering or original operation identity. A separate V78 creator-party retained-history fixture targets nonexistent reserved V77; it now migrates genuine V74 history through V78 and compares the complete Account and membership rows, with no party enrollment. Corrected Account check and boot JAR pass in the combined affected gate; all 488 Account integration definitions skip locally without Docker. Corrected PostgreSQL pagination and migration execution remain required. Existing Account proofs do not establish current creator-party/terms authorization or the four live Gameplay owner handoffs. The V78 individual creator-party candidate adds immutable Account-owned party-source rows with opaque exact policy/verification references, append-only tenant-party history, and an immutable fresh-association request/result journal. Its unregistered storage primitive compares the exact persisted fresh tenant and committed V64 creator qualification, serializes both fresh and retained-history writers on the canonical tenant row, and requires matching source/history/receipt readback. The deferred receipt guard rejects contradictory or additional history at the initial commit boundary; exact historical retries recover the original result after a later tombstone, while current initial-association reads deny later history. Two unit tests and ten PostgreSQL definitions cover canonical binding and value negatives, baseline preservation, strict no-mutation denials, exact readback/retry and changed-input conflicts, database-observed concurrent fresh requests and retained-history races, immutable guards, and deferred rollback. The corrected Account check, boot JAR, schema generation, formatting, analyzers and documentation gate passes in 2m18s: 1,083 matching unit cases are clean, including both new value tests; all 484 integration cases skip without local Docker, including the ten new definitions. Executed PostgreSQL migration, race and commit-guard proof remains required. Eight nullable database-read dereferences exposed by static analysis were corrected with explicit fail-closed readback rather than suppressions. Verified-party, policy and original creator qualification are explicitly stipulated fixtures: no verification writer, authenticated initiating-caller/Game Design producer composition, operative terms/acceptance source, commit-bound hosted currentness or activation is supplied. This is a necessary Gameplay prerequisite under [Account's hosted party contract](../../architecture/microservices/account-service/api-contracts.md#account-owned-hosted-terms-and-creator-party), not complete Unit 1B or authoring permission. The focused CI block runs the ten definitions once, captures raw XML after the earlier creator-bootstrap capture, and strictly requires every method without replacing earlier proof selectors. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index 99370a36a2..1b4138fcb1 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -10,6 +10,7 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFenceRepository; import net.firedevops.firemud.accountservice.tenantcreation.TenantCreationAuthorizationFenceRepository; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; @@ -280,6 +281,7 @@ public boolean requestSourceChange(SourceChange change) { } } new TenantCreationAuthorizationFenceRepository(dsl).revokeAffected(change.sources()); + new PublicationAuthorizationFenceRepository(dsl).revokeAffected(change.sources()); return allAffectedSettled(change.sources()); } @@ -622,7 +624,8 @@ private boolean allAffectedSettled(List sources) { return false; } } - return new TenantCreationAuthorizationFenceRepository(dsl).allAffectedSettled(sources); + return new TenantCreationAuthorizationFenceRepository(dsl).allAffectedSettled(sources) + && new PublicationAuthorizationFenceRepository(dsl).allAffectedSettled(sources); } private Settlement settlement(UUID operation, Ordering ordering) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authorpublication/PublicationAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authorpublication/PublicationAuthorizationFenceRepository.java new file mode 100644 index 0000000000..c6ccb3ae68 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authorpublication/PublicationAuthorizationFenceRepository.java @@ -0,0 +1,274 @@ +package net.firedevops.firemud.accountservice.authorpublication; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.ObjectMapper; + +/** + * Unwired publication participation in Account's existing source-change order. Callers + * authenticate, lock and revalidate the real authority sources in their writable owner transaction + * before reserving or ordering; this component neither captures nor authenticates them. Never + * retain this transaction across RPC. Reservation grants no permission. Draft/creation results + * cannot settle publication; every ordered operation remains unresolved until its own authenticated + * terminal contract and producer exist. + */ +public final class PublicationAuthorizationFenceRepository { + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal transaction collaborator.") + public PublicationAuthorizationFenceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + public enum Ordering { + RESERVED, + PUBLICATION_ORDER, + REVOKE_ORDER + } + + public record Snapshot( + Ordering ordering, byte[] binding, OffsetDateTime reservedAt, OffsetDateTime orderedAt) { + public Snapshot { + binding = binding.clone(); + } + + @Override + public byte[] binding() { + return binding.clone(); + } + } + + public Snapshot reserve(AccountPublicationAuthorizationBinding binding) { + requireTransaction(); + lockSources(binding.sources()); + Record existing = operation(binding.operationId()); + if (existing != null) { + return snapshot(requireExact(existing, binding)); + } + if (hasWaitingChange(binding.sources())) { + throw new IllegalStateException("Applicable authority source change is waiting"); + } + dsl.execute( + "INSERT INTO account_publication_authorization_fences" + + " (operation_id, tenant_id, publish_request_id, fence_id, actor_account_id, selection_json," + + " selection_digest, source_vector, binding, ordering)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?::jsonb, ?, 'RESERVED')", + binding.operationId(), + binding.tenantId(), + binding.publishRequestId(), + binding.fenceId(), + binding.input().actorAccountId(), + binding.input().selection().canonicalJson(), + binding.input().selection().digest(), + new ObjectMapper() + .writeValueAsString( + binding.sources().stream() + .map( + source -> + Map.of( + "key", + source.key(), + "evidence", + HexFormat.of().formatHex(source.canonicalBytes()))) + .toList()), + binding.canonicalBytes()); + for (SourceEvidence source : binding.sources()) { + dsl.execute( + "INSERT INTO account_publication_authorization_sources" + + " (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + binding.operationId(), + source.key(), + source.canonicalBytes()); + } + return snapshot(requireExact(operation(binding.operationId()), binding)); + } + + /** + * Revalidate actual locked source state first. An exact replay recovers order, not currentness. + */ + public Snapshot claimPublicationOrder(AccountPublicationAuthorizationBinding binding) { + requireTransaction(); + lockSources(binding.sources()); + Record row = requireExact(operation(binding.operationId()), binding); + Ordering order = Ordering.valueOf(row.get("ordering", String.class)); + if (order == Ordering.PUBLICATION_ORDER) { + return snapshot(row); + } + if (order == Ordering.REVOKE_ORDER || hasWaitingChange(binding.sources())) { + throw new IllegalStateException("Revocation precedes this publication"); + } + dsl.execute( + "UPDATE account_publication_authorization_fences" + + " SET ordering = 'PUBLICATION_ORDER', ordered_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND ordering = 'RESERVED'", + binding.operationId()); + return snapshot(requireExact(operation(binding.operationId()), binding)); + } + + public Snapshot read(AccountPublicationAuthorizationBinding binding) { + requireTransaction(); + return snapshot(requireExact(operation(binding.operationId()), binding)); + } + + /** Exact original evidence only. Absence is UNKNOWN, never definitive no-publication evidence. */ + public Optional readOriginalBinding(UUID operationId) { + requireTransaction(); + Record row = operation(operationId); + if (row == null) { + return Optional.empty(); + } + var binding = + AccountPublicationAuthorizationBinding.fromStored(row.get("binding", byte[].class)); + requireExact(row, binding); + return Optional.of(binding); + } + + /** Called by the existing source-change writer under its shared source locks. */ + public void revokeAffected(List sources) { + requireTransaction(); + lockSources(sources); + for (UUID id : affectedOperations(sources)) { + Record row = operation(id); + if (Ordering.RESERVED.name().equals(row.get("ordering", String.class))) { + dsl.execute( + "UPDATE account_publication_authorization_fences" + + " SET ordering = 'REVOKE_ORDER', ordered_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND ordering = 'RESERVED'", + id); + } + } + } + + /** + * No terminal shortcut exists: neither expiry, FAILED, nor Draft readback releases this order. + */ + public boolean allAffectedSettled(List sources) { + requireTransaction(); + lockSources(sources); + List affected = affectedOperations(sources); + for (UUID id : affected) { + operation(id); + } + return affected.isEmpty(); + } + + private List affectedOperations(List sources) { + return sources.stream() + .flatMap( + source -> + dsl + .fetch( + "SELECT operation_id FROM account_publication_authorization_sources WHERE source_key = ?", + source.key()) + .getValues("operation_id", UUID.class) + .stream()) + .distinct() + .sorted(Comparator.comparing(UUID::toString)) + .toList(); + } + + private void lockSources(List sources) { + for (String key : sources.stream().map(SourceEvidence::key).distinct().sorted().toList()) { + dsl.execute( + "INSERT INTO account_draft_authorization_source_locks (source_key)" + + " VALUES (?) ON CONFLICT DO NOTHING", + key); + dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks" + + " WHERE source_key = ? FOR UPDATE", + key); + } + } + + private boolean hasWaitingChange(List sources) { + return sources.stream() + .anyMatch( + source -> + !dsl.fetch( + "SELECT c.change_id FROM account_draft_authorization_source_changes c" + + " JOIN account_draft_authorization_changed_scopes s ON s.change_id = c.change_id" + + " WHERE s.source_key = ? AND c.status = 'WAITING'", + source.key()) + .isEmpty()); + } + + private Record operation(UUID id) { + return dsl.fetchOne( + "SELECT * FROM account_publication_authorization_fences" + + " WHERE operation_id = ? FOR UPDATE", + id); + } + + private Record requireExact(Record row, AccountPublicationAuthorizationBinding binding) { + if (row == null + || !binding.operationId().equals(row.get("operation_id", UUID.class)) + || !binding.tenantId().equals(row.get("tenant_id", UUID.class)) + || !binding.publishRequestId().equals(row.get("publish_request_id", String.class)) + || !binding.fenceId().equals(row.get("fence_id", UUID.class)) + || !Arrays.equals(binding.canonicalBytes(), row.get("binding", byte[].class))) { + throw new IllegalArgumentException("Absent or changed immutable publication operation"); + } + List stored = + dsl + .fetch( + "SELECT source_key, source_evidence" + + " FROM account_publication_authorization_sources WHERE operation_id = ?", + binding.operationId()) + .stream() + .sorted(Comparator.comparing(source -> source.get("source_key", String.class))) + .toList(); + if (stored.size() != binding.sources().size()) { + throw new IllegalStateException("Incomplete publication source participation"); + } + for (int i = 0; i < stored.size(); i++) { + SourceEvidence source = binding.sources().get(i); + if (!source.key().equals(stored.get(i).get("source_key", String.class)) + || !Arrays.equals( + source.canonicalBytes(), stored.get(i).get("source_evidence", byte[].class))) { + throw new IllegalStateException( + "Publication source participation differs from original capture"); + } + } + return row; + } + + private Snapshot snapshot(Record row) { + return new Snapshot( + Ordering.valueOf(row.get("ordering", String.class)), + row.get("binding", byte[].class), + row.get("reserved_at", OffsetDateTime.class), + row.get("ordered_at", OffsetDateTime.class)); + } + + private void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable caller Account transaction required"); + } + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Transaction-bound writable READ_COMMITTED connection required"); + } + }); + } +} diff --git a/services/account-service/src/main/resources/db/migration/V79__publication_authorization_participation.sql b/services/account-service/src/main/resources/db/migration/V79__publication_authorization_participation.sql new file mode 100644 index 0000000000..f15761d9cb --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V79__publication_authorization_participation.sql @@ -0,0 +1,220 @@ +-- Unwired publication source participation only. No operative legal authority or terminal +-- producer is manufactured. Every affected publication remains unresolved and source-blocking. +CREATE TABLE account_publication_authorization_fences ( + operation_id UUID PRIMARY KEY CHECK (operation_id <> '00000000-0000-0000-0000-000000000000'), + tenant_id UUID NOT NULL CHECK (tenant_id <> '00000000-0000-0000-0000-000000000000'), + publish_request_id VARCHAR(256) NOT NULL CHECK (octet_length(publish_request_id) BETWEEN 1 AND 256), + fence_id UUID NOT NULL UNIQUE CHECK (fence_id <> '00000000-0000-0000-0000-000000000000'), + actor_account_id UUID NOT NULL CHECK (actor_account_id <> '00000000-0000-0000-0000-000000000000'), + selection_json TEXT NOT NULL, + selection_digest VARCHAR(71) NOT NULL CHECK (selection_digest ~ '^sha256:[0-9a-f]{64}$'), + source_vector JSONB NOT NULL, + binding BYTEA NOT NULL, + ordering VARCHAR(24) NOT NULL CHECK (ordering IN ('RESERVED', 'PUBLICATION_ORDER', 'REVOKE_ORDER')), + reserved_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + ordered_at TIMESTAMPTZ, + UNIQUE (tenant_id, publish_request_id), + CHECK ((ordering = 'RESERVED') = (ordered_at IS NULL)) +); + +CREATE TABLE account_publication_authorization_sources ( + operation_id UUID NOT NULL REFERENCES account_publication_authorization_fences(operation_id), + source_key VARCHAR(2048) NOT NULL REFERENCES account_draft_authorization_source_locks(source_key), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) > 0), + PRIMARY KEY (operation_id, source_key) +); +CREATE INDEX account_publication_authorization_sources_by_scope + ON account_publication_authorization_sources(source_key, operation_id); + +-- [jooq ignore start] +ALTER TABLE account_publication_authorization_fences + ADD CONSTRAINT account_publication_authorization_nonempty_sources + CHECK (jsonb_typeof(source_vector) = 'array' AND jsonb_array_length(source_vector) > 0); + +-- PostgreSQL's UTF-8 collation need not equal Java String ordering for supplementary code points. +-- The existing owner sorts shared lock keys by UTF-16 code units; preserve that exact order in SQL. +CREATE FUNCTION account_publication_authorization_source_sort_key(value TEXT) +RETURNS INTEGER[] LANGUAGE plpgsql IMMUTABLE STRICT AS $$ +DECLARE + units INTEGER[] := ARRAY[]::INTEGER[]; + codepoint INTEGER; + character_index INTEGER; +BEGIN + FOR character_index IN 1..char_length(value) LOOP + codepoint := ascii(substring(value FROM character_index FOR 1)); + IF codepoint > 65535 THEN + units := array_append(units, 55296 + ((codepoint - 65536) / 1024)); + units := array_append(units, 56320 + ((codepoint - 65536) % 1024)); + ELSE + units := array_append(units, codepoint); + END IF; + END LOOP; + RETURN units; +END; +$$; + +CREATE FUNCTION account_publication_authorization_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + source JSONB; + source_bytes BYTEA; + source_prefix BYTEA; + input_bytes BYTEA; + expected_binding BYTEA; + selection JSONB; + keys TEXT[] := ARRAY[]::TEXT[]; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Publication authorization cannot be deleted' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'UPDATE' THEN + IF OLD.ordering <> 'RESERVED' + OR NEW.ordering NOT IN ('PUBLICATION_ORDER', 'REVOKE_ORDER') OR NEW.ordered_at IS NULL + OR (to_jsonb(NEW) - ARRAY['ordering','ordered_at']) IS DISTINCT FROM + (to_jsonb(OLD) - ARRAY['ordering','ordered_at']) THEN + RAISE EXCEPTION 'Publication identity, capture and finalized order are immutable' + USING ERRCODE = '23514'; + END IF; + ELSIF NEW.ordering <> 'RESERVED' OR NEW.ordered_at IS NOT NULL THEN + RAISE EXCEPTION 'Publication must begin reserved' USING ERRCODE = '23514'; + END IF; + selection := NEW.selection_json::JSONB; + IF NEW.selection_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(convert_to(NEW.selection_json, 'UTF8')), 'hex') + OR selection->>'schemaVersion' IS DISTINCT FROM '1' + OR selection->'intent'->>'canonicalTenantId' IS DISTINCT FROM NEW.tenant_id::TEXT + OR selection->'intent'->>'publishRequestId' IS DISTINCT FROM NEW.publish_request_id THEN + RAISE EXCEPTION 'Publication requires the exact original selection digest and request scope' + USING ERRCODE = '23514'; + END IF; + input_bytes := account_tenant_creation_authorization_frame(convert_to('account-publication-input/v1', 'UTF8')) + || account_tenant_creation_authorization_frame(convert_to(NEW.actor_account_id::TEXT, 'UTF8')) + || account_tenant_creation_authorization_frame(convert_to(NEW.selection_json, 'UTF8')) + || account_tenant_creation_authorization_frame(convert_to(NEW.selection_digest, 'UTF8')); + expected_binding := account_tenant_creation_authorization_frame(convert_to('account-publication-authorization/v1', 'UTF8')) + || account_tenant_creation_authorization_frame(convert_to(NEW.operation_id::TEXT, 'UTF8')) + || account_tenant_creation_authorization_frame(convert_to(NEW.fence_id::TEXT, 'UTF8')) + || account_tenant_creation_authorization_frame(input_bytes) + || account_tenant_creation_authorization_frame(convert_to(jsonb_array_length(NEW.source_vector)::TEXT, 'UTF8')); + FOR source IN SELECT value FROM jsonb_array_elements(NEW.source_vector) LOOP + IF jsonb_typeof(source) <> 'object' OR (SELECT count(*) FROM jsonb_object_keys(source)) <> 2 + OR jsonb_typeof(source->'key') IS DISTINCT FROM 'string' + OR jsonb_typeof(source->'evidence') IS DISTINCT FROM 'string' + OR source->>'key' = ANY(keys) OR source->>'evidence' !~ '^([0-9a-f]{2})+$' + OR position(':' IN source->>'key') < 2 THEN + RAISE EXCEPTION 'Exact distinct publication source vector required' USING ERRCODE = '23514'; + END IF; + keys := array_append(keys, source->>'key'); + source_bytes := decode(source->>'evidence', 'hex'); + source_prefix := account_tenant_creation_authorization_frame(convert_to('account-draft-source-evidence/v1', 'UTF8')) + || account_tenant_creation_authorization_frame(convert_to(split_part(source->>'key', ':', 1), 'UTF8')) + || account_tenant_creation_authorization_frame(convert_to(substring(source->>'key' FROM position(':' IN source->>'key') + 1), 'UTF8')); + IF substring(source_bytes FROM 1 FOR octet_length(source_prefix)) IS DISTINCT FROM source_prefix THEN + RAISE EXCEPTION 'Publication source key must bind its original source evidence' USING ERRCODE = '23514'; + END IF; + expected_binding := expected_binding || account_tenant_creation_authorization_frame(source_bytes); + END LOOP; + IF NEW.binding IS DISTINCT FROM expected_binding THEN + RAISE EXCEPTION 'Publication columns must bind the complete original operation bytes' USING ERRCODE = '23514'; + END IF; + IF keys IS DISTINCT FROM (SELECT array_agg(key ORDER BY account_publication_authorization_source_sort_key(key)) + FROM unnest(keys) key) THEN + RAISE EXCEPTION 'Publication sources must retain canonical shared lock order' USING ERRCODE = '23514'; + END IF; + -- The vector is retained in the owner's canonical sorted order. Use that same order for locks. + FOR source IN SELECT value FROM jsonb_array_elements(NEW.source_vector) LOOP + INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (source->>'key') ON CONFLICT DO NOTHING; + PERFORM source_key FROM account_draft_authorization_source_locks WHERE source_key = source->>'key' FOR UPDATE; + END LOOP; + IF (TG_OP = 'INSERT' OR NEW.ordering = 'PUBLICATION_ORDER') AND EXISTS ( + SELECT 1 FROM account_draft_authorization_changed_scopes changed + JOIN account_draft_authorization_source_changes change USING (change_id) + WHERE changed.source_key = ANY(keys) AND change.status = 'WAITING' + ) THEN + RAISE EXCEPTION 'Waiting source change precedes publication' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_publication_authorization_source_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + fence account_publication_authorization_fences%ROWTYPE; +BEGIN + SELECT * INTO fence FROM account_publication_authorization_fences + WHERE operation_id = NEW.operation_id FOR UPDATE; + IF fence.ordering IS DISTINCT FROM 'RESERVED' OR NOT EXISTS ( + SELECT 1 FROM jsonb_array_elements(fence.source_vector) source + WHERE source->>'key' = NEW.source_key + AND decode(source->>'evidence', 'hex') = NEW.source_evidence + ) THEN + RAISE EXCEPTION 'Publication source must match the original reserved operation' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_publication_authorization_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original_vector JSONB; + operation UUID := NEW.operation_id; +BEGIN + SELECT source_vector INTO original_vector FROM account_publication_authorization_fences + WHERE operation_id = operation; + IF (SELECT count(*) FROM account_publication_authorization_sources WHERE operation_id = operation) + <> jsonb_array_length(original_vector) THEN + RAISE EXCEPTION 'Complete immutable publication source participation required' USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_publication_authorization_source_transition_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + key TEXT; +BEGIN + -- Also serialize direct SQL terminal attempts with reservation/order, using the same existing + -- source participation rows and exact Java key order, before inspecting affected publication. + FOR key IN SELECT source_key FROM account_draft_authorization_changed_scopes + WHERE change_id = OLD.change_id ORDER BY account_publication_authorization_source_sort_key(source_key) LOOP + PERFORM source_key FROM account_draft_authorization_source_locks WHERE source_key = key FOR UPDATE; + END LOOP; + -- Deliberately no terminal-result path. Draft/creation outcomes, expiry, absence or FAILED + -- cannot prove definitive publication settlement. Both commit and source abort stay WAITING. + IF EXISTS ( + SELECT 1 FROM account_draft_authorization_changed_scopes changed + JOIN account_publication_authorization_sources source USING (source_key) + WHERE changed.change_id = OLD.change_id + ) THEN + RAISE EXCEPTION 'Publication-specific authenticated terminal evidence is unavailable' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_publication_authorization_fence_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_publication_authorization_fences + FOR EACH ROW EXECUTE FUNCTION account_publication_authorization_guard(); +CREATE TRIGGER account_publication_authorization_sources_insert_guard + BEFORE INSERT ON account_publication_authorization_sources + FOR EACH ROW EXECUTE FUNCTION account_publication_authorization_source_guard(); +CREATE TRIGGER account_publication_authorization_sources_immutable + BEFORE UPDATE OR DELETE ON account_publication_authorization_sources + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE CONSTRAINT TRIGGER account_publication_authorization_complete + AFTER INSERT OR UPDATE ON account_publication_authorization_fences + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_publication_authorization_complete_guard(); +CREATE TRIGGER account_publication_authorization_fences_no_truncate + BEFORE TRUNCATE ON account_publication_authorization_fences + FOR EACH STATEMENT EXECUTE FUNCTION account_tenant_creation_authorization_no_truncate(); +CREATE TRIGGER account_publication_authorization_sources_no_truncate + BEFORE TRUNCATE ON account_publication_authorization_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_tenant_creation_authorization_no_truncate(); +CREATE TRIGGER account_publication_authorization_source_transition + BEFORE UPDATE ON account_draft_authorization_source_changes + FOR EACH ROW EXECUTE FUNCTION account_publication_authorization_source_transition_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authorpublication/PublicationAuthorizationFencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authorpublication/PublicationAuthorizationFencePostgresIntegrationTest.java new file mode 100644 index 0000000000..0f904bf888 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authorpublication/PublicationAuthorizationFencePostgresIntegrationTest.java @@ -0,0 +1,633 @@ +package integration.net.firedevops.firemud.accountservice.authorpublication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChangeAbortReason; +import net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFenceRepository.Ordering; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Isolated component fixtures stipulate original authenticated synchronized selection and current + * Account capture. They prove no operative legal terms, source-verification product, RPC or live + * publication. No publication terminal fixture exists because that contract/producer is absent. + */ +@Testcontainers(disabledWithoutDocker = true) +class PublicationAuthorizationFencePostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void exactReserveOrderAndRestartReadbackPreserveOriginalBytes() { + Context context = context(); + var binding = binding(); + assertThat(tx(context, () -> context.publication().reserve(binding)).ordering()) + .isEqualTo(Ordering.RESERVED); + assertThat(tx(context, () -> context.publication().reserve(binding)).binding()) + .isEqualTo(binding.canonicalBytes()); + assertThat(tx(context, () -> context.publication().claimPublicationOrder(binding)).ordering()) + .isEqualTo(Ordering.PUBLICATION_ORDER); + var restarted = new PublicationAuthorizationFenceRepository(context.dsl()); + assertThat(tx(context, () -> restarted.readOriginalBinding(binding.operationId()))) + .get() + .satisfies( + original -> assertThat(original.canonicalBytes()).isEqualTo(binding.canonicalBytes())); + assertThat(tx(context, () -> restarted.claimPublicationOrder(binding)).binding()) + .isEqualTo(binding.canonicalBytes()); + assertThat(tx(context, () -> restarted.readOriginalBinding(UUID.randomUUID()))).isEmpty(); + } + + @Test + void changedRequestCaptureActorOrAllocatedIdentityCannotReplaceOriginal() { + Context context = context(); + var original = binding(); + tx(context, () -> context.publication().reserve(original)); + var changedSource = + new SourceEvidence( + SourceKind.ACCOUNT, + original.input().actorAccountId().toString(), + "4", + "5", + null, + null, + new byte[] {8}); + var recaptured = + new AccountPublicationAuthorizationBinding( + original.operationId(), original.fenceId(), original.input(), List.of(changedSource)); + assertThatThrownBy(() -> tx(context, () -> context.publication().reserve(recaptured))) + .isInstanceOf(IllegalArgumentException.class); + var reallocated = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), UUID.randomUUID(), original.input(), original.sources()); + assertThatThrownBy(() -> tx(context, () -> context.publication().reserve(reallocated))) + .isInstanceOf(DataAccessException.class); + var changedIntent = + new AccountPublicationAuthorizationBinding( + original.operationId(), + original.fenceId(), + new AccountPublicationAuthorizationBinding.PreallocationInput( + original.input().actorAccountId(), selection("changed")), + original.sources()); + assertThatThrownBy(() -> tx(context, () -> context.publication().read(changedIntent))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(tx(context, () -> context.publication().read(original)).binding()) + .isEqualTo(original.canonicalBytes()); + } + + @Test + void sourceChangeRevokesReservedPublicationButCannotCommitOrAbortWithoutItsOwnTerminalContract() { + Context context = context(); + var binding = binding(); + tx(context, () -> context.publication().reserve(binding)); + var change = change(binding); + assertThat(tx(context, () -> context.draft().requestSourceChange(change))).isFalse(); + assertThat(tx(context, () -> context.publication().read(binding)).ordering()) + .isEqualTo(Ordering.REVOKE_ORDER); + assertThatThrownBy( + () -> tx(context, () -> context.publication().claimPublicationOrder(binding))) + .isInstanceOf(IllegalStateException.class); + assertThat(tx(context, () -> context.draft().sourceMutationPermitted(change))).isFalse(); + assertThat(tx(context, () -> context.draft().sourceAbortPermitted(change))).isFalse(); + assertThatThrownBy( + () -> + tx( + context, + () -> { + context.draft().markSourceAborted(change, SourceChangeAbortReason.EXPIRED); + return null; + })) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_draft_authorization_source_changes SET status='SOURCE_COMMITTED'," + + " committed_at=CURRENT_TIMESTAMP WHERE change_id=?", + change.changeId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_draft_authorization_source_changes SET status='SOURCE_ABORTED'," + + " aborted_at=CURRENT_TIMESTAMP, abort_reason='EXPIRED' WHERE change_id=?", + change.changeId()))) + .isInstanceOf(DataAccessException.class); + assertThat(tx(context, () -> context.draft().readSourceChange(change)).status()) + .isEqualTo("WAITING"); + } + + @Test + void publicationOrderRemainsUnresolvedAfterOriginalDraftTerminalResults() { + Context context = context(); + var publication = binding(); + tx(context, () -> context.publication().reserve(publication)); + tx(context, () -> context.publication().claimPublicationOrder(publication)); + var commit = publication.input().selection().selectedCommit(); + var draft = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + commit.requestId(), + commit.commitId(), + UUID.randomUUID(), + publication.input().actorAccountId(), + publication.tenantId(), + commit.target().canonicalVersionId(), + commit.baseCommitId(), + "1", + commit.canonicalBytes(), + commit.canonicalBytes(), + commit.digest(), + publication.sources()); + tx( + context, + () -> { + context.draft().reserve(draft); + context.draft().claimCommitOrder(draft); + for (var owner : DraftAuthorizationFenceBinding.Owner.values()) { + context + .draft() + .recordOwnerReadback( + draft, + new DraftAuthorizationFenceBinding.OwnerReadback( + owner, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + draft.operationId(), + draft.commitId(), + draft.fenceId(), + draft.inputDigest(), + draft.canonicalBytes(), + new byte[] {1})); + } + return null; + }); + var change = change(publication); + assertThat(tx(context, () -> context.draft().requestSourceChange(change))).isFalse(); + assertThat(tx(context, () -> context.publication().read(publication)).ordering()) + .isEqualTo(Ordering.PUBLICATION_ORDER); + assertThat(tx(context, () -> context.draft().sourceMutationPermitted(change))).isFalse(); + assertThatThrownBy( + () -> + tx( + context, + () -> { + context.draft().markSourceCommitted(change); + return null; + })) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void waitingChangeDeniesNewReservationAndUnrelatedScopeStillProceeds() { + Context context = context(); + var binding = binding(); + var change = change(binding); + assertThat(tx(context, () -> context.draft().requestSourceChange(change))).isTrue(); + assertThatThrownBy(() -> tx(context, () -> context.publication().reserve(binding))) + .isInstanceOf(IllegalStateException.class); + var independentInput = + new AccountPublicationAuthorizationBinding.PreallocationInput( + UUID.randomUUID(), selection("notes")); + var unrelated = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + independentInput, + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + independentInput.actorAccountId().toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + assertThat(tx(context, () -> context.publication().reserve(unrelated)).ordering()) + .isEqualTo(Ordering.RESERVED); + } + + @Test + void concurrentPublicationClaimAndSourceChangeChooseOneDurableOrder() throws Exception { + Context context = context(); + var binding = binding(); + tx(context, () -> context.publication().reserve(binding)); + var change = change(binding); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + try (var executor = Executors.newFixedThreadPool(2)) { + var claim = + executor.submit( + () -> { + ready.countDown(); + await(start); + try { + return tx(context, () -> context.publication().claimPublicationOrder(binding)) + .ordering(); + } catch (IllegalStateException revoked) { + return Ordering.REVOKE_ORDER; + } + }); + var source = + executor.submit( + () -> { + ready.countDown(); + await(start); + return tx(context, () -> context.draft().requestSourceChange(change)); + }); + await(ready); + start.countDown(); + Ordering winner = claim.get(10, TimeUnit.SECONDS); + assertThat(source.get(10, TimeUnit.SECONDS)).isFalse(); + assertThat(tx(context, () -> context.publication().read(binding)).ordering()) + .isEqualTo(winner); + assertThat(tx(context, () -> context.draft().readSourceChange(change)).status()) + .isEqualTo("WAITING"); + assertThat(tx(context, () -> context.draft().sourceMutationPermitted(change))).isFalse(); + } + } + + @Test + void rawSqlCannotReplaceOriginalSourceBindingOrOrderOrTruncateEvidence() { + Context context = context(); + var binding = binding(); + tx(context, () -> context.publication().reserve(binding)); + for (String sql : + List.of( + "UPDATE account_publication_authorization_sources SET source_evidence=decode('01','hex') WHERE operation_id=?", + "DELETE FROM account_publication_authorization_sources WHERE operation_id=?", + "UPDATE account_publication_authorization_fences SET binding=decode('01','hex') WHERE operation_id=?", + "DELETE FROM account_publication_authorization_fences WHERE operation_id=?")) { + assertThatThrownBy(() -> tx(context, () -> context.dsl().execute(sql, binding.operationId()))) + .isInstanceOf(DataAccessException.class); + } + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "TRUNCATE account_publication_authorization_fences, account_publication_authorization_sources"))) + .isInstanceOf(DataAccessException.class); + tx(context, () -> context.publication().claimPublicationOrder(binding)); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_publication_authorization_fences SET ordering='REVOKE_ORDER'," + + " ordered_at=CURRENT_TIMESTAMP WHERE operation_id=?", + binding.operationId()))) + .isInstanceOf(DataAccessException.class); + } + + @Test + void failedOwnerTransactionRollsBackReservationAndParticipation() { + Context context = context(); + var binding = binding(); + assertThatThrownBy( + () -> + tx( + context, + () -> { + context.publication().reserve(binding); + throw new IllegalStateException("fixture rollback"); + })) + .isInstanceOf(IllegalStateException.class); + assertThat(tx(context, () -> context.publication().readOriginalBinding(binding.operationId()))) + .isEmpty(); + assertThat(context.dsl().fetchCount(DSL.table("account_publication_authorization_sources"))) + .isZero(); + } + + @Test + void concurrentExactReservationReturnsOneImmutableOperation() throws Exception { + Context context = context(); + var binding = binding(); + CountDownLatch start = new CountDownLatch(1); + try (var executor = Executors.newFixedThreadPool(2)) { + var first = + executor.submit( + () -> { + await(start); + return tx(context, () -> context.publication().reserve(binding)).binding(); + }); + var second = + executor.submit( + () -> { + await(start); + return tx(context, () -> context.publication().reserve(binding)).binding(); + }); + start.countDown(); + assertThat(first.get(10, TimeUnit.SECONDS)).isEqualTo(binding.canonicalBytes()); + assertThat(second.get(10, TimeUnit.SECONDS)).isEqualTo(binding.canonicalBytes()); + assertThat(context.dsl().fetchCount(DSL.table("account_publication_authorization_fences"))) + .isEqualTo(1); + } + } + + @Test + void rawSqlCannotReserveIncompleteSourceParticipationOrSubstituteRequestIdentity() { + Context context = context(); + var binding = binding(); + String vector = + new tools.jackson.databind.ObjectMapper() + .writeValueAsString( + binding.sources().stream() + .map( + source -> + Map.of( + "key", + source.key(), + "evidence", + java.util.HexFormat.of().formatHex(source.canonicalBytes()))) + .toList()); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "INSERT INTO account_publication_authorization_fences" + + " (operation_id, tenant_id, publish_request_id, fence_id, actor_account_id," + + " selection_json, selection_digest, source_vector, binding, ordering)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?::jsonb, ?, 'RESERVED')", + binding.operationId(), + binding.tenantId(), + binding.publishRequestId(), + binding.fenceId(), + binding.input().actorAccountId(), + binding.input().selection().canonicalJson(), + binding.input().selection().digest(), + vector, + binding.canonicalBytes()))) + .isInstanceOf(RuntimeException.class) + .hasStackTraceContaining("Complete immutable publication source participation required"); + assertThat(tx(context, () -> context.publication().readOriginalBinding(binding.operationId()))) + .isEmpty(); + tx(context, () -> context.publication().reserve(binding)); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "INSERT INTO account_publication_authorization_fences" + + " SELECT ?::uuid, tenant_id, 'substituted-request', ?::uuid, actor_account_id," + + " selection_json, selection_digest, source_vector, binding, ordering, reserved_at, ordered_at" + + " FROM account_publication_authorization_fences WHERE operation_id=?", + UUID.randomUUID(), + UUID.randomUUID(), + binding.operationId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "INSERT INTO account_publication_authorization_sources VALUES (?, ?, decode('01', 'hex'))", + binding.operationId(), + binding.sources().getFirst().key()))) + .isInstanceOf(DataAccessException.class); + } + + @Test + void sqlPreservesJavaSourceLockOrderingForSupplementaryUnicodeScopes() { + Context context = context(); + var original = binding(); + var binding = + new AccountPublicationAuthorizationBinding( + original.operationId(), + original.fenceId(), + original.input(), + List.of( + new SourceEvidence( + SourceKind.ISSUER, "issuer-\uE000", "1", "1", null, null, new byte[] {1}), + new SourceEvidence( + SourceKind.ISSUER, "issuer-\uD800\uDC00", "1", "1", null, null, new byte[] {2}), + original.sources().getFirst())); + assertThat(tx(context, () -> context.publication().reserve(binding)).binding()) + .isEqualTo(binding.canonicalBytes()); + assertThat(tx(context, () -> context.publication().claimPublicationOrder(binding)).ordering()) + .isEqualTo(Ordering.PUBLICATION_ORDER); + assertThat(tx(context, () -> context.draft().requestSourceChange(change(binding)))).isFalse(); + } + + @Test + void missingCurrentSchemaFailsClosedAndUpgradePreservesOriginalDraftEvidence() { + Context context = context("78"); + var publication = binding(); + var commit = publication.input().selection().selectedCommit(); + var draft = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + commit.requestId(), + commit.commitId(), + UUID.randomUUID(), + publication.input().actorAccountId(), + publication.tenantId(), + commit.target().canonicalVersionId(), + commit.baseCommitId(), + "1", + commit.canonicalBytes(), + commit.canonicalBytes(), + commit.digest(), + publication.sources()); + tx(context, () -> context.draft().reserve(draft)); + var before = tx(context, () -> context.draft().read(draft)); + assertThatThrownBy( + () -> tx(context, () -> context.draft().requestSourceChange(change(publication)))) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("account_publication_authorization_sources"); + assertThat(tx(context, () -> context.draft().read(draft)).ordering()) + .isEqualTo(before.ordering()); + migrate(context.source(), "latest"); + var after = tx(context, () -> context.draft().read(draft)); + assertThat(after.binding()).isEqualTo(before.binding()); + assertThat(after.ordering()).isEqualTo(before.ordering()); + assertThat(after.reservedAt()).isEqualTo(before.reservedAt()); + assertThat(after.orderedAt()).isEqualTo(before.orderedAt()); + assertThat(context.dsl().fetchCount(DSL.table("account_publication_authorization_fences"))) + .isZero(); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) + .isZero(); + } + + private static AccountPublicationAuthorizationBinding binding() { + var input = + new AccountPublicationAuthorizationBinding.PreallocationInput( + UUID.randomUUID(), selection("notes")); + return new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + input, + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + input.actorAccountId().toString(), + "3", + "4", + null, + null, + new byte[] {7}))); + } + + private static SourceChange change(AccountPublicationAuthorizationBinding binding) { + return new SourceChange(UUID.randomUUID(), binding.sources(), new byte[] {9}); + } + + private Context context() { + return context("latest"); + } + + private Context context(String target) { + String schema = "publication_fence_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + migrate(source, target); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return new Context( + dsl, + new PublicationAuthorizationFenceRepository(dsl), + new DraftAuthorizationFenceRepository(dsl), + transaction, + source); + } + + private static void migrate(DriverManagerDataSource source, String target) { + String schema = source.getSchema(); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(target) + .load() + .migrate(); + } + + private static T tx(Context context, Supplier work) { + return context.transaction().execute(status -> work.get()); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) throw new IllegalStateException("fixture timeout"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + } + + private record Context( + DSLContext dsl, + PublicationAuthorizationFenceRepository publication, + DraftAuthorizationFenceRepository draft, + TransactionTemplate transaction, + DriverManagerDataSource source) {} + + private static AuthoredDraftPublishSelectionBinding selection(String notes) { + var target = + new DraftCommitBinding.TargetProof( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 9007199254740993L, + "tenant-source", + 9007199254740995L, + "tenant-source", + "NEW_GAME_ROW"); + var commit = + DraftCommitBinding.create( + target, + UUID.fromString("33333333-3333-4333-8333-333333333333"), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.fromString("55555555-5555-4555-8555-555555555555"), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "{\"mutation\":\"fixture\"}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world", + "ROOM_SCOPE", + "room", + "900719925474099312345"))); + return AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + "publication-é", + "900719925474099312345", + notes, + commit.requestId(), + commit.commitId(), + commit.digest()), + target, + commit, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + commit.requestId(), + commit.commitId(), + commit.digest(), + "[]", + OffsetDateTime.parse("2026-10-05T00:00:00Z"))); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authorpublication/PublicationAuthorizationFenceRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authorpublication/PublicationAuthorizationFenceRepositoryTest.java new file mode 100644 index 0000000000..602be9b678 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authorpublication/PublicationAuthorizationFenceRepositoryTest.java @@ -0,0 +1,47 @@ +package unit.net.firedevops.firemud.accountservice.authorpublication; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFenceRepository; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class PublicationAuthorizationFenceRepositoryTest { + @Test + void allEntryPointsDenyOutsideWritableOwnerTransactionBeforePersistence() { + DSLContext dsl = mock(DSLContext.class); + var repository = new PublicationAuthorizationFenceRepository(dsl); + assertThatThrownBy(() -> repository.reserve(null)).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> repository.claimPublicationOrder(null)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> repository.read(null)).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> repository.readOriginalBinding(UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> repository.revokeAffected(List.of())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> repository.allAffectedSettled(List.of())) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(dsl); + } + + @Test + void readOnlyOwnerTransactionCannotReserveOrReleaseSourceParticipation() { + DSLContext dsl = mock(DSLContext.class); + var repository = new PublicationAuthorizationFenceRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + try { + assertThatThrownBy(() -> repository.reserve(null)).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> repository.allAffectedSettled(List.of())) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(dsl); + } finally { + TransactionSynchronizationManager.clear(); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBinding.java new file mode 100644 index 0000000000..8d4257ef55 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBinding.java @@ -0,0 +1,150 @@ +package net.firedevops.firemud.common.publication; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.FrameReader; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; + +/** + * Distinct publication operation's immutable original input and Account source participation. This + * validates complete selected Draft structure, not actor authentication or positive source + * authority. The future Account producer must independently establish the complete current source + * vector, including party and operative hosted terms. Draft COMMIT_ORDER and creation results never + * authorize or settle this operation. Later World captures and release/artifact results remain + * separate and must never rewrite the original selection digest. + */ +public record AccountPublicationAuthorizationBinding( + UUID operationId, UUID fenceId, PreallocationInput input, List sources) { + public static final String SCHEMA = "account-publication-authorization/v1"; + + public AccountPublicationAuthorizationBinding { + DraftAuthorizationFenceBinding.requireUuid(operationId); + DraftAuthorizationFenceBinding.requireUuid(fenceId); + Objects.requireNonNull(input); + sources = + List.copyOf(Objects.requireNonNull(sources)).stream() + .sorted(Comparator.comparing(SourceEvidence::key)) + .toList(); + if (sources.isEmpty() + || sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) { + throw new IllegalArgumentException("Distinct applicable publication sources required"); + } + for (SourceEvidence source : sources) { + String requiredScope = + switch (source.kind()) { + case ACCOUNT, GLOBAL_ROLES -> input.actorAccountId().toString(); + case TENANT -> input.selection().intent().canonicalTenantId().toString(); + case MEMBERSHIP -> + input.actorAccountId() + "/" + input.selection().intent().canonicalTenantId(); + default -> null; + }; + if (requiredScope != null && !requiredScope.equals(source.scopeId())) { + throw new IllegalArgumentException( + "Publication source differs from exact actor/tenant scope"); + } + } + } + + /** Stable caller/selection inputs, before any Account operation/fence or World allocation. */ + public record PreallocationInput( + UUID actorAccountId, AuthoredDraftPublishSelectionBinding selection) { + public PreallocationInput { + DraftAuthorizationFenceBinding.requireUuid(actorAccountId); + Objects.requireNonNull(selection); + // Reconstruct the whole closed selection, including target, commit and synchronized fence. + selection = + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()); + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "account-publication-input/v1"); + DraftAuthorizationFenceBinding.frame(out, actorAccountId.toString()); + DraftAuthorizationFenceBinding.frame(out, selection.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, selection.digest()); + return out.toByteArray(); + } + + public String digest() { + return DraftAuthorizationFenceBinding.digest(canonicalBytes()); + } + } + + public UUID tenantId() { + return input.selection().intent().canonicalTenantId(); + } + + public String publishRequestId() { + return input.selection().intent().publishRequestId(); + } + + @Override + public List sources() { + return List.copyOf(sources); + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, operationId.toString()); + DraftAuthorizationFenceBinding.frame(out, fenceId.toString()); + DraftAuthorizationFenceBinding.frame(out, input.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, Integer.toString(sources.size())); + for (SourceEvidence source : sources) { + DraftAuthorizationFenceBinding.frame(out, source.canonicalBytes()); + } + return out.toByteArray(); + } + + public static AccountPublicationAuthorizationBinding fromStored(byte[] stored) { + FrameReader reader = new FrameReader(stored); + reader.expect(SCHEMA); + UUID operationId = uuid(reader.text()); + UUID fenceId = uuid(reader.text()); + FrameReader inputReader = new FrameReader(reader.bytes()); + inputReader.expect("account-publication-input/v1"); + UUID actor = uuid(inputReader.text()); + byte[] selectionBytes = inputReader.bytes(); + String digest = inputReader.text(); + inputReader.requireEnd(); + var selection = + AuthoredDraftPublishSelectionBinding.fromStored( + new String(selectionBytes, StandardCharsets.UTF_8), digest); + String countText = reader.text(); + DraftAuthorizationFenceBinding.decimal(countText, false); + final int count; + try { + count = Integer.parseInt(countText); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException("Publication source count out of range", invalid); + } + if (count > reader.remaining() / Integer.BYTES) { + throw new IllegalArgumentException("Incomplete publication source vector"); + } + List sources = new ArrayList<>(); + for (int i = 0; i < count; i++) { + sources.add(SourceEvidence.fromStored(reader.bytes())); + } + reader.requireEnd(); + var binding = + new AccountPublicationAuthorizationBinding( + operationId, fenceId, new PreallocationInput(actor, selection), sources); + if (!Arrays.equals(stored, binding.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical publication authorization binding"); + } + return binding; + } + + private static UUID uuid(String value) { + DraftAuthorizationFenceBinding.canonicalUuid(value); + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBinding.java new file mode 100644 index 0000000000..9c1d742629 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBinding.java @@ -0,0 +1,359 @@ +package net.firedevops.firemud.common.publication; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** + * Immutable exact selection of an existing synchronized authored Draft for full-version + * publication. This is retained selection evidence, not authorization, owner freeze, or release + * evidence. + */ +public final class AuthoredDraftPublishSelectionBinding { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final PublishIntent intent; + private final TargetProof target; + private final DraftCommitBinding selectedCommit; + private final UUID fenceRequestId; + private final UUID fenceCommitId; + private final String fenceInputDigest; + private final String fenceResultVectorJson; + private final String fenceCreatedAt; + private final String canonicalJson; + private final byte[] canonicalBytes; + private final String digest; + + private AuthoredDraftPublishSelectionBinding( + PublishIntent intent, + TargetProof target, + DraftCommitBinding selectedCommit, + VisibilityFence fence) { + this.intent = Objects.requireNonNull(intent, "intent"); + this.target = Objects.requireNonNull(target, "target"); + this.selectedCommit = Objects.requireNonNull(selectedCommit, "selectedCommit"); + Objects.requireNonNull(fence, "fence"); + if (!intent.canonicalTenantId().equals(target.canonicalTenantId()) + || !intent.canonicalVersionId().equals(target.canonicalVersionId()) + || !target.equals(selectedCommit.target()) + || !intent.selectedCommitRequestId().equals(selectedCommit.requestId()) + || !intent.selectedCommitId().equals(selectedCommit.commitId()) + || !intent.selectedCommitDigest().equals(selectedCommit.digest()) + || !target.equals(fence.target()) + || !intent.selectedCommitRequestId().equals(fence.requestId()) + || !intent.selectedCommitId().equals(fence.commitId()) + || !intent.selectedCommitDigest().equals(fence.inputDigest())) { + throw new IllegalArgumentException( + "Authored Draft publication selection differs from its exact synchronized commit fence"); + } + requireCanonicalArray(fence.resultVectorJson()); + this.fenceRequestId = fence.requestId(); + this.fenceCommitId = fence.commitId(); + this.fenceInputDigest = fence.inputDigest(); + this.fenceResultVectorJson = fence.resultVectorJson(); + this.fenceCreatedAt = fence.createdAt().toInstant().toString(); + try { + canonicalBytes = + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(toJsonObject())); + canonicalJson = new String(canonicalBytes, StandardCharsets.UTF_8); + digest = sha256(canonicalBytes); + } catch (IOException exception) { + throw new IllegalArgumentException( + "Authored Draft publication selection could not be canonicalized", exception); + } + } + + /** + * Constructs the exact retained value after the repository has independently verified the locked + * Version, durable commit, owner result vector, and current visibility fence. + */ + public static AuthoredDraftPublishSelectionBinding capture( + PublishIntent intent, TargetProof target, DraftCommitBinding binding, VisibilityFence fence) { + return new AuthoredDraftPublishSelectionBinding(intent, target, binding, fence); + } + + /** Reconstructs a retained selection and rejects malformed or noncanonical stored bytes. */ + public static AuthoredDraftPublishSelectionBinding fromStored( + String storedJson, String storedDigest) { + Objects.requireNonNull(storedJson, "storedJson"); + Objects.requireNonNull(storedDigest, "storedDigest"); + try { + JsonNode root = JSON.readTree(storedJson); + if (root == null || !root.isObject() || !"1".equals(requiredText(root, "schemaVersion"))) { + throw new IllegalArgumentException("Unsupported authored Draft selection schema"); + } + JsonNode intentNode = requiredObject(root, "intent"); + PublishIntent intent = + new PublishIntent( + UUID.fromString(requiredText(intentNode, "canonicalTenantId")), + UUID.fromString(requiredText(intentNode, "canonicalVersionId")), + requiredText(intentNode, "publishRequestId"), + requiredText(intentNode, "expectedVersionStateEpoch"), + requiredText(intentNode, "notes"), + UUID.fromString(requiredText(intentNode, "selectedCommitRequestId")), + UUID.fromString(requiredText(intentNode, "selectedCommitId")), + requiredText(intentNode, "selectedCommitDigest")); + JsonNode targetNode = requiredObject(root, "target"); + TargetProof target = + new TargetProof( + UUID.fromString(requiredText(targetNode, "canonicalTenantId")), + UUID.fromString(requiredText(targetNode, "canonicalVersionId")), + positiveLong(targetNode, "gameDesignVersionRowId"), + requiredText(targetNode, "gameDesignVersionTenantKey"), + positiveLong(targetNode, "sourceGameRowId"), + requiredText(targetNode, "sourceGameTenantKey"), + requiredText(targetNode, "sourceProvenanceKind")); + DraftCommitBinding selectedCommit = + DraftCommitBinding.fromStored( + requiredText(root, "selectedCommitBindingJson"), + requiredText(root, "selectedCommitDigest")); + JsonNode fenceNode = requiredObject(root, "synchronizedFence"); + String fenceResultVectorJson = requiredText(fenceNode, "resultVectorJson"); + requireCanonicalArray(fenceResultVectorJson); + VisibilityFence fence = + new VisibilityFence( + target, + UUID.fromString(requiredText(fenceNode, "requestId")), + UUID.fromString(requiredText(fenceNode, "commitId")), + requiredText(fenceNode, "inputDigest"), + fenceResultVectorJson, + OffsetDateTime.parse(requiredText(fenceNode, "createdAt"))); + AuthoredDraftPublishSelectionBinding selection = + new AuthoredDraftPublishSelectionBinding(intent, target, selectedCommit, fence); + if (!selection.canonicalJson.equals(storedJson) + || !selection.digest.equals(storedDigest) + || !Arrays.equals( + selection.canonicalBytes, storedJson.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException( + "Stored authored Draft publication selection is not exact canonical JSON"); + } + return selection; + } catch (RuntimeException exception) { + throw new IllegalStateException("Stored authored Draft selection is corrupt", exception); + } + } + + public PublishIntent intent() { + return intent; + } + + public TargetProof target() { + return target; + } + + public DraftCommitBinding selectedCommit() { + return selectedCommit; + } + + public UUID fenceRequestId() { + return fenceRequestId; + } + + public UUID fenceCommitId() { + return fenceCommitId; + } + + public String fenceInputDigest() { + return fenceInputDigest; + } + + public String fenceResultVectorJson() { + return fenceResultVectorJson; + } + + public String fenceCreatedAt() { + return fenceCreatedAt; + } + + public String canonicalJson() { + return canonicalJson; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof AuthoredDraftPublishSelectionBinding selection + && digest.equals(selection.digest) + && Arrays.equals(canonicalBytes, selection.canonicalBytes)); + } + + @Override + public int hashCode() { + return 31 * digest.hashCode() + Arrays.hashCode(canonicalBytes); + } + + private Map toJsonObject() { + Map root = new LinkedHashMap<>(); + root.put("schemaVersion", "1"); + root.put("intent", intentJson(intent)); + root.put("target", targetJson(target)); + root.put("selectedCommitBindingJson", selectedCommit.canonicalJson()); + root.put("selectedCommitDigest", selectedCommit.digest()); + Map fence = new LinkedHashMap<>(); + fence.put("requestId", fenceRequestId.toString()); + fence.put("commitId", fenceCommitId.toString()); + fence.put("inputDigest", fenceInputDigest); + fence.put("resultVectorJson", fenceResultVectorJson); + fence.put("createdAt", fenceCreatedAt); + root.put("synchronizedFence", fence); + return root; + } + + private static Map intentJson(PublishIntent intent) { + Map object = new LinkedHashMap<>(); + object.put("canonicalTenantId", intent.canonicalTenantId().toString()); + object.put("canonicalVersionId", intent.canonicalVersionId().toString()); + object.put("publishRequestId", intent.publishRequestId()); + object.put("expectedVersionStateEpoch", intent.expectedVersionStateEpoch()); + object.put("notes", intent.notes()); + object.put("selectedCommitRequestId", intent.selectedCommitRequestId().toString()); + object.put("selectedCommitId", intent.selectedCommitId().toString()); + object.put("selectedCommitDigest", intent.selectedCommitDigest()); + return object; + } + + private static Map targetJson(TargetProof target) { + Map object = new LinkedHashMap<>(); + object.put("canonicalTenantId", target.canonicalTenantId().toString()); + object.put("canonicalVersionId", target.canonicalVersionId().toString()); + object.put("gameDesignVersionRowId", Long.toString(target.gameDesignVersionRowId())); + object.put("gameDesignVersionTenantKey", target.gameDesignVersionTenantKey()); + object.put("sourceGameRowId", Long.toString(target.sourceGameRowId())); + object.put("sourceGameTenantKey", target.sourceGameTenantKey()); + object.put("sourceProvenanceKind", target.sourceProvenanceKind()); + return object; + } + + private static JsonNode requiredObject(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isObject()) { + throw new IllegalArgumentException( + "Stored authored Draft selection is missing object field " + field); + } + return value; + } + + private static String requiredText(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException( + "Stored authored Draft selection is missing text field " + field); + } + return value.textValue(); + } + + private static long positiveLong(JsonNode object, String field) { + String value = requiredText(object, field); + try { + long parsed = Long.parseLong(value); + if (parsed <= 0 || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException( + "Stored source row ID is not a positive canonical decimal"); + } + return parsed; + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Stored source row ID is outside the supported range", exception); + } + } + + private static void requireCanonicalArray(String storedJson) { + try { + JsonNode node = JSON.readTree(storedJson); + if (node == null || !node.isArray()) { + throw new IllegalArgumentException("Stored owner result vector is not an array"); + } + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(storedJson); + if (!Arrays.equals(canonical, storedJson.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("Stored owner result vector is not canonical JSON"); + } + } catch (IOException exception) { + throw new IllegalArgumentException("Stored owner result vector is malformed JSON", exception); + } + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + /** Full caller-supplied intent for selecting one exact Draft commit to publish. */ + public record PublishIntent( + UUID canonicalTenantId, + UUID canonicalVersionId, + String publishRequestId, + String expectedVersionStateEpoch, + String notes, + UUID selectedCommitRequestId, + UUID selectedCommitId, + String selectedCommitDigest) { + public PublishIntent { + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + PublicationDigestRequestBinding.validatePublicationIdentity( + canonicalTenantId.toString(), publishRequestId); + requirePositiveCounter(expectedVersionStateEpoch, "expectedVersionStateEpoch"); + Objects.requireNonNull(notes, "notes"); + requireNonNil(selectedCommitRequestId, "selectedCommitRequestId"); + requireNonNil(selectedCommitId, "selectedCommitId"); + requireDigest(selectedCommitDigest, "selectedCommitDigest"); + } + } + + private static void requirePositiveCounter(String value, String label) { + Objects.requireNonNull(value, label); + if (!value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(label + " must be a positive canonical decimal string"); + } + } + + private static void requireDigest(String value, String label) { + Objects.requireNonNull(value, label); + if (!value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(label + " must be a canonical SHA-256 digest"); + } + } + + /** + * Exact previously captured synchronized fence; its structure does not authenticate its owner. + */ + public record VisibilityFence( + TargetProof target, + UUID requestId, + UUID commitId, + String inputDigest, + String resultVectorJson, + OffsetDateTime createdAt) {} + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBindingTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBindingTest.java new file mode 100644 index 0000000000..8b7be8ae28 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBindingTest.java @@ -0,0 +1,141 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.OffsetDateTime; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.junit.jupiter.api.Test; + +/** Isolated fixture currentness is stipulated, not a legal/verification producer. */ +class AccountPublicationAuthorizationBindingTest { + @Test + void roundTripRetainsNestedSelectionAndSeparatesInputFromAllocatedFencesAndCapture() { + var input = + new AccountPublicationAuthorizationBinding.PreallocationInput( + UUID.randomUUID(), selection("notes")); + var source = + new SourceEvidence( + SourceKind.ACCOUNT, + input.actorAccountId().toString(), + "3", + "4", + null, + null, + new byte[] {9}); + var original = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), UUID.randomUUID(), input, List.of(source)); + var restored = AccountPublicationAuthorizationBinding.fromStored(original.canonicalBytes()); + assertThat(restored.canonicalBytes()).isEqualTo(original.canonicalBytes()); + var reallocated = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), UUID.randomUUID(), input, List.of(source)); + assertThat(reallocated.input().digest()).isEqualTo(input.digest()); + assertThat(reallocated.canonicalBytes()).isNotEqualTo(original.canonicalBytes()); + assertThat(restored.input().selection().digest()).isEqualTo(input.selection().digest()); + var recaptured = + new AccountPublicationAuthorizationBinding( + original.operationId(), + original.fenceId(), + input, + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + input.actorAccountId().toString(), + "4", + "5", + null, + null, + new byte[] {10}))); + assertThat(recaptured.input().digest()).isEqualTo(input.digest()); + assertThat(recaptured.canonicalBytes()).isNotEqualTo(original.canonicalBytes()); + } + + @Test + void rejectsDifferentActorScopeDuplicateSourcesAndWrongOperationDomain() { + var input = + new AccountPublicationAuthorizationBinding.PreallocationInput( + UUID.randomUUID(), selection("notes")); + var source = + new SourceEvidence( + SourceKind.ACCOUNT, UUID.randomUUID().toString(), "1", "1", null, null, new byte[] {1}); + assertThatThrownBy( + () -> + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), UUID.randomUUID(), input, List.of(source))) + .isInstanceOf(IllegalArgumentException.class); + var exact = + new SourceEvidence( + SourceKind.ACCOUNT, + input.actorAccountId().toString(), + "1", + "1", + null, + null, + new byte[] {1}); + assertThatThrownBy( + () -> + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), UUID.randomUUID(), input, List.of(exact, exact))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> AccountPublicationAuthorizationBinding.fromStored(exact.canonicalBytes())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static AuthoredDraftPublishSelectionBinding selection(String notes) { + var target = + new DraftCommitBinding.TargetProof( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 9007199254740993L, + "tenant-source", + 9007199254740995L, + "tenant-source", + "NEW_GAME_ROW"); + var commit = + DraftCommitBinding.create( + target, + UUID.fromString("33333333-3333-4333-8333-333333333333"), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.fromString("55555555-5555-4555-8555-555555555555"), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "{\"mutation\":\"fixture\"}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world", + "ROOM_SCOPE", + "room", + "900719925474099312345"))); + return AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + "publication-é", + "900719925474099312345", + notes, + commit.requestId(), + commit.commitId(), + commit.digest()), + target, + commit, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + commit.requestId(), + commit.commitId(), + commit.digest(), + "[]", + OffsetDateTime.parse("2026-10-05T00:00:00Z"))); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBindingTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBindingTest.java new file mode 100644 index 0000000000..82257a3097 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBindingTest.java @@ -0,0 +1,168 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.OffsetDateTime; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.junit.jupiter.api.Test; + +/** + * Codec-only fixtures stipulate upstream synchronized evidence; they grant no publication + * authority. + */ +class AuthoredDraftPublishSelectionBindingTest { + @Test + void preservesRetainedBytesDigestLargeCountersAndDefensiveCopies() { + var original = selection(" exact notes — "); + var restored = + AuthoredDraftPublishSelectionBinding.fromStored( + original.canonicalJson(), original.digest()); + assertThat(restored).isEqualTo(original); + assertThat(restored.digest()) + .isEqualTo(DraftAuthorizationFenceBinding.digest(original.canonicalBytes())); + assertThat(restored.intent().expectedVersionStateEpoch()).isEqualTo("900719925474099312345"); + assertThat(restored.canonicalJson()) + .contains("\"gameDesignVersionRowId\":\"9007199254740993\""); + byte[] copy = restored.canonicalBytes(); + copy[0] = 0; + assertThat(restored.canonicalBytes()).isEqualTo(original.canonicalBytes()); + } + + @Test + void changedNotesChangeCompleteSelectionDigest() { + assertThat(selection("old").digest()).isNotEqualTo(selection("new").digest()); + } + + @Test + void everyCallerSelectionFieldAndSynchronizedEvidenceIsBound() { + var original = selection("notes"); + String json = original.canonicalJson(); + for (String changed : + List.of( + json.replace("publication-é", "publication-other"), + json.replace( + "\"expectedVersionStateEpoch\":\"900719925474099312345\"", + "\"expectedVersionStateEpoch\":\"900719925474099312346\""), + json.replace("\"notes\":\"notes\"", "\"notes\":\"changed\""), + json.replace("2026-10-05T00:00:00Z", "2026-10-05T00:00:01Z"), + json.replace("\"resultVectorJson\":\"[]\"", "\"resultVectorJson\":\"[1]\""))) { + String digest = + DraftAuthorizationFenceBinding.digest( + changed.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + assertThat(digest).isNotEqualTo(original.digest()); + assertThat(AuthoredDraftPublishSelectionBinding.fromStored(changed, digest).canonicalJson()) + .isEqualTo(changed); + } + for (String field : + List.of( + "canonicalTenantId", + "canonicalVersionId", + "selectedCommitRequestId", + "selectedCommitId")) { + String changed = + json.replaceFirst( + "\\\"" + field + "\\\":\\\"[0-9a-f-]+\\\"", + "\"" + field + "\":\"66666666-6666-4666-8666-666666666666\""); + assertThatThrownBy( + () -> + AuthoredDraftPublishSelectionBinding.fromStored( + changed, + DraftAuthorizationFenceBinding.digest( + changed.getBytes(java.nio.charset.StandardCharsets.UTF_8)))) + .isInstanceOf(IllegalStateException.class); + } + String changedDigest = + json.replaceFirst( + "\\\"selectedCommitDigest\\\":\\\"sha256:[0-9a-f]{64}\\\"", + "\"selectedCommitDigest\":\"sha256:" + "0".repeat(64) + "\""); + assertThatThrownBy( + () -> + AuthoredDraftPublishSelectionBinding.fromStored( + changedDigest, + DraftAuthorizationFenceBinding.digest( + changedDigest.getBytes(java.nio.charset.StandardCharsets.UTF_8)))) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void corruptNestedCommitOrSynchronizedFenceFailsEvenWithRecomputedOuterDigest() { + var original = selection("notes"); + String corrupt = + original.canonicalJson().replace("\"inputDigest\":\"", "\"inputDigest\":\"changed-"); + assertThatThrownBy( + () -> + AuthoredDraftPublishSelectionBinding.fromStored( + corrupt, + DraftAuthorizationFenceBinding.digest( + corrupt.getBytes(java.nio.charset.StandardCharsets.UTF_8)))) + .isInstanceOf(IllegalStateException.class); + String changed = original.canonicalJson().replace("900719925474099312345", "01"); + assertThatThrownBy( + () -> + AuthoredDraftPublishSelectionBinding.fromStored( + changed, + DraftAuthorizationFenceBinding.digest( + changed.getBytes(java.nio.charset.StandardCharsets.UTF_8)))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + AuthoredDraftPublishSelectionBinding.fromStored( + original.canonicalJson() + " ", original.digest())) + .isInstanceOf(IllegalStateException.class); + } + + private static AuthoredDraftPublishSelectionBinding selection(String notes) { + var target = + new DraftCommitBinding.TargetProof( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 9007199254740993L, + "tenant-source", + 9007199254740995L, + "tenant-source", + "NEW_GAME_ROW"); + var commit = + DraftCommitBinding.create( + target, + UUID.fromString("33333333-3333-4333-8333-333333333333"), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.fromString("55555555-5555-4555-8555-555555555555"), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "{\"mutation\":\"fixture\"}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world", + "ROOM_SCOPE", + "room", + "900719925474099312345"))); + return AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + "publication-é", + "900719925474099312345", + notes, + commit.requestId(), + commit.commitId(), + commit.digest()), + target, + commit, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + commit.requestId(), + commit.commitId(), + commit.digest(), + "[]", + OffsetDateTime.parse("2026-10-05T00:00:00Z"))); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelection.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelection.java index 5ff59fe7d1..32feeec605 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelection.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelection.java @@ -1,352 +1,84 @@ package net.firedevops.firemud.gamedesign.draft; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.time.OffsetDateTime; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.Map; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; -import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.PublicationEvidence; -import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.VisibilityFence; -import tools.jackson.databind.JsonNode; -import tools.jackson.databind.ObjectMapper; /** - * Immutable exact selection of an existing synchronized authored Draft for full-version - * publication. This is retained selection evidence, not authorization, owner freeze, or release - * evidence. + * Exact existing synchronized Draft selection. The shared codec preserves the original V43 bytes + * and digest; neither this retained selection nor codec validation establishes publication authority. */ public final class AuthoredDraftPublishSelection { - private static final ObjectMapper JSON = new ObjectMapper(); - private static final UUID NIL_UUID = new UUID(0L, 0L); + private final AuthoredDraftPublishSelectionBinding binding; - private final PublishIntent intent; - private final TargetProof target; - private final DraftCommitBinding selectedCommit; - private final UUID fenceRequestId; - private final UUID fenceCommitId; - private final String fenceInputDigest; - private final String fenceResultVectorJson; - private final String fenceCreatedAt; - private final String canonicalJson; - private final byte[] canonicalBytes; - private final String digest; - - private AuthoredDraftPublishSelection( - PublishIntent intent, - TargetProof target, - DraftCommitBinding selectedCommit, - VisibilityFence fence) { - this.intent = Objects.requireNonNull(intent, "intent"); - this.target = Objects.requireNonNull(target, "target"); - this.selectedCommit = Objects.requireNonNull(selectedCommit, "selectedCommit"); - Objects.requireNonNull(fence, "fence"); - if (!intent.canonicalTenantId().equals(target.canonicalTenantId()) - || !intent.canonicalVersionId().equals(target.canonicalVersionId()) - || !target.equals(selectedCommit.target()) - || !intent.selectedCommitRequestId().equals(selectedCommit.requestId()) - || !intent.selectedCommitId().equals(selectedCommit.commitId()) - || !intent.selectedCommitDigest().equals(selectedCommit.digest()) - || !target.equals(fence.target()) - || !intent.selectedCommitRequestId().equals(fence.requestId()) - || !intent.selectedCommitId().equals(fence.commitId()) - || !intent.selectedCommitDigest().equals(fence.inputDigest())) { - throw new IllegalArgumentException( - "Authored Draft publication selection differs from its exact synchronized commit fence"); - } - requireCanonicalArray(fence.resultVectorJson()); - this.fenceRequestId = fence.requestId(); - this.fenceCommitId = fence.commitId(); - this.fenceInputDigest = fence.inputDigest(); - this.fenceResultVectorJson = fence.resultVectorJson(); - this.fenceCreatedAt = fence.createdAt().toInstant().toString(); - try { - canonicalBytes = - Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(toJsonObject())); - canonicalJson = new String(canonicalBytes, StandardCharsets.UTF_8); - digest = sha256(canonicalBytes); - } catch (IOException exception) { - throw new IllegalArgumentException( - "Authored Draft publication selection could not be canonicalized", exception); - } + private AuthoredDraftPublishSelection(AuthoredDraftPublishSelectionBinding binding) { + this.binding = Objects.requireNonNull(binding); } - /** - * Constructs the exact retained value after the repository has independently verified the locked - * Version, durable commit, owner result vector, and current visibility fence. - */ public static AuthoredDraftPublishSelection capture( PublishIntent intent, TargetProof target, PublicationEvidence evidence) { Objects.requireNonNull(evidence, "evidence"); + var fence = evidence.visibilityFence(); return new AuthoredDraftPublishSelection( - intent, target, evidence.binding(), evidence.visibilityFence()); + AuthoredDraftPublishSelectionBinding.capture( + sharedIntent(intent), target, evidence.binding(), + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + fence.target(), fence.requestId(), fence.commitId(), fence.inputDigest(), + fence.resultVectorJson(), fence.createdAt()))); } - /** Reconstructs a retained selection and rejects malformed or noncanonical stored bytes. */ public static AuthoredDraftPublishSelection fromStored(String storedJson, String storedDigest) { - Objects.requireNonNull(storedJson, "storedJson"); - Objects.requireNonNull(storedDigest, "storedDigest"); - try { - JsonNode root = JSON.readTree(storedJson); - if (root == null || !root.isObject() || !"1".equals(requiredText(root, "schemaVersion"))) { - throw new IllegalArgumentException("Unsupported authored Draft selection schema"); - } - JsonNode intentNode = requiredObject(root, "intent"); - PublishIntent intent = - new PublishIntent( - UUID.fromString(requiredText(intentNode, "canonicalTenantId")), - UUID.fromString(requiredText(intentNode, "canonicalVersionId")), - requiredText(intentNode, "publishRequestId"), - requiredText(intentNode, "expectedVersionStateEpoch"), - requiredText(intentNode, "notes"), - UUID.fromString(requiredText(intentNode, "selectedCommitRequestId")), - UUID.fromString(requiredText(intentNode, "selectedCommitId")), - requiredText(intentNode, "selectedCommitDigest")); - JsonNode targetNode = requiredObject(root, "target"); - TargetProof target = - new TargetProof( - UUID.fromString(requiredText(targetNode, "canonicalTenantId")), - UUID.fromString(requiredText(targetNode, "canonicalVersionId")), - positiveLong(targetNode, "gameDesignVersionRowId"), - requiredText(targetNode, "gameDesignVersionTenantKey"), - positiveLong(targetNode, "sourceGameRowId"), - requiredText(targetNode, "sourceGameTenantKey"), - requiredText(targetNode, "sourceProvenanceKind")); - DraftCommitBinding selectedCommit = - DraftCommitBinding.fromStored( - requiredText(root, "selectedCommitBindingJson"), - requiredText(root, "selectedCommitDigest")); - JsonNode fenceNode = requiredObject(root, "synchronizedFence"); - String fenceResultVectorJson = requiredText(fenceNode, "resultVectorJson"); - requireCanonicalArray(fenceResultVectorJson); - VisibilityFence fence = - new VisibilityFence( - target, - UUID.fromString(requiredText(fenceNode, "requestId")), - UUID.fromString(requiredText(fenceNode, "commitId")), - requiredText(fenceNode, "inputDigest"), - fenceResultVectorJson, - OffsetDateTime.parse(requiredText(fenceNode, "createdAt"))); - AuthoredDraftPublishSelection selection = - new AuthoredDraftPublishSelection(intent, target, selectedCommit, fence); - if (!selection.canonicalJson.equals(storedJson) - || !selection.digest.equals(storedDigest) - || !Arrays.equals( - selection.canonicalBytes, storedJson.getBytes(StandardCharsets.UTF_8))) { - throw new IllegalArgumentException( - "Stored authored Draft publication selection is not exact canonical JSON"); - } - return selection; - } catch (RuntimeException exception) { - throw new IllegalStateException("Stored authored Draft selection is corrupt", exception); - } + return new AuthoredDraftPublishSelection( + AuthoredDraftPublishSelectionBinding.fromStored(storedJson, storedDigest)); } public PublishIntent intent() { - return intent; - } - - public TargetProof target() { - return target; - } - - public DraftCommitBinding selectedCommit() { - return selectedCommit; - } - - public UUID fenceRequestId() { - return fenceRequestId; - } - - public UUID fenceCommitId() { - return fenceCommitId; - } - - public String fenceInputDigest() { - return fenceInputDigest; - } - - public String fenceResultVectorJson() { - return fenceResultVectorJson; - } - - public String fenceCreatedAt() { - return fenceCreatedAt; - } - - public String canonicalJson() { - return canonicalJson; - } - - public byte[] canonicalBytes() { - return canonicalBytes.clone(); - } - - public String digest() { - return digest; - } + var intent = binding.intent(); + return new PublishIntent(intent.canonicalTenantId(), intent.canonicalVersionId(), + intent.publishRequestId(), intent.expectedVersionStateEpoch(), intent.notes(), + intent.selectedCommitRequestId(), intent.selectedCommitId(), intent.selectedCommitDigest()); + } + + public TargetProof target() { return binding.target(); } + public DraftCommitBinding selectedCommit() { return binding.selectedCommit(); } + public UUID fenceRequestId() { return binding.fenceRequestId(); } + public UUID fenceCommitId() { return binding.fenceCommitId(); } + public String fenceInputDigest() { return binding.fenceInputDigest(); } + public String fenceResultVectorJson() { return binding.fenceResultVectorJson(); } + public String fenceCreatedAt() { return binding.fenceCreatedAt(); } + public String canonicalJson() { return binding.canonicalJson(); } + public byte[] canonicalBytes() { return binding.canonicalBytes(); } + public String digest() { return binding.digest(); } @Override public boolean equals(Object other) { - return this == other - || (other instanceof AuthoredDraftPublishSelection selection - && digest.equals(selection.digest) - && Arrays.equals(canonicalBytes, selection.canonicalBytes)); + return this == other || (other instanceof AuthoredDraftPublishSelection selection + && binding.equals(selection.binding)); } @Override - public int hashCode() { - return 31 * digest.hashCode() + Arrays.hashCode(canonicalBytes); - } + public int hashCode() { return binding.hashCode(); } - private Map toJsonObject() { - Map root = new LinkedHashMap<>(); - root.put("schemaVersion", "1"); - root.put("intent", intentJson(intent)); - root.put("target", targetJson(target)); - root.put("selectedCommitBindingJson", selectedCommit.canonicalJson()); - root.put("selectedCommitDigest", selectedCommit.digest()); - Map fence = new LinkedHashMap<>(); - fence.put("requestId", fenceRequestId.toString()); - fence.put("commitId", fenceCommitId.toString()); - fence.put("inputDigest", fenceInputDigest); - fence.put("resultVectorJson", fenceResultVectorJson); - fence.put("createdAt", fenceCreatedAt); - root.put("synchronizedFence", fence); - return root; + private static AuthoredDraftPublishSelectionBinding.PublishIntent sharedIntent(PublishIntent intent) { + Objects.requireNonNull(intent, "intent"); + return new AuthoredDraftPublishSelectionBinding.PublishIntent( + intent.canonicalTenantId(), intent.canonicalVersionId(), intent.publishRequestId(), + intent.expectedVersionStateEpoch(), intent.notes(), intent.selectedCommitRequestId(), + intent.selectedCommitId(), intent.selectedCommitDigest()); } - private static Map intentJson(PublishIntent intent) { - Map object = new LinkedHashMap<>(); - object.put("canonicalTenantId", intent.canonicalTenantId().toString()); - object.put("canonicalVersionId", intent.canonicalVersionId().toString()); - object.put("publishRequestId", intent.publishRequestId()); - object.put("expectedVersionStateEpoch", intent.expectedVersionStateEpoch()); - object.put("notes", intent.notes()); - object.put("selectedCommitRequestId", intent.selectedCommitRequestId().toString()); - object.put("selectedCommitId", intent.selectedCommitId().toString()); - object.put("selectedCommitDigest", intent.selectedCommitDigest()); - return object; - } - - private static Map targetJson(TargetProof target) { - Map object = new LinkedHashMap<>(); - object.put("canonicalTenantId", target.canonicalTenantId().toString()); - object.put("canonicalVersionId", target.canonicalVersionId().toString()); - object.put("gameDesignVersionRowId", Long.toString(target.gameDesignVersionRowId())); - object.put("gameDesignVersionTenantKey", target.gameDesignVersionTenantKey()); - object.put("sourceGameRowId", Long.toString(target.sourceGameRowId())); - object.put("sourceGameTenantKey", target.sourceGameTenantKey()); - object.put("sourceProvenanceKind", target.sourceProvenanceKind()); - return object; - } - - private static JsonNode requiredObject(JsonNode object, String field) { - JsonNode value = object == null ? null : object.get(field); - if (value == null || !value.isObject()) { - throw new IllegalArgumentException( - "Stored authored Draft selection is missing object field " + field); - } - return value; - } - - private static String requiredText(JsonNode object, String field) { - JsonNode value = object == null ? null : object.get(field); - if (value == null || !value.isTextual()) { - throw new IllegalArgumentException( - "Stored authored Draft selection is missing text field " + field); - } - return value.textValue(); - } - - private static long positiveLong(JsonNode object, String field) { - String value = requiredText(object, field); - try { - long parsed = Long.parseLong(value); - if (parsed <= 0 || !Long.toString(parsed).equals(value)) { - throw new IllegalArgumentException( - "Stored source row ID is not a positive canonical decimal"); - } - return parsed; - } catch (NumberFormatException exception) { - throw new IllegalArgumentException( - "Stored source row ID is outside the supported range", exception); - } - } - - private static void requireCanonicalArray(String storedJson) { - try { - JsonNode node = JSON.readTree(storedJson); - if (node == null || !node.isArray()) { - throw new IllegalArgumentException("Stored owner result vector is not an array"); - } - byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(storedJson); - if (!Arrays.equals(canonical, storedJson.getBytes(StandardCharsets.UTF_8))) { - throw new IllegalArgumentException("Stored owner result vector is not canonical JSON"); - } - } catch (IOException exception) { - throw new IllegalArgumentException("Stored owner result vector is malformed JSON", exception); - } - } - - private static String sha256(byte[] bytes) { - try { - return "sha256:" - + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 is unavailable", exception); - } - } - - /** Full caller-supplied intent for selecting one exact Draft commit to publish. */ + /** Full original eight caller inputs, retaining the existing public API. */ public record PublishIntent( - UUID canonicalTenantId, - UUID canonicalVersionId, - String publishRequestId, - String expectedVersionStateEpoch, - String notes, - UUID selectedCommitRequestId, - UUID selectedCommitId, - String selectedCommitDigest) { + UUID canonicalTenantId, UUID canonicalVersionId, String publishRequestId, + String expectedVersionStateEpoch, String notes, UUID selectedCommitRequestId, + UUID selectedCommitId, String selectedCommitDigest) { public PublishIntent { - requireNonNil(canonicalTenantId, "canonicalTenantId"); - requireNonNil(canonicalVersionId, "canonicalVersionId"); - PublicationDigestRequestBinding.validatePublicationIdentity( - canonicalTenantId.toString(), publishRequestId); - requirePositiveCounter(expectedVersionStateEpoch, "expectedVersionStateEpoch"); - Objects.requireNonNull(notes, "notes"); - requireNonNil(selectedCommitRequestId, "selectedCommitRequestId"); - requireNonNil(selectedCommitId, "selectedCommitId"); - requireDigest(selectedCommitDigest, "selectedCommitDigest"); - } - } - - private static void requirePositiveCounter(String value, String label) { - Objects.requireNonNull(value, label); - if (!value.matches("[1-9][0-9]*")) { - throw new IllegalArgumentException(label + " must be a positive canonical decimal string"); - } - } - - private static void requireDigest(String value, String label) { - Objects.requireNonNull(value, label); - if (!value.matches("sha256:[0-9a-f]{64}")) { - throw new IllegalArgumentException(label + " must be a canonical SHA-256 digest"); - } - } - - private static void requireNonNil(UUID value, String label) { - Objects.requireNonNull(value, label); - if (NIL_UUID.equals(value)) { - throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + new AuthoredDraftPublishSelectionBinding.PublishIntent( + canonicalTenantId, canonicalVersionId, publishRequestId, expectedVersionStateEpoch, + notes, selectedCommitRequestId, selectedCommitId, selectedCommitDigest); } } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishAttempt.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishAttempt.java index ab51eeb0da..b9ef9861f4 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishAttempt.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishAttempt.java @@ -12,6 +12,7 @@ public class PublishAttempt { private String publishWorkflowId; private PublishType publishType; private PublishAttemptStatus status = PublishAttemptStatus.PENDING; + private long revision = 1L; private Long versionId; private int versionNumber; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperation.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperation.java new file mode 100644 index 0000000000..214da466b3 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperation.java @@ -0,0 +1,67 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; + +/** Closed original operation input. Codec validation supplies integrity, never authorization. */ +public record GameDesignPublicationOperation( + AccountPublicationAuthorizationBinding account, + WorldPublishedStartLocationEvidence world) { + public static final String SCHEMA = "game-design-publication-operation/v1"; + + public GameDesignPublicationOperation { + Objects.requireNonNull(account); + Objects.requireNonNull(world); + account = AccountPublicationAuthorizationBinding.fromStored(account.canonicalBytes()); + world = WorldPublishedStartLocationEvidence.fromStored(world.canonicalBytes()); + var selection = account.input().selection(); + var intent = selection.intent(); + var freeze = world.request(); + if (!account.tenantId().equals(freeze.canonicalTenantId()) + || !intent.canonicalVersionId().equals(freeze.canonicalVersionId()) + || !intent.publishRequestId().equals(freeze.publicationRequestId()) + || !selection.digest().equals("sha256:" + freeze.requestDigest()) + || !intent.expectedVersionStateEpoch().equals(Long.toString(freeze.versionStateEpoch())) + || !intent.selectedCommitId().toString().equals(freeze.appliedCommitId()) + || !Arrays.equals(selection.selectedCommit().canonicalBytes(), + DraftAuthorizationFenceBinding.fromStored(world.originalAccountBindingBytes()).normalizedInput())) { + throw new IllegalArgumentException("PUBLICATION_OPERATION_IDENTITY_CONFLICT"); + } + String workflow = FiremudWorkflowIds.workflowId("publish", account.tenantId().toString(), + "publish-request", intent.publishRequestId()); + if (!workflow.equals(freeze.publishWorkflowId())) { + throw new IllegalArgumentException("PUBLICATION_OPERATION_WORKFLOW_CONFLICT"); + } + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, account.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, world.canonicalBytes()); + return out.toByteArray(); + } + + public static GameDesignPublicationOperation fromStored(byte[] bytes) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(bytes); + reader.expect(SCHEMA); + var operation = new GameDesignPublicationOperation( + AccountPublicationAuthorizationBinding.fromStored(reader.bytes()), + WorldPublishedStartLocationEvidence.fromStored(reader.bytes())); + reader.requireEnd(); + if (!Arrays.equals(bytes, operation.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical publication operation"); + } + return operation; + } + + public String workflowId() { return world.request().publishWorkflowId(); } + public String tenantKey() { return account.input().selection().target().gameDesignVersionTenantKey(); } + public long versionId() { return account.input().selection().target().gameDesignVersionRowId(); } + public String selectionDigest() { return account.input().selection().digest(); } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java new file mode 100644 index 0000000000..b9d89f9dfd --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java @@ -0,0 +1,120 @@ +package net.firedevops.firemud.gamedesign.publication; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner storage only. Deliberately has no runtime bean or authenticated ingress. */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal owner storage collaborator.") +public final class GameDesignPublicationOperationRepository { + private final DSLContext dsl; + + public GameDesignPublicationOperationRepository(DSLContext dsl) { this.dsl = Objects.requireNonNull(dsl); } + + public void reserve(GameDesignPublicationOperation operation) { + requireTransaction(); + lock(operation.tenantKey(), operation.workflowId(), operation.versionId()); + Optional existing = read(operation.workflowId()); + if (existing.isPresent()) { + exact(existing.get().operation(), operation); + return; + } + dsl.execute("INSERT INTO game_design_publication_operation " + + "(publish_workflow_id, tenant_id, version_id, selection_digest, request_bytes) VALUES (?, ?, ?, ?, ?)", + operation.workflowId(), operation.tenantKey(), operation.versionId(), operation.selectionDigest(), operation.canonicalBytes()); + } + + public GameDesignPublicationOperation requirePending(String tenant, String workflow, long version, String digest) { + requireTransaction(); + lock(tenant, workflow, version); + Readback result = read(workflow).orElseThrow(() -> new IllegalStateException("PUBLICATION_OPERATION_UNAVAILABLE")); + var operation = result.operation(); + if (!operation.tenantKey().equals(tenant) || operation.versionId() != version + || !operation.selectionDigest().equals(digest) || !result.outcome().equals("PENDING")) { + throw new IllegalStateException("PUBLICATION_OPERATION_SEALED_OR_CHANGED"); + } + return operation; + } + + public void seal(String tenant, String workflow, long version, String digest, boolean published) { + GameDesignPublicationOperation operation = requirePending(tenant, workflow, version, digest); + Record release = dsl.fetchOne("SELECT to_jsonb(r)::TEXT AS evidence FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", tenant, version); + String evidence = release == null ? null : release.get("evidence", String.class); + if (published != (evidence != null)) throw new IllegalStateException("PUBLICATION_READBACK_UNRESOLVED"); + String outcome = published ? "PUBLISHED" : "NO_PUBLICATION"; + byte[] result = receipt(operation, outcome, evidence); + int changed = dsl.execute("UPDATE game_design_publication_operation SET outcome = ?, result_bytes = ?, release_row_json = ?, revision = revision + 1 WHERE publish_workflow_id = ? AND outcome = 'PENDING' AND revision = 1", + outcome, result, evidence, workflow); + if (changed != 1) throw new IllegalStateException("PUBLICATION_OPERATION_CAS_CONFLICT"); + } + + public Optional read(String workflow) { + Record row = dsl.fetchOne("SELECT * FROM game_design_publication_operation WHERE publish_workflow_id = ?", workflow); + if (row == null) return Optional.empty(); + var operation = GameDesignPublicationOperation.fromStored(row.get("request_bytes", byte[].class)); + String outcome = row.get("outcome", String.class); + byte[] bytes = row.get("result_bytes", byte[].class); + String evidence = row.get("release_row_json", String.class); + if (!operation.workflowId().equals(workflow) + || !operation.tenantKey().equals(row.get("tenant_id", String.class)) + || operation.versionId() != row.get("version_id", Long.class) + || !operation.selectionDigest().equals(row.get("selection_digest", String.class))) { + throw new IllegalStateException("PUBLICATION_OPERATION_STORAGE_CONFLICT"); + } + if (!"PENDING".equals(outcome)) { + if (!Arrays.equals(bytes, receipt(operation, outcome, evidence))) throw new IllegalStateException("PUBLICATION_RECEIPT_CORRUPT"); + Record release = dsl.fetchOne("SELECT to_jsonb(r)::TEXT AS evidence FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", operation.tenantKey(), operation.versionId()); + String actual = release == null ? null : release.get("evidence", String.class); + if (!Objects.equals(actual, evidence) || ("PUBLISHED".equals(outcome) != (actual != null))) { + throw new IllegalStateException("PUBLICATION_RECEIPT_BACKING_CONFLICT"); + } + Record attempt = dsl.fetchOne("SELECT status FROM publish_attempt WHERE publish_workflow_id = ?", workflow); + if (attempt == null) { + throw new IllegalStateException("PUBLICATION_RECEIPT_ATTEMPT_CONFLICT"); + } + String attemptStatus = attempt.get("status", String.class); + if (!("PUBLISHED".equals(outcome) ? "SUCCEEDED" : "FAILED").equals(attemptStatus)) { + throw new IllegalStateException("PUBLICATION_RECEIPT_ATTEMPT_CONFLICT"); + } + } + return Optional.of(new Readback(operation, outcome, bytes)); + } + + private void lock(String tenant, String workflow, long version) { + if (dsl.fetchOne("SELECT id FROM game WHERE tenant_id = ? FOR UPDATE", tenant) == null + || dsl.fetchOne("SELECT id FROM publish_attempt WHERE tenant_id = ? AND publish_workflow_id = ? AND version_id = ? FOR UPDATE", tenant, workflow, version) == null + || dsl.fetchOne("SELECT id FROM version WHERE tenant_id = ? AND id = ? FOR UPDATE", tenant, version) == null) { + throw new IllegalStateException("PUBLICATION_OWNER_IDENTITY_UNAVAILABLE"); + } + } + + public static void exact(GameDesignPublicationOperation retained, GameDesignPublicationOperation requested) { + if (!Arrays.equals(retained.canonicalBytes(), requested.canonicalBytes())) throw new IllegalArgumentException("PUBLICATION_OPERATION_IDENTITY_CONFLICT"); + } + + private static byte[] receipt(GameDesignPublicationOperation operation, String outcome, String evidence) { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-publication-owner-readback/v1"); + DraftAuthorizationFenceBinding.frame(out, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, outcome); + DraftAuthorizationFenceBinding.frame(out, evidence == null ? "" : evidence); + return out.toByteArray(); + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) throw new IllegalStateException("Publication owner transaction required"); + } + + public record Readback(GameDesignPublicationOperation operation, String outcome, byte[] receiptBytes) { + public Readback { receiptBytes = receiptBytes == null ? null : receiptBytes.clone(); } + @Override public byte[] receiptBytes() { return receiptBytes == null ? null : receiptBytes.clone(); } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationService.java new file mode 100644 index 0000000000..be98a8096e --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationService.java @@ -0,0 +1,46 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Objects; +import java.util.Optional; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Explicit local seam; upstream authentication/current authority must be established separately. */ +public final class GameDesignPublicationOperationService { + private final GameDesignPublicationOperationRepository repository; + private final TransactionTemplate write; + private final TransactionTemplate read; + + public GameDesignPublicationOperationService(GameDesignPublicationOperationRepository repository, + PlatformTransactionManager transactions) { + this.repository = Objects.requireNonNull(repository); + write = new TransactionTemplate(transactions); + write.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + read = new TransactionTemplate(transactions); + read.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + read.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + read.setReadOnly(true); + } + + public GameDesignPublicationOperationRepository.Readback retainVerifiedOperation(GameDesignPublicationOperation operation) { + requireIndependent(); + var retained = readExact(operation); + if (retained.isPresent()) return retained.orElseThrow(); + write.executeWithoutResult(status -> repository.reserve(operation)); + return readExact(operation).orElseThrow(() -> new IllegalStateException("Publication operation readback absent")); + } + + public Optional readExact(GameDesignPublicationOperation operation) { + requireIndependent(); + return read.execute(status -> repository.read(operation.workflowId()).map(result -> { + GameDesignPublicationOperationRepository.exact(result.operation(), operation); + return result; + })); + } + + private static void requireIndependent() { + if (TransactionSynchronizationManager.isActualTransactionActive()) throw new IllegalStateException("Independent publication read/write boundary required"); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java index cb187e11ef..e355d85b1b 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java @@ -8,6 +8,7 @@ import net.firedevops.firemud.gamedesign.entity.PublishAttempt; import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; import net.firedevops.firemud.gamedesign.model.PublishType; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; import org.jooq.Condition; import org.jooq.DSLContext; import org.jooq.Field; @@ -29,6 +30,7 @@ public class PublishAttemptRepository { private static final Field PUBLISH_TYPE = DSL.field(DSL.name("publish_type"), String.class); private static final Field STATUS = DSL.field(DSL.name("status"), String.class); + private static final Field REVISION = DSL.field(DSL.name("revision"), Long.class); private static final Field VERSION_ID = DSL.field(DSL.name("version_id"), Long.class); private static final Field VERSION_NUMBER = DSL.field(DSL.name("version_number"), Integer.class); @@ -61,6 +63,44 @@ public Optional findByPublishWorkflowId(String publishWorkflowId .fetchOne(this::toEntity)); } + /** The owning Game lock always precedes the exact attempt lock. */ + public Optional findByPublishWorkflowIdForUpdate(String workflow) { + Optional initial = findByPublishWorkflowId(workflow); + if (initial.isEmpty()) return initial; + dsl.fetchOne("SELECT id FROM game WHERE tenant_id = ? FOR UPDATE", initial.get().getTenantId()); + return Optional.ofNullable(dsl.selectFrom(PUBLISH_ATTEMPT_TABLE) + .where(PUBLISH_WORKFLOW_ID.eq(workflow)).forUpdate().fetchOne(this::toEntity)); + } + + public net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence requirePublicationPending(PublishAttempt attempt) { + return new GameDesignPublicationOperationRepository(dsl).requirePending(attempt.getTenantId(), + attempt.getPublishWorkflowId(), attempt.getVersionId(), attempt.getRequestDigest()).world(); + } + + public void sealPublication(PublishAttempt attempt, boolean published) { + new GameDesignPublicationOperationRepository(dsl).seal(attempt.getTenantId(), + attempt.getPublishWorkflowId(), attempt.getVersionId(), attempt.getRequestDigest(), published); + } + + public void requirePublishedOperation(PublishAttempt attempt) { + requireTerminalOperation(attempt, "PUBLISHED"); + } + + public void requireNoPublicationOperation(PublishAttempt attempt) { + requireTerminalOperation(attempt, "NO_PUBLICATION"); + } + + private void requireTerminalOperation(PublishAttempt attempt, String outcome) { + var result = new GameDesignPublicationOperationRepository(dsl).read(attempt.getPublishWorkflowId()) + .orElseThrow(() -> new IllegalStateException("PUBLICATION_OPERATION_UNAVAILABLE")); + if (!outcome.equals(result.outcome()) + || !result.operation().selectionDigest().equals(attempt.getRequestDigest()) + || result.operation().versionId() != attempt.getVersionId() + || !result.operation().tenantKey().equals(attempt.getTenantId())) { + throw new IllegalStateException("PUBLICATION_OPERATION_SEALED_OR_CHANGED"); + } + } + /** * Installs a compatibility digest only once, and only on the exact legacy full-version row whose * identity was validated by the caller. @@ -88,6 +128,7 @@ public Optional backfillFullVersionRequestDigestIfAbsent( .and(VERSION_NUMBER.eq(versionNumber)); dsl.update(PUBLISH_ATTEMPT_TABLE) .set(REQUEST_DIGEST, requestDigest) + .set(REVISION, REVISION.plus(1L)) .where(fullVersionAttemptIdentity.and(REQUEST_DIGEST.isNull())) .execute(); return Optional.ofNullable( @@ -122,6 +163,7 @@ public PublishAttempt save(PublishAttempt attempt) { PUBLISH_WORKFLOW_ID, PUBLISH_TYPE, STATUS, + REVISION, VERSION_ID, VERSION_NUMBER, SCRIPT_PATCH_VERSION, @@ -137,11 +179,12 @@ public PublishAttempt save(PublishAttempt attempt) { } return toEntity(record); } - dsl.update(PUBLISH_ATTEMPT_TABLE) + int changed = dsl.update(PUBLISH_ATTEMPT_TABLE) .set(TENANT_ID, attempt.getTenantId()) .set(PUBLISH_WORKFLOW_ID, attempt.getPublishWorkflowId()) .set(PUBLISH_TYPE, attempt.getPublishType().name()) .set(STATUS, attempt.getStatus().name()) + .set(REVISION, Math.addExact(attempt.getRevision(), 1L)) .set(VERSION_ID, attempt.getVersionId()) .set(VERSION_NUMBER, attempt.getVersionNumber()) .set(SCRIPT_PATCH_VERSION, attempt.getScriptPatchVersion()) @@ -151,8 +194,10 @@ public PublishAttempt save(PublishAttempt attempt) { .set(FAILURE_MESSAGE, attempt.getFailureMessage()) .set(CREATED_AT, JooqPersistenceSupport.toTimestamp(createdAt)) .set(COMPLETED_AT, JooqPersistenceSupport.toTimestamp(attempt.getCompletedAt())) - .where(ID.eq(attempt.getId())) + .where(ID.eq(attempt.getId()).and(REVISION.eq(attempt.getRevision())) + .and(STATUS.eq(PublishAttemptStatus.PENDING.name()))) .execute(); + if (changed != 1) throw new IllegalStateException("PUBLISH_ATTEMPT_CAS_CONFLICT"); return findByPublishWorkflowId(attempt.getPublishWorkflowId()).orElseThrow(); } @@ -162,6 +207,7 @@ private PublishAttempt toEntity(Record record) { } PublishAttempt attempt = new PublishAttempt(); attempt.setId(record.get(ID)); + attempt.setRevision(record.get(REVISION)); attempt.setTenantId(record.get(TENANT_ID)); attempt.setPublishWorkflowId(record.get(PUBLISH_WORKFLOW_ID)); String publishType = record.get(PUBLISH_TYPE); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java index d92da744bd..3b2e0f6b38 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java @@ -113,6 +113,7 @@ public void recordFullVersionParticipantDigests( private void recordParticipantDigestsInCurrentTransaction( String publishWorkflowId, List participantDigests) { PublishAttempt attempt = requireAttempt(publishWorkflowId); + if (attempt.getStatus() != PublishAttemptStatus.PENDING) throw new IllegalStateException("Publish attempt is terminal"); participantDigestRepository.deleteByPublishAttemptId(attempt.getId()); participantDigests.forEach( digest -> participantDigestRepository.save(toEntity(attempt.getId(), digest))); @@ -132,6 +133,8 @@ public void markFullVersionSucceeded(String publishWorkflowId) { private void markSucceededInCurrentTransaction(String publishWorkflowId) { PublishAttempt attempt = requireAttempt(publishWorkflowId); + if (attempt.getStatus() == PublishAttemptStatus.SUCCEEDED) return; + if (attempt.getStatus() != PublishAttemptStatus.PENDING) throw new IllegalStateException("Publish attempt is terminal"); attempt.setStatus(PublishAttemptStatus.SUCCEEDED); attempt.setFailureCode(null); attempt.setFailureMessage(null); @@ -156,6 +159,10 @@ public void markFullVersionFailed( private void markFailedInCurrentTransaction( String publishWorkflowId, String failureCode, String failureMessage) { PublishAttempt attempt = requireAttempt(publishWorkflowId); + if (attempt.getStatus() == PublishAttemptStatus.FAILED + && Objects.equals(attempt.getFailureCode(), failureCode) + && Objects.equals(attempt.getFailureMessage(), failureMessage)) return; + if (attempt.getStatus() != PublishAttemptStatus.PENDING) throw new IllegalStateException("Publish attempt is terminal"); attempt.setStatus(PublishAttemptStatus.FAILED); attempt.setFailureCode(failureCode); attempt.setFailureMessage(failureMessage); @@ -165,7 +172,7 @@ private void markFailedInCurrentTransaction( private PublishAttempt requireAttempt(String publishWorkflowId) { return publishAttemptRepository - .findByPublishWorkflowId(publishWorkflowId) + .findByPublishWorkflowIdForUpdate(publishWorkflowId) .orElseThrow(() -> new IllegalArgumentException("publish attempt not found")); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java index b7478f5db3..5946c22bae 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java @@ -21,6 +21,9 @@ import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.AssetSelection; import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; +import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.VersionAssetExportCandidateService; @@ -43,6 +46,8 @@ public final class VersionAssetExportCandidateServiceImpl private static final String MANIFEST_USAGE_KEY = "manifest.json"; private static final String BINARY_ARTIFACT_KIND = "BINARY"; private final VersionRepository versionRepository; + private final GameRepository gameRepository; + private final PublishAttemptRepository attemptRepository; private final VersionAssetArtifactRepository artifactRepository; private final VersionAssetPublicationService publicationService; private final ObjectMapper objectMapper; @@ -51,11 +56,15 @@ public final class VersionAssetExportCandidateServiceImpl public VersionAssetExportCandidateServiceImpl( VersionRepository versionRepository, + GameRepository gameRepository, + PublishAttemptRepository attemptRepository, VersionAssetArtifactRepository artifactRepository, VersionAssetPublicationService publicationService, PlatformTransactionManager transactionManager, ObjectMapper objectMapper) { this.versionRepository = Objects.requireNonNull(versionRepository, "versionRepository"); + this.gameRepository = Objects.requireNonNull(gameRepository, "gameRepository"); + this.attemptRepository = Objects.requireNonNull(attemptRepository, "attemptRepository"); this.artifactRepository = Objects.requireNonNull(artifactRepository, "artifactRepository"); this.publicationService = Objects.requireNonNull(publicationService, "publicationService"); this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper"); @@ -103,6 +112,9 @@ public ExportedAssetManifest readExportCandidate(String tenantId, int versionNum private ExportedAssetManifest recordInOwnerTransaction( String tenantId, int versionNumber, ExportedAssetManifest requested) { + if (gameRepository.findByTenantIdForUpdate(tenantId) == null) { + throw new IllegalStateException(CANDIDATE_NOT_FOUND); + } Version initiallyFound = versionRepository .findByTenantIdAndVersionNumber(tenantId, versionNumber) @@ -110,6 +122,20 @@ private ExportedAssetManifest recordInOwnerTransaction( if (initiallyFound.getId() == null || initiallyFound.getId() <= 0) { throw new IllegalStateException(CANDIDATE_CONFLICT); } + var initialArtifact = artifactRepository.findByTenantIdAndVersionId(tenantId, initiallyFound.getId()) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + var attempt = attemptRepository.findByPublishWorkflowIdForUpdate(initialArtifact.getLastWorkflowId()); + // Standalone private candidate recording is not publication authority. If an actual selected + // attempt exists, its immutable operation must still be open before any new candidate admission. + if (attempt.isPresent()) { + var current = attempt.get(); + if (!Objects.equals(current.getTenantId(), tenantId) + || !Objects.equals(current.getVersionId(), initiallyFound.getId()) + || current.getStatus() != PublishAttemptStatus.PENDING) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + if (current.getRequestDigest() != null) attemptRepository.requirePublicationPending(current); + } Version version = versionRepository .findByTenantIdAndIdForUpdate(tenantId, initiallyFound.getId()) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java index 1de3dda72f..e9440728e2 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java @@ -151,6 +151,7 @@ public PublishWorkflowSnapshot reconcileFullVersionPublish(PublishWorkflowReques // Failed legacy attempts may retain only terminal evidence after their draft was deleted. // Validate their stable scope before entering the draft-dependent compatibility backfill. validateTerminalFullVersionAttempt(attempt, request); + if (request.intent() != null) publishAttemptRepository.requireNoPublicationOperation(attempt); return new PublishWorkflowSnapshot( attempt.getVersionId() == null ? 0L : attempt.getVersionId(), attempt.getVersionNumber(), @@ -327,9 +328,12 @@ private PublishAttempt reserveDraftAttempt(PublishWorkflowRequest request) { } private PublishAttempt createDraftAttempt(PublishWorkflowRequest request) { + if (gameRepository.findByTenantIdForUpdate(request.tenantId()) == null) { + throw new IllegalArgumentException("game not found"); + } AuthoredDraftPublishSelection selection = requireSelectedIntent(request); Optional existingAttempt = - publishAttemptRepository.findByPublishWorkflowId(request.publishWorkflowId()); + publishAttemptRepository.findByPublishWorkflowIdForUpdate(request.publishWorkflowId()); if (existingAttempt.isPresent()) { validateFullVersionAttempt(existingAttempt.get(), request); return existingAttempt.get(); @@ -365,10 +369,11 @@ PublishWorkflowSnapshot finalizeFullVersion( } PublishAttempt attempt = publishAttemptRepository - .findByPublishWorkflowId(request.publishWorkflowId()) + .findByPublishWorkflowIdForUpdate(request.publishWorkflowId()) .orElseThrow(() -> new PendingReconciliationException("publish attempt not found")); validateFullVersionAttempt(attempt, request); if (attempt.getStatus() == PublishAttemptStatus.SUCCEEDED) { + publishAttemptRepository.requirePublishedOperation(attempt); PublicationReadback readback = readPublication(request, attempt); if (!readback.isComplete()) { throw pendingReconciliation( @@ -381,6 +386,8 @@ PublishWorkflowSnapshot finalizeFullVersion( throw pendingReconciliation("full-version attempt is no longer pending"); } + var publicationOperation = publishAttemptRepository.requirePublicationPending(attempt); + Version version = requireAttemptVersionForUpdate(attempt, request); PublicationReadback existingPublication = readPublication(request, attempt); if (existingPublication.isComplete()) { @@ -391,6 +398,7 @@ PublishWorkflowSnapshot finalizeFullVersion( request.publishWorkflowId(), existingPublication.bundle().participantDigests()); publishAttemptService.markFullVersionSucceeded(request.publishWorkflowId()); + publishAttemptRepository.sealPublication(attempt, true); return succeededSnapshot(attempt); } if (existingPublication.isPartial()) { @@ -424,7 +432,8 @@ PublishWorkflowSnapshot finalizeFullVersion( request.publishWorkflowId(), exportedManifest, generationConfigRevision, - participantDigests); + participantDigests, + publicationOperation); version.setVersionState(VersionLifecycleState.PUBLISHED); version.setVersionStateEpoch(Math.addExact(version.getVersionStateEpoch(), 1L)); version.setUpdatedAt(LocalDateTime.now()); @@ -438,6 +447,7 @@ PublishWorkflowSnapshot finalizeFullVersion( recordedParticipantDigestService.recordVerifiedDigests( dto.tenantId(), PublishType.FULL_VERSION, request.publishWorkflowId(), participantDigests); publishAttemptService.markFullVersionSucceeded(request.publishWorkflowId()); + publishAttemptRepository.sealPublication(attempt, true); return succeededSnapshot(attempt); } @@ -454,6 +464,7 @@ private PublishWorkflowSnapshot reconcileCommittedAttempt( private PublishWorkflowSnapshot replaySucceededAttempt( PublishWorkflowRequest request, PublishAttempt attempt) { + if (request.intent() != null) publishAttemptRepository.requirePublishedOperation(attempt); PublishedReleaseBundleDto bundle; try { bundle = readPublishedReleaseBundle(request.tenantId(), attempt.getVersionId()); @@ -487,7 +498,7 @@ private void recordVerifiedAndSucceed( } PublishAttempt current = publishAttemptRepository - .findByPublishWorkflowId(request.publishWorkflowId()) + .findByPublishWorkflowIdForUpdate(request.publishWorkflowId()) .orElseThrow( () -> new PendingReconciliationException("publish attempt not found")); validateFullVersionAttempt(current, request); @@ -495,6 +506,11 @@ private void recordVerifiedAndSucceed( && current.getStatus() != PublishAttemptStatus.SUCCEEDED) { throw pendingReconciliation("full-version attempt is no longer pending"); } + if (current.getStatus() == PublishAttemptStatus.PENDING) { + publishAttemptRepository.requirePublicationPending(current); + } else { + publishAttemptRepository.requirePublishedOperation(current); + } requireAttemptVersionForUpdate(current, request); PublicationReadback currentReadback = readPublication(request, current); if (!currentReadback.isComplete()) { @@ -512,6 +528,7 @@ private void recordVerifiedAndSucceed( currentReadback.bundle().participantDigests()); if (current.getStatus() == PublishAttemptStatus.PENDING) { publishAttemptService.markFullVersionSucceeded(request.publishWorkflowId()); + publishAttemptRepository.sealPublication(current, true); } return null; }); @@ -562,13 +579,14 @@ private PublishWorkflowSnapshot failDefinitively( } PublishAttempt current = publishAttemptRepository - .findByPublishWorkflowId(request.publishWorkflowId()) + .findByPublishWorkflowIdForUpdate(request.publishWorkflowId()) .orElseThrow( () -> new PendingReconciliationException("publish attempt not found")); validateFullVersionAttempt(current, request); if (current.getStatus() != PublishAttemptStatus.PENDING) { throw pendingReconciliation("full-version attempt is no longer pending"); } + publishAttemptRepository.requirePublicationPending(current); Version currentVersion = requireAttemptVersionForUpdate(current, request); PublicationReadback readback = readPublication(request, current); if (!readback.isAbsent()) { @@ -598,10 +616,13 @@ private PublishWorkflowSnapshot failDefinitively( } publishAttemptService.markFullVersionFailed( request.publishWorkflowId(), failureCode, failureMessage); + publishAttemptRepository.sealPublication(current, false); // Approved launch remap sets may reference this failed candidate, so retain the row. return Boolean.TRUE; }); } catch (PublishAttemptService.FullVersionTransactionException ex) { + PublicationReadback winningPublication = readPublication(request, attempt); + if (winningPublication.isComplete()) return reconcileCommittedAttempt(request, attempt); throw pendingReconciliation( "full-version failure marking commit outcome is unknown; readback/reconciliation is required", ex.causeException()); diff --git a/services/game-design-service/src/main/resources/db/migration/V50__publication_operation_terminal_seal.sql b/services/game-design-service/src/main/resources/db/migration/V50__publication_operation_terminal_seal.sql new file mode 100644 index 0000000000..056e74b3a5 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V50__publication_operation_terminal_seal.sql @@ -0,0 +1,180 @@ +ALTER TABLE publish_attempt ADD COLUMN revision BIGINT NOT NULL DEFAULT 1 CHECK (revision > 0); + +CREATE TABLE game_design_publication_operation ( + publish_workflow_id VARCHAR(1024) PRIMARY KEY REFERENCES publish_attempt(publish_workflow_id) ON DELETE RESTRICT, + tenant_id VARCHAR(36) NOT NULL, + version_id BIGINT NOT NULL REFERENCES version(id) ON DELETE RESTRICT, + selection_digest VARCHAR(71) NOT NULL, + request_bytes BYTEA NOT NULL CHECK (octet_length(request_bytes) > 0), + outcome TEXT NOT NULL DEFAULT 'PENDING' CHECK (outcome IN ('PENDING', 'PUBLISHED', 'NO_PUBLICATION')), + revision BIGINT NOT NULL DEFAULT 1 CHECK (revision > 0), + result_bytes BYTEA, + release_row_json TEXT, + CHECK ((outcome = 'PENDING') = (result_bytes IS NULL)), + CHECK ((outcome = 'PUBLISHED') = (release_row_json IS NOT NULL)), + UNIQUE (tenant_id, version_id) +); + +-- [jooq ignore start] +CREATE FUNCTION guard_game_design_publication_operation() RETURNS trigger AS $$ +DECLARE attempt publish_attempt%ROWTYPE; selected game_design_authored_draft_publish_selection%ROWTYPE; + account_bytes BYTEA; input_bytes BYTEA; world_json JSONB; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'publication operation history is immutable' USING ERRCODE = 'check_violation'; + END IF; + PERFORM 1 FROM game WHERE tenant_id = NEW.tenant_id FOR UPDATE; + SELECT * INTO STRICT attempt FROM publish_attempt + WHERE publish_workflow_id = NEW.publish_workflow_id FOR UPDATE; + PERFORM 1 FROM version WHERE id = NEW.version_id AND tenant_id = NEW.tenant_id FOR UPDATE; + SELECT * INTO STRICT selected FROM game_design_authored_draft_publish_selection + WHERE game_design_version_tenant_key = NEW.tenant_id AND game_design_version_row_id = NEW.version_id; + account_bytes := published_world_selector_frame(NEW.request_bytes, 1); + input_bytes := published_world_selector_frame(account_bytes, 3); + world_json := convert_from(published_world_selector_frame(NEW.request_bytes, 2), 'UTF8')::JSONB; + IF convert_from(published_world_selector_frame(NEW.request_bytes, 0), 'UTF8') <> 'game-design-publication-operation/v1' + OR convert_from(published_world_selector_frame(account_bytes, 0), 'UTF8') <> 'account-publication-authorization/v1' + OR convert_from(published_world_selector_frame(input_bytes, 0), 'UTF8') <> 'account-publication-input/v1' + OR published_world_selector_frame(input_bytes, 2) IS DISTINCT FROM convert_to(selected.selection_json, 'UTF8') + OR convert_from(published_world_selector_frame(input_bytes, 3), 'UTF8') IS DISTINCT FROM selected.selection_digest + OR world_json->'request'->>'requestDigest' IS DISTINCT FROM substring(selected.selection_digest FROM 8) + OR world_json->'request'->>'canonicalTenantId' IS DISTINCT FROM selected.canonical_tenant_id::TEXT + OR world_json->'request'->>'canonicalVersionId' IS DISTINCT FROM selected.canonical_version_id::TEXT + OR world_json->'request'->>'publishWorkflowId' IS DISTINCT FROM NEW.publish_workflow_id + OR world_json->'request'->>'publicationRequestId' IS DISTINCT FROM selected.publish_request_id + OR world_json->'request'->>'versionStateEpoch' IS DISTINCT FROM selected.version_state_epoch::TEXT THEN + RAISE EXCEPTION 'publication operation bytes differ from exact owner selection' USING ERRCODE = 'check_violation'; + END IF; + IF attempt.tenant_id <> NEW.tenant_id OR attempt.version_id <> NEW.version_id + OR attempt.publish_type <> 'FULL_VERSION' OR attempt.request_digest IS DISTINCT FROM NEW.selection_digest + OR NOT EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection s + WHERE s.game_design_version_tenant_key = NEW.tenant_id + AND s.game_design_version_row_id = NEW.version_id AND s.selection_digest = NEW.selection_digest) THEN + RAISE EXCEPTION 'publication operation does not bind exact selected attempt' USING ERRCODE = 'check_violation'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.outcome <> 'PENDING' OR NEW.revision <> 1 OR attempt.status <> 'PENDING' + OR EXISTS (SELECT 1 FROM published_release_bundle WHERE tenant_id = NEW.tenant_id AND version_id = NEW.version_id) THEN + RAISE EXCEPTION 'historical attempts cannot acquire publication authority' USING ERRCODE = 'check_violation'; + END IF; + ELSE + IF OLD.outcome <> 'PENDING' OR NEW.outcome = 'PENDING' + OR NEW.revision <> OLD.revision + 1 + OR (NEW.publish_workflow_id, NEW.tenant_id, NEW.version_id, NEW.selection_digest, NEW.request_bytes) + IS DISTINCT FROM (OLD.publish_workflow_id, OLD.tenant_id, OLD.version_id, OLD.selection_digest, OLD.request_bytes) THEN + RAISE EXCEPTION 'publication operation identity or terminal outcome is immutable' USING ERRCODE = 'check_violation'; + END IF; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER game_design_publication_operation_guard BEFORE INSERT OR UPDATE OR DELETE + ON game_design_publication_operation FOR EACH ROW EXECUTE FUNCTION guard_game_design_publication_operation(); + +CREATE FUNCTION guard_selected_publication_release() RETURNS trigger AS $$ +DECLARE attempt publish_attempt%ROWTYPE; operation game_design_publication_operation%ROWTYPE; +BEGIN + IF NEW.script_only THEN RETURN NEW; END IF; + -- Old unselected history keeps its original read semantics; no operation is backfilled. + IF NEW.attestation_schema_version <> 'v2' AND NOT EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection + WHERE game_design_version_tenant_key = NEW.tenant_id AND game_design_version_row_id = NEW.version_id) THEN + RETURN NEW; + END IF; + PERFORM 1 FROM game WHERE tenant_id = NEW.tenant_id FOR UPDATE; + SELECT * INTO STRICT attempt FROM publish_attempt WHERE publish_workflow_id = NEW.publish_workflow_id FOR UPDATE; + PERFORM 1 FROM version WHERE id = NEW.version_id AND tenant_id = NEW.tenant_id FOR UPDATE; + SELECT * INTO STRICT operation FROM game_design_publication_operation WHERE publish_workflow_id = NEW.publish_workflow_id; + IF attempt.status <> 'PENDING' OR operation.outcome <> 'PENDING' + OR operation.tenant_id <> NEW.tenant_id OR operation.version_id <> NEW.version_id + OR attempt.request_digest IS DISTINCT FROM operation.selection_digest + OR NEW.attestation_schema_version <> 'v2' + OR convert_to(NEW.world_published_start_location_evidence_json, 'UTF8') + IS DISTINCT FROM published_world_selector_frame(operation.request_bytes, 2) THEN + RAISE EXCEPTION 'selected publication is absent, sealed, or changed' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER selected_publication_release_guard BEFORE INSERT ON published_release_bundle + FOR EACH ROW EXECUTE FUNCTION guard_selected_publication_release(); + +CREATE FUNCTION verify_publication_operation_commit() RETURNS trigger AS $$ +DECLARE operation game_design_publication_operation%ROWTYPE; release_json TEXT; attempt_status TEXT; +BEGIN + SELECT * INTO operation FROM game_design_publication_operation WHERE publish_workflow_id = NEW.publish_workflow_id; + IF NOT FOUND THEN RETURN NULL; END IF; + SELECT status INTO attempt_status FROM publish_attempt WHERE publish_workflow_id = operation.publish_workflow_id; + SELECT to_jsonb(r)::TEXT INTO release_json FROM published_release_bundle r + WHERE r.tenant_id = operation.tenant_id AND r.version_id = operation.version_id; + IF operation.outcome <> 'PENDING' AND operation.result_bytes IS DISTINCT FROM + int4send(octet_length(convert_to('game-design-publication-owner-readback/v1', 'UTF8'))) + || convert_to('game-design-publication-owner-readback/v1', 'UTF8') + || int4send(octet_length(operation.request_bytes)) || operation.request_bytes + || int4send(octet_length(convert_to(operation.outcome, 'UTF8'))) || convert_to(operation.outcome, 'UTF8') + || int4send(octet_length(convert_to(COALESCE(operation.release_row_json, ''), 'UTF8'))) + || convert_to(COALESCE(operation.release_row_json, ''), 'UTF8') THEN + RAISE EXCEPTION 'publication result bytes are not the exact owner receipt' USING ERRCODE = 'check_violation'; + END IF; + IF operation.outcome = 'PENDING' AND (release_json IS NOT NULL OR attempt_status <> 'PENDING') THEN + RAISE EXCEPTION 'selected publication must commit receipt and owner result together' USING ERRCODE = 'check_violation'; + ELSIF operation.outcome = 'NO_PUBLICATION' AND (release_json IS NOT NULL OR attempt_status <> 'FAILED') THEN + RAISE EXCEPTION 'no-publication seal contradicts owner commit' USING ERRCODE = 'check_violation'; + ELSIF operation.outcome = 'PUBLISHED' AND (release_json IS DISTINCT FROM operation.release_row_json + OR attempt_status <> 'SUCCEEDED' + OR NOT EXISTS (SELECT 1 FROM version WHERE id = operation.version_id AND tenant_id = operation.tenant_id AND version_state = 'PUBLISHED') + OR NOT EXISTS (SELECT 1 FROM version_asset_artifact WHERE tenant_id = operation.tenant_id AND version_id = operation.version_id AND artifact_state = 'PUBLISHED')) THEN + RAISE EXCEPTION 'publication receipt lacks atomic owner result' USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; +CREATE CONSTRAINT TRIGGER publication_operation_commit_guard AFTER INSERT OR UPDATE + ON game_design_publication_operation DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION verify_publication_operation_commit(); +CREATE CONSTRAINT TRIGGER selected_publication_release_commit_guard AFTER INSERT + ON published_release_bundle DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION verify_publication_operation_commit(); +CREATE CONSTRAINT TRIGGER selected_publication_attempt_commit_guard AFTER UPDATE + ON publish_attempt DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION verify_publication_operation_commit(); + +CREATE FUNCTION guard_publish_attempt_revision() RETURNS trigger AS $$ +BEGIN + IF OLD.status <> 'PENDING' OR NEW.revision <> OLD.revision + 1 + OR (NEW.id, NEW.tenant_id, NEW.publish_workflow_id, NEW.publish_type, NEW.version_id, + NEW.version_number, NEW.script_patch_version, NEW.base_version_id, NEW.created_at) + IS DISTINCT FROM (OLD.id, OLD.tenant_id, OLD.publish_workflow_id, OLD.publish_type, OLD.version_id, + OLD.version_number, OLD.script_patch_version, OLD.base_version_id, OLD.created_at) + OR (NEW.request_digest IS DISTINCT FROM OLD.request_digest AND + (OLD.request_digest IS NOT NULL OR EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection + WHERE game_design_version_tenant_key = OLD.tenant_id AND game_design_version_row_id = OLD.version_id))) THEN + RAISE EXCEPTION 'publish attempt is stale or terminal' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER publish_attempt_revision_guard BEFORE UPDATE ON publish_attempt + FOR EACH ROW EXECUTE FUNCTION guard_publish_attempt_revision(); + +CREATE FUNCTION guard_sealed_candidate_admission() RETURNS trigger AS $$ +BEGIN + -- Private puts already in flight may finish; this guards admission/retained candidate changes, + -- not cancellation, reachability, abandonment, deletion, or distributed object-store writes. + IF NEW.artifact_state = 'STAGED' AND EXISTS (SELECT 1 FROM game_design_publication_operation + WHERE tenant_id = NEW.tenant_id AND version_id = NEW.version_id AND outcome <> 'PENDING') THEN + RAISE EXCEPTION 'sealed publication refuses candidate admission' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER sealed_candidate_admission_guard BEFORE INSERT OR UPDATE ON version_asset_artifact + FOR EACH ROW EXECUTE FUNCTION guard_sealed_candidate_admission(); + +CREATE FUNCTION forbid_publication_operation_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'publication operation history cannot be truncated' USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER publication_operation_no_truncate BEFORE TRUNCATE ON game_design_publication_operation + FOR EACH STATEMENT EXECUTE FUNCTION forbid_publication_operation_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java new file mode 100644 index 0000000000..3447d22e51 --- /dev/null +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.gamedesign.draft; + +import java.math.BigInteger; +import java.util.List; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.gamedesign.entity.PublishAttempt; +import net.firedevops.firemud.gamedesign.model.PublishType; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; +import org.jooq.DSLContext; +import java.util.function.Supplier; +import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; +import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; +import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; + +/** ISOLATED upstream authority; executes actual GD synchronized selection/attempt/operation writes. */ +public final class IsolatedPublicationOwnerSetup { + private IsolatedPublicationOwnerSetup() {} + + /** Caller supplies a writable READ_COMMITTED owner transaction and an actual Draft target/epoch. */ + public static GameDesignPublicationOperation retain(DSLContext dsl, DraftCommitBinding.TargetProof target, + long draftEpoch) throws Exception { + return retain(dsl, target, draftEpoch, "ISOLATED owner transaction proof"); + } + + public static GameDesignPublicationOperation retain(DSLContext dsl, DraftCommitBinding.TargetProof target, + long draftEpoch, String notes) throws Exception { + var seed = IsolatedPublicationOperationFixtures.fresh(target); + var draft = seed.account().input().selection().selectedCommit(); + var coordinator = new DraftCommitCoordinatorRepository(dsl); + // The original Draft Account/World result is stipulated upstream fixture evidence, not a new + // GD Draft-authorization operation or live Account authority issued by this helper. + coordinator.claim(draft); + coordinator.claimApplicationSlot(draft); + var epochs = draft.affectedUnits().stream().map(unit -> new DraftCommitCoordinatorRepository.AppliedEpoch( + unit.aggregateType(), unit.aggregateId(), unit.scopeType(), unit.scopeId(), unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())).toList(); + var outcome = new DraftCommitCoordinatorRepository.OwnerOutcome(DraftCommitBinding.Owner.WORLD_MANAGEMENT, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, draft.commitId(), draft.digest(), + "ISOLATED-world-applied", seed.world().appliedResultBytes(), epochs); + coordinator.markOwnerInProgress(draft, DraftCommitBinding.Owner.WORLD_MANAGEMENT); + coordinator.recordOwnerOutcome(draft, outcome); + coordinator.advanceVisibilityFence(draft, new DraftCommitCoordinatorRepository.CoordinatorProof(draft, List.of(outcome))); + coordinator.releaseApplicationSlot(draft); + var seedIntent = seed.account().input().selection().intent(); + var selection = new AuthoredDraftPublishSelectionRepository(dsl, coordinator).reserve( + new AuthoredDraftPublishSelection.PublishIntent(target.canonicalTenantId(), target.canonicalVersionId(), + java.util.UUID.randomUUID().toString(), Long.toString(draftEpoch), notes, draft.requestId(), draft.commitId(), draft.digest())).selection(); + var operation = IsolatedPublicationOperationFixtures.forSelection( + AuthoredDraftPublishSelectionBinding.fromStored(selection.canonicalJson(), selection.digest()), seed.world()); + var attempt = new PublishAttempt(); + attempt.setTenantId(target.gameDesignVersionTenantKey()); + attempt.setPublishWorkflowId(operation.workflowId()); + attempt.setPublishType(PublishType.FULL_VERSION); + attempt.setVersionId(target.gameDesignVersionRowId()); + attempt.setVersionNumber(dsl.fetchOne("SELECT version_number FROM version WHERE id = ?", target.gameDesignVersionRowId()).get(0, Integer.class)); + attempt.setRequestDigest(selection.digest()); + new PublishAttemptRepository(dsl).save(attempt); + new GameDesignPublicationOperationRepository(dsl).reserve(operation); + return operation; + } + + /** Storage fixture commit only; does not substitute for actual command finalization proof. */ + public static PublishedReleaseBundle commitStorage(DSLContext dsl, VersionRepository versions, + GameDesignPublicationOperation operation, Supplier releaseWrite) { + var attempts = new PublishAttemptRepository(dsl); + var attempt = attempts.findByPublishWorkflowIdForUpdate(operation.workflowId()).orElseThrow(); + if (attempt.getStatus() == PublishAttemptStatus.SUCCEEDED) { + attempts.requirePublishedOperation(attempt); + return releaseWrite.get(); + } + attempts.requirePublicationPending(attempt); + var version = versions.findByTenantIdAndIdForUpdate(operation.tenantKey(), operation.versionId()).orElseThrow(); + PublishedReleaseBundle bundle = releaseWrite.get(); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(Math.addExact(version.getVersionStateEpoch(), 1)); + versions.save(version); + var artifact = new VersionAssetArtifact(); + artifact.setTenantId(operation.tenantKey()); artifact.setVersionId(operation.versionId()); + artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); artifact.setStateEpoch(1); + artifact.setExportedVersionNumber(version.getVersionNumber()); artifact.setManifestHash(bundle.getManifestHash()); + artifact.setLastWorkflowId(operation.workflowId()); artifact.setManifestSchemaVersion(bundle.getManifestSchemaVersion()); + artifact.setArtifactDigestsJson(bundle.getArtifactDigestsJson()); artifact.setPublishedObjectProofsJson("[]"); + new VersionAssetArtifactRepository(dsl).save(artifact); + attempt.setStatus(PublishAttemptStatus.SUCCEEDED); attempts.save(attempt); + attempts.sealPublication(attempt, true); + return bundle; + } +} diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java new file mode 100644 index 0000000000..7fd4477c1b --- /dev/null +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java @@ -0,0 +1,67 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; +import tools.jackson.databind.ObjectMapper; + +/** ISOLATED stipulated upstream source/World bytes; only callers' GD owner writes are real proof. */ +public final class IsolatedPublicationOperationFixtures { + private IsolatedPublicationOperationFixtures() {} + + /** A new fixture operation and freeze, never a reinterpretation of retained publication history. */ + public static GameDesignPublicationOperation fresh(DraftCommitBinding.TargetProof target) throws Exception { + var seed = PublishedWorldSelectorFixtures.evidence(target); + var originalDraftAccount = DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); + var draft = DraftCommitBinding.fromStored(new String(originalDraftAccount.gameDesignBinding(), StandardCharsets.UTF_8), originalDraftAccount.inputDigest()); + var appliedEpochs = draft.affectedUnits().stream().map(unit -> Map.of( + "aggregateType", unit.aggregateType(), "aggregateId", unit.aggregateId(), + "scopeType", unit.scopeType(), "scopeId", unit.scopeId(), + "expectedEpoch", unit.expectedEpoch(), "resultingEpoch", new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())).toList(); + String vector = new String(Rfc8785CanonicalJson.canonicalizeUtf8(new ObjectMapper().writeValueAsString(List.of(Map.of( + "owner", "WORLD_MANAGEMENT", "status", "APPLIED", "commitId", draft.commitId().toString(), + "bindingDigest", draft.digest(), "resultIdentity", "ISOLATED-world-applied", + "resultBytesBase64", Base64.getEncoder().encodeToString(seed.appliedResultBytes()), "appliedEpochs", appliedEpochs)))), StandardCharsets.UTF_8); + var intent = new AuthoredDraftPublishSelectionBinding.PublishIntent(target.canonicalTenantId(), target.canonicalVersionId(), + "ISOLATED-publication-request", "5", "ISOLATED owner transaction proof", draft.requestId(), draft.commitId(), draft.digest()); + var selected = AuthoredDraftPublishSelectionBinding.capture(intent, target, draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence(target, draft.requestId(), draft.commitId(), draft.digest(), vector, + OffsetDateTime.parse("2026-10-07T00:00:00Z"))); + return forSelection(selected, seed); + } + + public static GameDesignPublicationOperation forSelection(AuthoredDraftPublishSelectionBinding selected, + WorldPublishedStartLocationEvidence seed) { + var originalDraftAccount = DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); + var target = selected.target(); + var intent = selected.intent(); + var draft = selected.selectedCommit(); + var account = new AccountPublicationAuthorizationBinding(UUID.randomUUID(), UUID.randomUUID(), + new AccountPublicationAuthorizationBinding.PreallocationInput(originalDraftAccount.actorAccountId(), selected), + java.util.Arrays.stream(DraftAuthorizationFenceBinding.SourceKind.values()).map(kind -> + new DraftAuthorizationFenceBinding.SourceEvidence(kind, switch (kind) { + case ACCOUNT, GLOBAL_ROLES -> originalDraftAccount.actorAccountId().toString(); + case TENANT -> target.canonicalTenantId().toString(); + case MEMBERSHIP -> originalDraftAccount.actorAccountId() + "/" + target.canonicalTenantId(); + default -> "ISOLATED-" + kind; + }, "1", "1", null, null, ("ISOLATED-stipulated-" + kind).getBytes(StandardCharsets.UTF_8))).toList()); + var world = new WorldPublishedStartLocationEvidence(new WorldPublishedStartLocationEvidence.Request("test", target.canonicalTenantId(), + target.canonicalVersionId(), seed.request().intakeRequestId(), UUID.randomUUID(), intent.publishRequestId(), selected.digest().substring(7), + Long.parseLong(intent.expectedVersionStateEpoch()), FiremudWorkflowIds.workflowId("publish", target.canonicalTenantId().toString(), "publish-request", intent.publishRequestId()), + draft.commitId().toString(), seed.request().contentDigest(), 3, seed.request().worldAffectedTuples()), + seed.selectorReceiptBytes(), seed.originalAccountBindingBytes(), seed.appliedResultBytes()); + return new GameDesignPublicationOperation(account, world); + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java new file mode 100644 index 0000000000..a9453c25f7 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java @@ -0,0 +1,213 @@ +package integration.net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.config.PostgresProperties; +import net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; +import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; +import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationService; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; +import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +/** Actual GD owner DB guard proof; every upstream creator/source/freeze input is ISOLATED. */ +@Testcontainers(disabledWithoutDocker = true) +class GameDesignPublicationOperationPostgresIntegrationTest { + @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + private static final String MANIFEST = "sha256:" + "a".repeat(64); + + @Test + void noPublicationReceiptReplaysAfterLostResponseAndExcludesDelayedFinalizerAndRawInsert() throws Exception { + var fixture = fixture(); + noPublication(fixture); + var original = fixture.service().readExact(fixture.operation()).orElseThrow(); + assertThat(original.outcome()).isEqualTo("NO_PUBLICATION"); + assertThat(fixture.service().retainVerifiedOperation(fixture.operation()).receiptBytes()).isEqualTo(original.receiptBytes()); + assertThatThrownBy(() -> fixture.write().executeWithoutResult(status -> fixture.operations().requirePending( + fixture.operation().tenantKey(), fixture.operation().workflowId(), fixture.operation().versionId(), fixture.operation().selectionDigest()))) + .isInstanceOf(IllegalStateException.class).hasMessageContaining("SEALED_OR_CHANGED"); + assertThatThrownBy(() -> fixture.write().executeWithoutResult(status -> rawReleaseInsert(fixture))) + .hasMessageContaining("selected publication is absent, sealed, or changed"); + assertThat(fixture.releases().findByTenantIdAndVersionId(fixture.operation().tenantKey(), fixture.operation().versionId())).isEmpty(); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().receiptBytes()).isEqualTo(original.receiptBytes()); + } + + @Test + void publishedReceiptCannotBeDemotedByStaleFailureAndRetainsOriginalFreezeEpoch() throws Exception { + var fixture = fixture(); + var staleFailure = fixture.attempts().findByPublishWorkflowId(fixture.operation().workflowId()).orElseThrow(); + publish(fixture); + var original = fixture.service().readExact(fixture.operation()).orElseThrow(); + assertThat(original.outcome()).isEqualTo("PUBLISHED"); + assertThat(fixture.service().retainVerifiedOperation(fixture.operation()).receiptBytes()).isEqualTo(original.receiptBytes()); + assertThat(fixture.versions().findByTenantIdAndId(fixture.operation().tenantKey(), fixture.operation().versionId()).orElseThrow().getVersionStateEpoch()) + .isEqualTo(fixture.operation().world().request().versionStateEpoch() + 1); + staleFailure.setStatus(PublishAttemptStatus.FAILED); + assertThatThrownBy(() -> fixture.write().executeWithoutResult(status -> fixture.attempts().save(staleFailure))) + .isInstanceOf(IllegalStateException.class).hasMessageContaining("CAS_CONFLICT"); + assertThatThrownBy(() -> noPublication(fixture)).isInstanceOf(IllegalStateException.class); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().receiptBytes()).isEqualTo(original.receiptBytes()); + } + + @Test + void failedAtomicCommitLeavesAttemptOperationVersionAndReleasePendingForExactRetry() throws Exception { + var fixture = fixture(); + assertThatThrownBy(() -> fixture.write().executeWithoutResult(status -> { + publishInTransaction(fixture); + throw new IllegalStateException("ISOLATED rollback after all owner writes"); + })).hasMessageContaining("rollback after all owner writes"); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().outcome()).isEqualTo("PENDING"); + assertThat(fixture.releases().findByTenantIdAndVersionId(fixture.operation().tenantKey(), fixture.operation().versionId())).isEmpty(); + assertThat(fixture.attempts().findByPublishWorkflowId(fixture.operation().workflowId()).orElseThrow().getStatus()).isEqualTo(PublishAttemptStatus.PENDING); + assertThat(fixture.versions().findByTenantIdAndId(fixture.operation().tenantKey(), fixture.operation().versionId()).orElseThrow().getVersionState()).isEqualTo(VersionLifecycleState.DRAFT); + publish(fixture); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().outcome()).isEqualTo("PUBLISHED"); + } + + @Test + void noPublicationSerializesAgainstAnAlreadyScheduledLatePublisher() throws Exception { + var fixture = fixture(); + var sealed = new CountDownLatch(1); + var releaseSeal = new CountDownLatch(1); + try (var executor = Executors.newFixedThreadPool(2)) { + var winner = executor.submit(() -> fixture.write().executeWithoutResult(status -> { + noPublicationInTransaction(fixture); + sealed.countDown(); + await(releaseSeal); + })); + assertThat(sealed.await(10, TimeUnit.SECONDS)).isTrue(); + var loser = executor.submit(() -> { + assertThatThrownBy(() -> publish(fixture)).isInstanceOf(IllegalStateException.class); + }); + releaseSeal.countDown(); + winner.get(10, TimeUnit.SECONDS); + loser.get(10, TimeUnit.SECONDS); + } finally { releaseSeal.countDown(); } + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().outcome()).isEqualTo("NO_PUBLICATION"); + } + + private void noPublication(Fixture fixture) { fixture.write().executeWithoutResult(status -> noPublicationInTransaction(fixture)); } + private void noPublicationInTransaction(Fixture fixture) { + var op = fixture.operation(); + fixture.operations().requirePending(op.tenantKey(), op.workflowId(), op.versionId(), op.selectionDigest()); + var attempt = fixture.attempts().findByPublishWorkflowIdForUpdate(op.workflowId()).orElseThrow(); + attempt.setStatus(PublishAttemptStatus.FAILED); + attempt.setFailureCode("ISOLATED_BUSINESS_DENIAL"); + fixture.attempts().save(attempt); + fixture.operations().seal(op.tenantKey(), op.workflowId(), op.versionId(), op.selectionDigest(), false); + } + private void publish(Fixture fixture) { fixture.write().executeWithoutResult(status -> publishInTransaction(fixture)); } + private void publishInTransaction(Fixture fixture) { + var op = fixture.operation(); + fixture.operations().requirePending(op.tenantKey(), op.workflowId(), op.versionId(), op.selectionDigest()); + fixture.releases().save(bundle(fixture)); + var version = fixture.versions().findByTenantIdAndIdForUpdate(op.tenantKey(), op.versionId()).orElseThrow(); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(version.getVersionStateEpoch() + 1); + fixture.versions().save(version); + var artifact = new VersionAssetArtifact(); + artifact.setTenantId(op.tenantKey()); artifact.setVersionId(op.versionId()); + artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); artifact.setStateEpoch(1); + artifact.setExportedVersionNumber(version.getVersionNumber()); artifact.setManifestHash(MANIFEST); + artifact.setLastWorkflowId(op.workflowId()); artifact.setManifestSchemaVersion(1); + artifact.setArtifactDigestsJson("[]"); artifact.setPublishedObjectProofsJson("[]"); + fixture.artifacts().save(artifact); + var attempt = fixture.attempts().findByPublishWorkflowIdForUpdate(op.workflowId()).orElseThrow(); + attempt.setStatus(PublishAttemptStatus.SUCCEEDED); fixture.attempts().save(attempt); + fixture.operations().seal(op.tenantKey(), op.workflowId(), op.versionId(), op.selectionDigest(), true); + } + + private PublishedReleaseBundle bundle(Fixture fixture) { + var op = fixture.operation(); + var bundle = new PublishedReleaseBundle(); + bundle.setTenantId(op.tenantKey()); bundle.setVersionId(op.versionId()); bundle.setVersionNumber(1); + bundle.setCanonicalTenantId(op.account().tenantId()); bundle.setCanonicalVersionId(op.world().request().canonicalVersionId()); + bundle.setAttestationSchemaVersion("v2"); bundle.setPublishWorkflowId(op.workflowId()); + bundle.setManifestHash(MANIFEST); bundle.setManifestSchemaVersion(1); bundle.setArtifactDigestsJson("[]"); + bundle.setRequiredManifestAssetKeysJson("[]"); bundle.setCommandDefinitionsJson("[]"); + bundle.setGenerationConfigRevision("generation-1"); + bundle.setParticipantDigestsJson(new ObjectMapper().writeValueAsString(PublishedWorldSelectorFixtures.participants(op.versionId(), op.world()))); + bundle.setWorldPublishedStartLocationEvidenceJson(new String(op.world().canonicalBytes(), StandardCharsets.UTF_8)); + return bundle; + } + + private void rawReleaseInsert(Fixture fixture) { + var bundle = bundle(fixture); + fixture.dsl().execute("INSERT INTO published_release_bundle (tenant_id, version_id, version_number, canonical_tenant_id, canonical_version_id, " + + "published_release_bundle_ref, attestation_schema_version, publish_workflow_id, manifest_hash, generation_config_revision, manifest_schema_version, " + + "artifact_digests_json, required_manifest_asset_keys_json, participant_digests_json, command_definitions_json, script_only, world_published_start_location_evidence_json) " + + "VALUES (?, ?, 1, ?, ?, ?, 'v2', ?, ?, ?, 1, '[]', '[]', ?, '[]', FALSE, ?)", bundle.getTenantId(), bundle.getVersionId(), + bundle.getCanonicalTenantId(), bundle.getCanonicalVersionId(), UUID.randomUUID().toString(), bundle.getPublishWorkflowId(), MANIFEST, + bundle.getGenerationConfigRevision(), bundle.getParticipantDigestsJson(), bundle.getWorldPublishedStartLocationEvidenceJson()); + } + + private Fixture fixture() throws Exception { + String schema = "gd_pub_op_" + UUID.randomUUID().toString().replace("-", ""); + var source = new DriverManagerDataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway.configure().dataSource(source).schemas(schema).defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations("classpath:db/migration").table("flyway_schema_history_game_design_service").load().migrate(); + var transactions = new DataSourceTransactionManager(source); + var write = new TransactionTemplate(transactions); write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var configuration = new org.jooq.impl.DefaultConfiguration(); + configuration.set(SQLDialect.POSTGRES); + configuration.set(new org.jooq.impl.DataSourceConnectionProvider(new TransactionAwareDataSourceProxy(source))); + configuration.set(new org.springframework.boot.jooq.autoconfigure.SpringTransactionProvider(transactions)); + var dsl = DSL.using(configuration); + var games = new GameRepository(dsl); + var properties = new PostgresProperties(); properties.setSchema(schema); + var versions = new VersionRepository(dsl, properties); + Game game = write.execute(status -> { var requested = new Game(); requested.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); requested.setName("ISOLATED publication owner"); return games.save(requested); }); + Version version = write.execute(status -> { var requested = new Version(); requested.setTenantId(game.getTenantId()); requested.setVersionNumber(1); return versions.save(requested); }); + var target = new TargetProof(version.getCanonicalTenantId(), version.getCanonicalVersionId(), version.getId(), version.getTenantId(), + version.getIdentitySourceGameRowId(), version.getIdentitySourceGameTenantKey(), version.getIdentitySourceProvenanceKind()); + var operation = write.execute(status -> { + try { return IsolatedPublicationOwnerSetup.retain(dsl, target, version.getVersionStateEpoch()); } + catch (Exception failure) { throw new IllegalStateException(failure); } + }); + var operations = new GameDesignPublicationOperationRepository(dsl); + return new Fixture(dsl, write, versions, new PublishAttemptRepository(dsl), new PublishedReleaseBundleRepository(dsl), + new VersionAssetArtifactRepository(dsl), operations, new GameDesignPublicationOperationService(operations, transactions), operation); + } + + private static void await(CountDownLatch latch) { + try { if (!latch.await(10, TimeUnit.SECONDS)) throw new IllegalStateException("ISOLATED barrier timed out"); } + catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw new IllegalStateException(interrupted); } + } + private record Fixture(DSLContext dsl, TransactionTemplate write, VersionRepository versions, PublishAttemptRepository attempts, + PublishedReleaseBundleRepository releases, VersionAssetArtifactRepository artifacts, GameDesignPublicationOperationRepository operations, + GameDesignPublicationOperationService service, GameDesignPublicationOperation operation) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java index 13dc87c86f..55a5302b2a 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java @@ -44,6 +44,7 @@ class PublishedReleaseCanonicalIdentityIntegrationTest { private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); private static final String OTHER_MANIFEST_HASH = "sha256:" + "b".repeat(64); + private static final String GENERATION_CONFIG_REVISION = "generation-1"; private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; private static final MigrationVersion V35 = MigrationVersion.fromVersion("35"); private static final MigrationVersion V35_1 = MigrationVersion.fromVersion("35.1"); @@ -576,9 +577,12 @@ void selectorV2RetainsCompleteOriginalEvidenceAndExactlyReplaysWithoutReplacingR Fixture fixture = fixture(null); Game owner = saveGame(fixture, "selector-release-source"); Version version = saveVersion(fixture, owner); - WorldPublishedStartLocationEvidence evidence = selectorEvidence(version); + var operation = selectorOperation(fixture, version); + WorldPublishedStartLocationEvidence evidence = operation.world(); PublishedReleaseBundle requested = selectorBundle(version, evidence); - PublishedReleaseBundle saved = fixture.releaseBundleRepository().save(requested); + PublishedReleaseBundle saved = fixture.transactionTemplate().execute(status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup.commitStorage( + fixture.dsl(), fixture.versionRepository(), operation, () -> fixture.releaseBundleRepository().save(requested))); String beforeXmin = bundleXmin(fixture.dsl(), saved.getId()); String original = new String(evidence.canonicalBytes(), StandardCharsets.UTF_8); assertThat(saved.getWorldPublishedStartLocationEvidenceJson()).isEqualTo(original); @@ -628,14 +632,17 @@ void concurrentExactSelectorRetriesCommitOneImmutableBundle() throws Exception { Fixture fixture = fixture(null); Game owner = saveGame(fixture, "selector-concurrent-source"); Version version = saveVersion(fixture, owner); - var evidence = selectorEvidence(version); + var operation = selectorOperation(fixture, version); + var evidence = operation.world(); var start = new java.util.concurrent.CountDownLatch(1); try (var executor = java.util.concurrent.Executors.newFixedThreadPool(2)) { java.util.concurrent.Callable save = () -> { start.await(); - return new PublishedReleaseBundleRepository(fixture.dsl()) - .save(selectorBundle(version, evidence)); + return fixture.transactionTemplate().execute(status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup.commitStorage( + fixture.dsl(), fixture.versionRepository(), operation, () -> new PublishedReleaseBundleRepository(fixture.dsl()) + .save(selectorBundle(version, evidence)))); }; var first = executor.submit(save); var second = executor.submit(save); @@ -653,7 +660,8 @@ void sqlGuardRejectsMissingInjectedAndMismatchedSelectorBindingsWithoutAnyReleas Fixture fixture = fixture(null); Game owner = saveGame(fixture, "selector-denial-source"); Version version = saveVersion(fixture, owner); - WorldPublishedStartLocationEvidence evidence = selectorEvidence(version); + var operation = selectorOperation(fixture, version); + WorldPublishedStartLocationEvidence evidence = operation.world(); var json = new ObjectMapper(); String original = new String(evidence.canonicalBytes(), StandardCharsets.UTF_8); String participants = @@ -732,7 +740,12 @@ void sqlGuardRejectsMissingInjectedAndMismatchedSelectorBindingsWithoutAnyReleas fixture, version, "v2", original, json.writeValueAsString(changedParticipants))) .isInstanceOf(DataAccessException.class); assertThat(bundleCount(fixture.dsl())).isZero(); - insertRawSelector(fixture, version, "v2", original, participants); + fixture.transactionTemplate().executeWithoutResult(status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup.commitStorage( + fixture.dsl(), fixture.versionRepository(), operation, () -> { + insertRawSelector(fixture, version, "v2", original, participants); + return fixture.releaseBundleRepository().findByTenantIdAndVersionId(version.getTenantId(), version.getId()).orElseThrow(); + })); assertThat( new PublishedReleaseBundleRepository(fixture.dsl()) .findByTenantIdAndVersionId(version.getTenantId(), version.getId()) @@ -753,6 +766,18 @@ private WorldPublishedStartLocationEvidence selectorEvidence(Version version) th version.getIdentitySourceProvenanceKind())); } + /** ISOLATED upstream sources/freeze; synchronized selection and terminal GD rows are actual DB writes. */ + private net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation selectorOperation( + Fixture fixture, Version version) { + var target = new TargetProof(version.getCanonicalTenantId(), version.getCanonicalVersionId(), version.getId(), version.getTenantId(), + version.getIdentitySourceGameRowId(), version.getIdentitySourceGameTenantKey(), version.getIdentitySourceProvenanceKind()); + return fixture.transactionTemplate().execute(status -> { + try { + return net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup.retain(fixture.dsl(), target, version.getVersionStateEpoch()); + } catch (Exception failure) { throw new IllegalStateException(failure); } + }); + } + private PublishedReleaseBundle selectorBundle( Version version, WorldPublishedStartLocationEvidence evidence) { PublishedReleaseBundle bundle = bundle(version.getTenantId(), version.getId()); @@ -774,16 +799,18 @@ private void insertRawSelector( .execute( "INSERT INTO published_release_bundle (tenant_id, version_id, version_number, " + "canonical_tenant_id, canonical_version_id, published_release_bundle_ref, attestation_schema_version, " - + "publish_workflow_id, manifest_hash, manifest_schema_version, artifact_digests_json, " + + "publish_workflow_id, manifest_hash, generation_config_revision, manifest_schema_version, artifact_digests_json, " + "required_manifest_asset_keys_json, participant_digests_json, command_definitions_json, script_only, " - + "world_published_start_location_evidence_json) VALUES (?, ?, 1, ?, ?, ?, ?, 'publish-workflow', ?, 1, '[]', '[]', ?, '[]', FALSE, ?)", + + "world_published_start_location_evidence_json) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?, ?, 1, '[]', '[]', ?, '[]', FALSE, ?)", version.getTenantId(), version.getId(), version.getCanonicalTenantId(), version.getCanonicalVersionId(), UUID.randomUUID().toString(), schema, + fixture.dsl().fetchOne("SELECT publish_workflow_id FROM game_design_publication_operation WHERE tenant_id = ? AND version_id = ?", version.getTenantId(), version.getId()).get(0, String.class), MANIFEST_HASH, + GENERATION_CONFIG_REVISION, participants, evidence); } @@ -798,6 +825,7 @@ private Fixture fixture(MigrationVersion target) { private Fixture fixtureFromMigratedSchema(String schema, DriverManagerDataSource dataSource) { DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + transactionTemplate.setIsolationLevel(org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); DefaultConfiguration jooqConfiguration = new DefaultConfiguration(); jooqConfiguration.set(SQLDialect.POSTGRES); jooqConfiguration.set( @@ -897,7 +925,7 @@ private PublishedReleaseBundle bundle(String tenantId, Long versionId) { bundle.setManifestHash(MANIFEST_HASH); bundle.setManifestSchemaVersion(1); bundle.setArtifactDigestsJson("[]"); - bundle.setGenerationConfigRevision("generation-1"); + bundle.setGenerationConfigRevision(GENERATION_CONFIG_REVISION); bundle.setRequiredManifestAssetKeysJson("[]"); bundle.setParticipantDigestsJson("[]"); bundle.setCommandDefinitionsJson("[]"); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index 4ec8ffb127..097b16bfe5 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -378,15 +378,8 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth .thenAnswer( invocation -> { VersionDto version = invocation.getArgument(0); - return List.of( - new PublishParticipantDigestDto( - "GAME_DESIGN_CONTROL_PLANE", - String.valueOf(version.id()), - fixture.selection().selectedCommit().commitId().toString(), - "transaction-proof-design-digest", - 1, - null, - null)); + return net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures.participants( + version.id(), fixture.operation().world()); }); Mockito.when(assetExportService.exportAssets(tenantId, 1)) .thenAnswer( @@ -522,15 +515,8 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( VersionDto candidate = invocation.getArgument(0); candidateVersionId.set(candidate.id()); candidateVersionNumber.set(candidate.versionNumber()); - return List.of( - new PublishParticipantDigestDto( - "GAME_DESIGN_CONTROL_PLANE", - String.valueOf(candidate.id()), - fixture.selection().selectedCommit().commitId().toString(), - "failed-remap-design-digest", - 1, - null, - null)); + return net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures.participants( + candidate.id(), fixture.operation().world()); }); Mockito.doAnswer( invocation -> { @@ -689,8 +675,9 @@ private SelectedDraftFixture createSelectedDraftFixture( } /** - * Stipulates synthetic exact selection evidence for the internal transaction-mechanics fixture. - * The repository and current-owner publication-carrier boundary are intentionally not proved. + * ISOLATED upstream source/freeze authority; actual GD synchronized selection and immutable + * operation rows are retained before exercising the real selected finalizer. Runtime authority + * and authenticated upstream production remain unproved. */ private SelectedDraftFixture createSelectedDraftFixture( Game game, int versionNumber, String notes) { @@ -711,76 +698,24 @@ private SelectedDraftFixture createSelectedDraftFixture( game.getId(), game.getTenantId(), "NEW_GAME_ROW"); - String publishRequestId = UUID.randomUUID().toString(); - UUID selectedCommitRequestId = UUID.randomUUID(); - UUID selectedCommitId = UUID.randomUUID(); - List revisions = - java.util.stream.IntStream.range(0, Owner.values().length) - .mapToObj( - index -> - new RevisionPayload( - Integer.toString(index), - UUID.randomUUID(), - Owner.values()[index], - "{\"fixture\":\"transaction-proof\"}")) - .toList(); - List affectedUnits = - java.util.Arrays.stream(Owner.values()) - .map( - owner -> - new AffectedUnit( - owner, - "VERSION", - savedVersion.getCanonicalVersionId().toString(), - "VERSION", - savedVersion.getCanonicalVersionId().toString(), - "1")) - .toList(); - DraftCommitBinding selectedCommit = - DraftCommitBinding.create( - target, - selectedCommitRequestId, - selectedCommitId, - UUID.randomUUID().toString(), - revisions, - affectedUnits); - PublishIntent intent = - new PublishIntent( - game.getCanonicalTenantId(), - savedVersion.getCanonicalVersionId(), - publishRequestId, - savedVersion.getVersionStateEpoch().toString(), - notes, - selectedCommitRequestId, - selectedCommitId, - selectedCommit.digest()); - VisibilityFence visibilityFence = - new VisibilityFence( - target, - selectedCommitRequestId, - selectedCommitId, - selectedCommit.digest(), - "[]", - OffsetDateTime.now(ZoneOffset.UTC)); - AuthoredDraftPublishSelection selection = - AuthoredDraftPublishSelection.capture( - intent, target, new PublicationEvidence(selectedCommit, visibilityFence)); + var operation = publishAttemptService.executeFullVersionTransaction(() -> { + try { + return net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup.retain( + dsl, target, savedVersion.getVersionStateEpoch(), notes); + } catch (Exception failure) { throw new IllegalStateException(failure); } + }); + var retained = operation.account().input().selection(); + AuthoredDraftPublishSelection selection = AuthoredDraftPublishSelection.fromStored(retained.canonicalJson(), retained.digest()); + String publishRequestId = selection.intent().publishRequestId(); Mockito.when( authoredSelectionRepository.readByPublishRequest( game.getCanonicalTenantId(), publishRequestId)) .thenReturn( Optional.of(new SelectionSnapshot(selection, OffsetDateTime.now(ZoneOffset.UTC)))); - String workflowId = - FiremudWorkflowIds.workflowId( - TemporalVersionPublishWorkflow.WORKFLOW_FAMILY, - game.getCanonicalTenantId().toString(), - "publish-request", - publishRequestId); - publishAttemptService.createFullVersionAttempt( - versionMapper.toDto(savedVersion), workflowId, selection.digest()); + String workflowId = operation.workflowId(); return new SelectedDraftFixture( - game.getTenantId(), notes, publishRequestId, workflowId, savedVersion, selection); + game.getTenantId(), notes, publishRequestId, workflowId, savedVersion, selection, operation); } private Object invokeSelectedPublicationMechanics(SelectedDraftFixture fixture) { @@ -825,7 +760,8 @@ private record SelectedDraftFixture( String publishRequestId, String publishWorkflowId, Version version, - AuthoredDraftPublishSelection selection) {} + AuthoredDraftPublishSelection selection, + net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation operation) {} private static String firstStackFrame(Throwable failure) { if (failure == null || failure.getStackTrace().length == 0) { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationMinioPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationMinioPostgresIntegrationTest.java index d86435441e..85a896b5a8 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationMinioPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationMinioPostgresIntegrationTest.java @@ -421,6 +421,8 @@ private Fixture fixtureFromSchema(String schema, DriverManagerDataSource dataSou VersionAssetExportCandidateServiceImpl candidateService = new VersionAssetExportCandidateServiceImpl( versionRepository, + gameRepository, + new net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository(dsl), artifactRepository, publicationService, transactionManager, diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceIntegrationTest.java index ed3d16b785..e3b50149a6 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceIntegrationTest.java @@ -96,6 +96,7 @@ void durableCandidateIsSnapshotBoundRetryableAndIncludesManifestAndBinaryProofs( .contains("artifacts/sha256/", "manifests/sha256/", candidate.manifestHash()); VersionAssetExportCandidateServiceImpl restartedService = candidateService( + fixture.dsl(), fixture.versionRepository(), fixture.artifactRepository(), fixture.publicationService(), @@ -222,6 +223,7 @@ void retainedNullCandidateFieldsRemainAbsentAcrossV38WithoutReadInference() { migrate(fixture.dataSource(), fixture.schema(), V38); VersionAssetExportCandidateServiceImpl candidateService = candidateService( + fixture.dsl(), fixture.versionRepository(), fixture.artifactRepository(), fixture.publicationService(), @@ -442,16 +444,19 @@ private Fixture fixtureFromSchema(String schema, DriverManagerDataSource dataSou publicationService, artifactRepository, candidateService( - versionRepository, artifactRepository, publicationService, transactionManager)); + dsl, versionRepository, artifactRepository, publicationService, transactionManager)); } private VersionAssetExportCandidateServiceImpl candidateService( + DSLContext dsl, VersionRepository versionRepository, VersionAssetArtifactRepository artifactRepository, VersionAssetPublicationServiceImpl publicationService, PlatformTransactionManager transactionManager) { return new VersionAssetExportCandidateServiceImpl( versionRepository, + new GameRepository(dsl), + new net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository(dsl), artifactRepository, publicationService, transactionManager, diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionTest.java index 1814a0320d..636291f6cd 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionTest.java @@ -11,6 +11,11 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import java.util.Map; +import tools.jackson.databind.ObjectMapper; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.PublicationEvidence; @@ -21,7 +26,7 @@ class AuthoredDraftPublishSelectionTest { private static final String LARGE_COUNTER = "900719925474099312345678901234567890"; @Test - void selectionRetainsExactIntentFullCommitAndSynchronizedEvidence() { + void selectionRetainsExactIntentFullCommitAndSynchronizedEvidence() throws Exception { TargetProof target = target(); DraftCommitBinding binding = binding(target); VisibilityFence fence = @@ -68,6 +73,31 @@ void selectionRetainsExactIntentFullCommitAndSynchronizedEvidence() { assertThat(restored.selectedCommit().canonicalJson()).isEqualTo(binding.canonicalJson()); assertThat(restored.fenceResultVectorJson()).isEqualTo(fence.resultVectorJson()); assertThat(restored.fenceCreatedAt()).isEqualTo("2026-10-05T00:00:00Z"); + // Independent original V43 object layout. Extraction must preserve its exact bytes/digest. + byte[] legacy = Rfc8785CanonicalJson.canonicalizeUtf8(new ObjectMapper().writeValueAsString( + Map.of("schemaVersion", "1", + "intent", Map.of("canonicalTenantId", intent.canonicalTenantId().toString(), + "canonicalVersionId", intent.canonicalVersionId().toString(), + "publishRequestId", intent.publishRequestId(), + "expectedVersionStateEpoch", intent.expectedVersionStateEpoch(), + "notes", intent.notes(), "selectedCommitRequestId", intent.selectedCommitRequestId().toString(), + "selectedCommitId", intent.selectedCommitId().toString(), + "selectedCommitDigest", intent.selectedCommitDigest()), + "target", Map.of("canonicalTenantId", target.canonicalTenantId().toString(), + "canonicalVersionId", target.canonicalVersionId().toString(), + "gameDesignVersionRowId", Long.toString(target.gameDesignVersionRowId()), + "gameDesignVersionTenantKey", target.gameDesignVersionTenantKey(), + "sourceGameRowId", Long.toString(target.sourceGameRowId()), + "sourceGameTenantKey", target.sourceGameTenantKey(), + "sourceProvenanceKind", target.sourceProvenanceKind()), + "selectedCommitBindingJson", binding.canonicalJson(), "selectedCommitDigest", binding.digest(), + "synchronizedFence", Map.of("requestId", fence.requestId().toString(), + "commitId", fence.commitId().toString(), "inputDigest", fence.inputDigest(), + "resultVectorJson", fence.resultVectorJson(), "createdAt", "2026-10-05T00:00:00Z")))); + assertThat(selection.canonicalBytes()).containsExactly(legacy); + assertThat(selection.digest()).isEqualTo(DraftAuthorizationFenceBinding.digest(legacy)); + var shared = AuthoredDraftPublishSelectionBinding.fromStored(selection.canonicalJson(), selection.digest()); + assertThat(shared.canonicalBytes()).containsExactly(legacy); } @Test diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationTest.java new file mode 100644 index 0000000000..76a5fabc5e --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationTest.java @@ -0,0 +1,69 @@ +package unit.net.firedevops.firemud.gamedesign.publication; + +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.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import org.junit.jupiter.api.Test; + +class GameDesignPublicationOperationTest { + @Test + void exactCodecPreservesDistinctAccountOperationCompleteSelectionAndOriginalWorldBytes() throws Exception { + var operation = fixture(); + var restored = GameDesignPublicationOperation.fromStored(operation.canonicalBytes()); + assertThat(restored.canonicalBytes()).isEqualTo(operation.canonicalBytes()); + assertThat(restored.account().canonicalBytes()).isEqualTo(operation.account().canonicalBytes()); + assertThat(restored.world().canonicalBytes()).isEqualTo(operation.world().canonicalBytes()); + assertThat(restored.selectionDigest()).isEqualTo("sha256:" + restored.world().request().requestDigest()); + GameDesignPublicationOperationRepository.exact(operation, restored); + } + + @Test + void changedAccountAllocationAndWorldFenceConflictInsteadOfReplacingOriginalOperation() throws Exception { + var operation = fixture(); + var account = operation.account(); + var changedAccount = new GameDesignPublicationOperation(new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), account.fenceId(), account.input(), account.sources()), operation.world()); + assertThatThrownBy(() -> GameDesignPublicationOperationRepository.exact(operation, changedAccount)) + .isInstanceOf(IllegalArgumentException.class); + var original = operation.world(); + var request = original.request(); + var changedWorld = new GameDesignPublicationOperation(account, new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request(request.targetNamespace(), request.canonicalTenantId(), request.canonicalVersionId(), + request.intakeRequestId(), UUID.randomUUID(), request.publicationRequestId(), request.requestDigest(), request.versionStateEpoch(), + request.publishWorkflowId(), request.appliedCommitId(), request.contentDigest(), request.digestSchemaVersion(), request.worldAffectedTuples()), + original.selectorReceiptBytes(), original.originalAccountBindingBytes(), original.appliedResultBytes())); + assertThatThrownBy(() -> GameDesignPublicationOperationRepository.exact(operation, changedWorld)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void changedWorkflowOrSelectionDigestCannotConstructOwnerOperation() throws Exception { + var operation = fixture(); + var original = operation.world(); + var request = original.request(); + assertThatThrownBy(() -> new GameDesignPublicationOperation(operation.account(), new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request(request.targetNamespace(), request.canonicalTenantId(), request.canonicalVersionId(), + request.intakeRequestId(), request.publicationFence(), request.publicationRequestId(), "f".repeat(64), request.versionStateEpoch(), + request.publishWorkflowId(), request.appliedCommitId(), request.contentDigest(), request.digestSchemaVersion(), request.worldAffectedTuples()), + original.selectorReceiptBytes(), original.originalAccountBindingBytes(), original.appliedResultBytes()))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new GameDesignPublicationOperation(operation.account(), new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request(request.targetNamespace(), request.canonicalTenantId(), request.canonicalVersionId(), + request.intakeRequestId(), request.publicationFence(), request.publicationRequestId(), request.requestDigest(), request.versionStateEpoch(), + "changed-workflow", request.appliedCommitId(), request.contentDigest(), request.digestSchemaVersion(), request.worldAffectedTuples()), + original.selectorReceiptBytes(), original.originalAccountBindingBytes(), original.appliedResultBytes()))) + .isInstanceOf(IllegalArgumentException.class); + } + + private GameDesignPublicationOperation fixture() throws Exception { + return IsolatedPublicationOperationFixtures.fresh(new TargetProof(UUID.randomUUID(), UUID.randomUUID(), 7L, + "ISOLATED-tenant", 3L, "ISOLATED-tenant", "NEW_GAME_ROW")); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepositoryTest.java index f3b11f2c2d..6c0e5f50d8 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepositoryTest.java @@ -24,7 +24,7 @@ void saveReturnsInsertedAttemptAndMatchesIndependentReadback() throws Exception "CREATE TABLE publish_attempt (" + "id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, " + "tenant_id VARCHAR(36) NOT NULL, publish_workflow_id VARCHAR(64) NOT NULL, " - + "publish_type VARCHAR(32) NOT NULL, status VARCHAR(16) NOT NULL, " + + "publish_type VARCHAR(32) NOT NULL, status VARCHAR(16) NOT NULL, revision BIGINT NOT NULL DEFAULT 1, " + "version_id BIGINT, version_number INT NOT NULL, " + "script_patch_version VARCHAR(100), base_version_id BIGINT, " + "request_digest VARCHAR(128), failure_code VARCHAR(64), " diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java index 6a32d4dead..f46b8c1578 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java @@ -47,6 +47,8 @@ class VersionAssetExportCandidateServiceImplTest { UUID.fromString("8b0c1a0f-b8c9-4c4b-9021-381f57699002"); @Mock private VersionRepository versionRepository; + @Mock private net.firedevops.firemud.gamedesign.repository.GameRepository gameRepository; + @Mock private net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository attemptRepository; @Mock private VersionAssetArtifactRepository artifactRepository; @Mock private VersionAssetPublicationService publicationService; @Mock private PlatformTransactionManager transactionManager; @@ -59,6 +61,8 @@ class VersionAssetExportCandidateServiceImplTest { @BeforeEach void setUp() { + lenient().when(gameRepository.findByTenantIdForUpdate(TENANT_ID)) + .thenReturn(new net.firedevops.firemud.gamedesign.entity.Game()); TransactionStatus transactionStatus = new SimpleTransactionStatus(); when(transactionManager.getTransaction(any(TransactionDefinition.class))) .thenReturn(transactionStatus); @@ -94,6 +98,8 @@ void setUp() { service = new VersionAssetExportCandidateServiceImpl( versionRepository, + gameRepository, + attemptRepository, artifactRepository, publicationService, transactionManager, diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index 564aa6b094..b13fb6ebc1 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -346,6 +346,8 @@ private record SelectorReadback( @BeforeEach void setup() { MockitoAnnotations.openMocks(this); + when(publishAttemptRepository.findByPublishWorkflowIdForUpdate(any(String.class))) + .thenAnswer(invocation -> publishAttemptRepository.findByPublishWorkflowId(invocation.getArgument(0))); when(publishedReleaseBundleService.findPublishedReleaseBundle( any(String.class), any(Long.class))) .thenReturn(Optional.empty()); @@ -461,7 +463,8 @@ void finalizeFullVersionUsesSelectedExistingDraftAndFiveMatchingParticipantCommi any(String.class), any(ExportedAssetManifest.class), any(String.class), - any(List.class))) + any(List.class), + org.mockito.ArgumentMatchers.nullable(WorldPublishedStartLocationEvidence.class))) .thenReturn( new PublishedReleaseBundleDto( 1L, @@ -573,6 +576,8 @@ void internalSelectedFinalizationPreservesTypedGateFailureBeforeWrites() { .recordFullVersionParticipantDigests(any(String.class), any(List.class)); verify(publishedReleaseBundleService, never()) .createFullVersionBundle(any(), any(), any(), any(), any()); + verify(publishedReleaseBundleService, never()) + .createFullVersionBundle(any(), any(), any(), any(), any(), any()); verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); } @@ -634,6 +639,8 @@ void internalSelectedFinalizationRejectsOneParticipantOnAnotherCommitBeforeWrite verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); verify(publishedReleaseBundleService, never()) .createFullVersionBundle(any(), any(), any(), any(), any()); + verify(publishedReleaseBundleService, never()) + .createFullVersionBundle(any(), any(), any(), any(), any(), any()); } @Test @@ -692,7 +699,8 @@ void internalSelectedFinalizationBundleFailureLeavesAttemptPendingAndRetainsCand any(String.class), any(ExportedAssetManifest.class), any(String.class), - any(List.class)); + any(List.class), + org.mockito.ArgumentMatchers.nullable(WorldPublishedStartLocationEvidence.class)); assertThrows( IllegalStateException.class, @@ -1318,7 +1326,8 @@ void postBundleFailureAfterRollbackMarksFailureAndRetainsExportedAssets() { any(String.class), any(ExportedAssetManifest.class), any(String.class), - any(List.class))) + any(List.class), + org.mockito.ArgumentMatchers.nullable(WorldPublishedStartLocationEvidence.class))) .thenReturn(bundle); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.empty()); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java index e9f204c8f4..f493d154e9 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java @@ -10,6 +10,7 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.world.RoomTemplateRef; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; @@ -297,8 +298,7 @@ private void requireInputIdentity( requireText(source, "receiptDigest", binding.sourceIntakeReceipt().receiptDigest()); requireText(source, "requestDigest", binding.sourceIntakeReceipt().requestDigest()); requireInteger(source, "localTenantKey", binding.sourceIntakeReceipt().localTenantKey()); - requireText( - source, "sourceEvidence", writeClosedEvidenceJson(binding.sourceIntakeReceipt().source())); + requireSourceEvidenceObject(source, binding.sourceIntakeReceipt().source()); JsonNode topology = requiredObject(input, "topology"); requireText(topology, "captureId", captureId.toString()); @@ -507,6 +507,38 @@ private static void requireFields(JsonNode value, Set expected, String l if (!actual.equals(expected)) throw invalid(label + " has missing or unsupported fields"); } + private static void requireSourceEvidenceObject( + JsonNode retained, AuthoredWorldSourceEvidence evidence) { + JsonNode actual = requiredObject(retained, "sourceEvidence"); + Set fields = + Set.of( + "schemaVersion", + "registrationRequestId", + "sourceOperationId", + "requestDigest", + "canonicalTenantId", + "tenantSlug", + "worldSlug", + "worldDisplayName", + "sourceGameRowId", + "sourceGameTenantKey", + "provenanceKind", + "evidenceDigest"); + requireFields(actual, fields, "Retained World source evidence"); + requireInteger(actual, "schemaVersion", evidence.schemaVersion()); + requireText(actual, "registrationRequestId", evidence.registrationRequestId().toString()); + requireText(actual, "sourceOperationId", evidence.operationId().toString()); + requireText(actual, "requestDigest", evidence.requestDigest()); + requireText(actual, "canonicalTenantId", evidence.canonicalTenantId().toString()); + requireText(actual, "tenantSlug", evidence.tenantSlug()); + requireText(actual, "worldSlug", evidence.worldSlug()); + requireText(actual, "worldDisplayName", evidence.worldDisplayName()); + requireInteger(actual, "sourceGameRowId", evidence.sourceGameRowId()); + requireText(actual, "sourceGameTenantKey", evidence.sourceGameTenantKey()); + requireText(actual, "provenanceKind", evidence.provenanceKind()); + requireText(actual, "evidenceDigest", evidence.evidenceDigest()); + } + private static JsonNode requiredObject(JsonNode parent, String field) { JsonNode value = parent.get(field); if (value == null || !value.isObject()) throw invalid(field + " must be an object"); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 7db8596706..bf1e7b0ffb 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -178,7 +178,7 @@ void releaseSelectorMaterializesItsOriginalRoomAndExactlyRetriesWithSeparateRunt var mapped = Objects.requireNonNull( dsl.fetchOne( - "SELECT m.template_id,r.room_instance_id FROM world_canonical_instance_topology_identity m " + "SELECT m.template_id,r.room_instance_row_id AS room_instance_id FROM world_canonical_instance_topology_identity m " + "JOIN room_instance r ON r.id=m.runtime_row_id WHERE m.world_instance_id=? AND m.family='ROOM' AND m.template_id=?", result.association().worldInstanceId(), lastRoom)); From a3a98b53bc005974047474ec60fc8addab2dabe2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 05:46:55 +1300 Subject: [PATCH 05/13] Correct publication owner fixtures and canonical formatting --- .../draft/AuthoredDraftPublishSelection.java | 124 ++++-- .../GameDesignPublicationOperation.java | 42 +- ...eDesignPublicationOperationRepository.java | 103 +++-- ...GameDesignPublicationOperationService.java | 32 +- .../repository/PublishAttemptRepository.java | 73 ++-- .../impl/PublishAttemptServiceImpl.java | 9 +- ...ersionAssetExportCandidateServiceImpl.java | 18 +- .../draft/IsolatedPublicationOwnerSetup.java | 126 ++++-- .../IsolatedPublicationOperationFixtures.java | 165 ++++++-- ...ationOperationPostgresIntegrationTest.java | 360 +++++++++++++----- ...leaseCanonicalIdentityIntegrationTest.java | 103 +++-- ...emptServiceTransactionIntegrationTest.java | 43 ++- .../AuthoredDraftPublishSelectionTest.java | 89 +++-- .../GameDesignPublicationOperationTest.java | 113 ++++-- ...ectedAuthoredDraftPublishWorkflowTest.java | 5 +- ...onAssetExportCandidateServiceImplTest.java | 8 +- .../VersionPublishCommandServiceImplTest.java | 4 +- 17 files changed, 1042 insertions(+), 375 deletions(-) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelection.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelection.java index 32feeec605..94ec38dc56 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelection.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelection.java @@ -9,7 +9,8 @@ /** * Exact existing synchronized Draft selection. The shared codec preserves the original V43 bytes - * and digest; neither this retained selection nor codec validation establishes publication authority. + * and digest; neither this retained selection nor codec validation establishes publication + * authority. */ public final class AuthoredDraftPublishSelection { private final AuthoredDraftPublishSelectionBinding binding; @@ -24,10 +25,16 @@ public static AuthoredDraftPublishSelection capture( var fence = evidence.visibilityFence(); return new AuthoredDraftPublishSelection( AuthoredDraftPublishSelectionBinding.capture( - sharedIntent(intent), target, evidence.binding(), + sharedIntent(intent), + target, + evidence.binding(), new AuthoredDraftPublishSelectionBinding.VisibilityFence( - fence.target(), fence.requestId(), fence.commitId(), fence.inputDigest(), - fence.resultVectorJson(), fence.createdAt()))); + fence.target(), + fence.requestId(), + fence.commitId(), + fence.inputDigest(), + fence.resultVectorJson(), + fence.createdAt()))); } public static AuthoredDraftPublishSelection fromStored(String storedJson, String storedDigest) { @@ -37,48 +44,103 @@ public static AuthoredDraftPublishSelection fromStored(String storedJson, String public PublishIntent intent() { var intent = binding.intent(); - return new PublishIntent(intent.canonicalTenantId(), intent.canonicalVersionId(), - intent.publishRequestId(), intent.expectedVersionStateEpoch(), intent.notes(), - intent.selectedCommitRequestId(), intent.selectedCommitId(), intent.selectedCommitDigest()); - } - - public TargetProof target() { return binding.target(); } - public DraftCommitBinding selectedCommit() { return binding.selectedCommit(); } - public UUID fenceRequestId() { return binding.fenceRequestId(); } - public UUID fenceCommitId() { return binding.fenceCommitId(); } - public String fenceInputDigest() { return binding.fenceInputDigest(); } - public String fenceResultVectorJson() { return binding.fenceResultVectorJson(); } - public String fenceCreatedAt() { return binding.fenceCreatedAt(); } - public String canonicalJson() { return binding.canonicalJson(); } - public byte[] canonicalBytes() { return binding.canonicalBytes(); } - public String digest() { return binding.digest(); } + return new PublishIntent( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + intent.expectedVersionStateEpoch(), + intent.notes(), + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()); + } + + public TargetProof target() { + return binding.target(); + } + + public DraftCommitBinding selectedCommit() { + return binding.selectedCommit(); + } + + public UUID fenceRequestId() { + return binding.fenceRequestId(); + } + + public UUID fenceCommitId() { + return binding.fenceCommitId(); + } + + public String fenceInputDigest() { + return binding.fenceInputDigest(); + } + + public String fenceResultVectorJson() { + return binding.fenceResultVectorJson(); + } + + public String fenceCreatedAt() { + return binding.fenceCreatedAt(); + } + + public String canonicalJson() { + return binding.canonicalJson(); + } + + public byte[] canonicalBytes() { + return binding.canonicalBytes(); + } + + public String digest() { + return binding.digest(); + } @Override public boolean equals(Object other) { - return this == other || (other instanceof AuthoredDraftPublishSelection selection - && binding.equals(selection.binding)); + return this == other + || (other instanceof AuthoredDraftPublishSelection selection + && binding.equals(selection.binding)); } @Override - public int hashCode() { return binding.hashCode(); } + public int hashCode() { + return binding.hashCode(); + } - private static AuthoredDraftPublishSelectionBinding.PublishIntent sharedIntent(PublishIntent intent) { + private static AuthoredDraftPublishSelectionBinding.PublishIntent sharedIntent( + PublishIntent intent) { Objects.requireNonNull(intent, "intent"); return new AuthoredDraftPublishSelectionBinding.PublishIntent( - intent.canonicalTenantId(), intent.canonicalVersionId(), intent.publishRequestId(), - intent.expectedVersionStateEpoch(), intent.notes(), intent.selectedCommitRequestId(), - intent.selectedCommitId(), intent.selectedCommitDigest()); + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + intent.expectedVersionStateEpoch(), + intent.notes(), + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()); } /** Full original eight caller inputs, retaining the existing public API. */ public record PublishIntent( - UUID canonicalTenantId, UUID canonicalVersionId, String publishRequestId, - String expectedVersionStateEpoch, String notes, UUID selectedCommitRequestId, - UUID selectedCommitId, String selectedCommitDigest) { + UUID canonicalTenantId, + UUID canonicalVersionId, + String publishRequestId, + String expectedVersionStateEpoch, + String notes, + UUID selectedCommitRequestId, + UUID selectedCommitId, + String selectedCommitDigest) { public PublishIntent { new AuthoredDraftPublishSelectionBinding.PublishIntent( - canonicalTenantId, canonicalVersionId, publishRequestId, expectedVersionStateEpoch, - notes, selectedCommitRequestId, selectedCommitId, selectedCommitDigest); + canonicalTenantId, + canonicalVersionId, + publishRequestId, + expectedVersionStateEpoch, + notes, + selectedCommitRequestId, + selectedCommitId, + selectedCommitDigest); } } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperation.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperation.java index 214da466b3..4832a86662 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperation.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperation.java @@ -5,13 +5,12 @@ import java.util.Objects; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; -import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; /** Closed original operation input. Codec validation supplies integrity, never authorization. */ public record GameDesignPublicationOperation( - AccountPublicationAuthorizationBinding account, - WorldPublishedStartLocationEvidence world) { + AccountPublicationAuthorizationBinding account, WorldPublishedStartLocationEvidence world) { public static final String SCHEMA = "game-design-publication-operation/v1"; public GameDesignPublicationOperation { @@ -28,12 +27,15 @@ public record GameDesignPublicationOperation( || !selection.digest().equals("sha256:" + freeze.requestDigest()) || !intent.expectedVersionStateEpoch().equals(Long.toString(freeze.versionStateEpoch())) || !intent.selectedCommitId().toString().equals(freeze.appliedCommitId()) - || !Arrays.equals(selection.selectedCommit().canonicalBytes(), - DraftAuthorizationFenceBinding.fromStored(world.originalAccountBindingBytes()).normalizedInput())) { + || !Arrays.equals( + selection.selectedCommit().canonicalBytes(), + DraftAuthorizationFenceBinding.fromStored(world.originalAccountBindingBytes()) + .normalizedInput())) { throw new IllegalArgumentException("PUBLICATION_OPERATION_IDENTITY_CONFLICT"); } - String workflow = FiremudWorkflowIds.workflowId("publish", account.tenantId().toString(), - "publish-request", intent.publishRequestId()); + String workflow = + FiremudWorkflowIds.workflowId( + "publish", account.tenantId().toString(), "publish-request", intent.publishRequestId()); if (!workflow.equals(freeze.publishWorkflowId())) { throw new IllegalArgumentException("PUBLICATION_OPERATION_WORKFLOW_CONFLICT"); } @@ -50,9 +52,10 @@ public byte[] canonicalBytes() { public static GameDesignPublicationOperation fromStored(byte[] bytes) { var reader = new DraftAuthorizationFenceBinding.FrameReader(bytes); reader.expect(SCHEMA); - var operation = new GameDesignPublicationOperation( - AccountPublicationAuthorizationBinding.fromStored(reader.bytes()), - WorldPublishedStartLocationEvidence.fromStored(reader.bytes())); + var operation = + new GameDesignPublicationOperation( + AccountPublicationAuthorizationBinding.fromStored(reader.bytes()), + WorldPublishedStartLocationEvidence.fromStored(reader.bytes())); reader.requireEnd(); if (!Arrays.equals(bytes, operation.canonicalBytes())) { throw new IllegalArgumentException("Noncanonical publication operation"); @@ -60,8 +63,19 @@ public static GameDesignPublicationOperation fromStored(byte[] bytes) { return operation; } - public String workflowId() { return world.request().publishWorkflowId(); } - public String tenantKey() { return account.input().selection().target().gameDesignVersionTenantKey(); } - public long versionId() { return account.input().selection().target().gameDesignVersionRowId(); } - public String selectionDigest() { return account.input().selection().digest(); } + public String workflowId() { + return world.request().publishWorkflowId(); + } + + public String tenantKey() { + return account.input().selection().target().gameDesignVersionTenantKey(); + } + + public long versionId() { + return account.input().selection().target().gameDesignVersionRowId(); + } + + public String selectionDigest() { + return account.input().selection().digest(); + } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java index b9d89f9dfd..5f1e20c4fe 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java @@ -17,7 +17,9 @@ public final class GameDesignPublicationOperationRepository { private final DSLContext dsl; - public GameDesignPublicationOperationRepository(DSLContext dsl) { this.dsl = Objects.requireNonNull(dsl); } + public GameDesignPublicationOperationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } public void reserve(GameDesignPublicationOperation operation) { requireTransaction(); @@ -27,18 +29,28 @@ public void reserve(GameDesignPublicationOperation operation) { exact(existing.get().operation(), operation); return; } - dsl.execute("INSERT INTO game_design_publication_operation " - + "(publish_workflow_id, tenant_id, version_id, selection_digest, request_bytes) VALUES (?, ?, ?, ?, ?)", - operation.workflowId(), operation.tenantKey(), operation.versionId(), operation.selectionDigest(), operation.canonicalBytes()); + dsl.execute( + "INSERT INTO game_design_publication_operation " + + "(publish_workflow_id, tenant_id, version_id, selection_digest, request_bytes) VALUES (?, ?, ?, ?, ?)", + operation.workflowId(), + operation.tenantKey(), + operation.versionId(), + operation.selectionDigest(), + operation.canonicalBytes()); } - public GameDesignPublicationOperation requirePending(String tenant, String workflow, long version, String digest) { + public GameDesignPublicationOperation requirePending( + String tenant, String workflow, long version, String digest) { requireTransaction(); lock(tenant, workflow, version); - Readback result = read(workflow).orElseThrow(() -> new IllegalStateException("PUBLICATION_OPERATION_UNAVAILABLE")); + Readback result = + read(workflow) + .orElseThrow(() -> new IllegalStateException("PUBLICATION_OPERATION_UNAVAILABLE")); var operation = result.operation(); - if (!operation.tenantKey().equals(tenant) || operation.versionId() != version - || !operation.selectionDigest().equals(digest) || !result.outcome().equals("PENDING")) { + if (!operation.tenantKey().equals(tenant) + || operation.versionId() != version + || !operation.selectionDigest().equals(digest) + || !result.outcome().equals("PENDING")) { throw new IllegalStateException("PUBLICATION_OPERATION_SEALED_OR_CHANGED"); } return operation; @@ -46,20 +58,34 @@ public GameDesignPublicationOperation requirePending(String tenant, String workf public void seal(String tenant, String workflow, long version, String digest, boolean published) { GameDesignPublicationOperation operation = requirePending(tenant, workflow, version, digest); - Record release = dsl.fetchOne("SELECT to_jsonb(r)::TEXT AS evidence FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", tenant, version); + Record release = + dsl.fetchOne( + "SELECT to_jsonb(r)::TEXT AS evidence FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", + tenant, + version); String evidence = release == null ? null : release.get("evidence", String.class); - if (published != (evidence != null)) throw new IllegalStateException("PUBLICATION_READBACK_UNRESOLVED"); + if (published != (evidence != null)) + throw new IllegalStateException("PUBLICATION_READBACK_UNRESOLVED"); String outcome = published ? "PUBLISHED" : "NO_PUBLICATION"; byte[] result = receipt(operation, outcome, evidence); - int changed = dsl.execute("UPDATE game_design_publication_operation SET outcome = ?, result_bytes = ?, release_row_json = ?, revision = revision + 1 WHERE publish_workflow_id = ? AND outcome = 'PENDING' AND revision = 1", - outcome, result, evidence, workflow); + int changed = + dsl.execute( + "UPDATE game_design_publication_operation SET outcome = ?, result_bytes = ?, release_row_json = ?, revision = revision + 1 WHERE publish_workflow_id = ? AND outcome = 'PENDING' AND revision = 1", + outcome, + result, + evidence, + workflow); if (changed != 1) throw new IllegalStateException("PUBLICATION_OPERATION_CAS_CONFLICT"); } public Optional read(String workflow) { - Record row = dsl.fetchOne("SELECT * FROM game_design_publication_operation WHERE publish_workflow_id = ?", workflow); + Record row = + dsl.fetchOne( + "SELECT * FROM game_design_publication_operation WHERE publish_workflow_id = ?", + workflow); if (row == null) return Optional.empty(); - var operation = GameDesignPublicationOperation.fromStored(row.get("request_bytes", byte[].class)); + var operation = + GameDesignPublicationOperation.fromStored(row.get("request_bytes", byte[].class)); String outcome = row.get("outcome", String.class); byte[] bytes = row.get("result_bytes", byte[].class); String evidence = row.get("release_row_json", String.class); @@ -70,13 +96,20 @@ public Optional read(String workflow) { throw new IllegalStateException("PUBLICATION_OPERATION_STORAGE_CONFLICT"); } if (!"PENDING".equals(outcome)) { - if (!Arrays.equals(bytes, receipt(operation, outcome, evidence))) throw new IllegalStateException("PUBLICATION_RECEIPT_CORRUPT"); - Record release = dsl.fetchOne("SELECT to_jsonb(r)::TEXT AS evidence FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", operation.tenantKey(), operation.versionId()); + if (!Arrays.equals(bytes, receipt(operation, outcome, evidence))) + throw new IllegalStateException("PUBLICATION_RECEIPT_CORRUPT"); + Record release = + dsl.fetchOne( + "SELECT to_jsonb(r)::TEXT AS evidence FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", + operation.tenantKey(), + operation.versionId()); String actual = release == null ? null : release.get("evidence", String.class); if (!Objects.equals(actual, evidence) || ("PUBLISHED".equals(outcome) != (actual != null))) { throw new IllegalStateException("PUBLICATION_RECEIPT_BACKING_CONFLICT"); } - Record attempt = dsl.fetchOne("SELECT status FROM publish_attempt WHERE publish_workflow_id = ?", workflow); + Record attempt = + dsl.fetchOne( + "SELECT status FROM publish_attempt WHERE publish_workflow_id = ?", workflow); if (attempt == null) { throw new IllegalStateException("PUBLICATION_RECEIPT_ATTEMPT_CONFLICT"); } @@ -90,17 +123,27 @@ public Optional read(String workflow) { private void lock(String tenant, String workflow, long version) { if (dsl.fetchOne("SELECT id FROM game WHERE tenant_id = ? FOR UPDATE", tenant) == null - || dsl.fetchOne("SELECT id FROM publish_attempt WHERE tenant_id = ? AND publish_workflow_id = ? AND version_id = ? FOR UPDATE", tenant, workflow, version) == null - || dsl.fetchOne("SELECT id FROM version WHERE tenant_id = ? AND id = ? FOR UPDATE", tenant, version) == null) { + || dsl.fetchOne( + "SELECT id FROM publish_attempt WHERE tenant_id = ? AND publish_workflow_id = ? AND version_id = ? FOR UPDATE", + tenant, + workflow, + version) + == null + || dsl.fetchOne( + "SELECT id FROM version WHERE tenant_id = ? AND id = ? FOR UPDATE", tenant, version) + == null) { throw new IllegalStateException("PUBLICATION_OWNER_IDENTITY_UNAVAILABLE"); } } - public static void exact(GameDesignPublicationOperation retained, GameDesignPublicationOperation requested) { - if (!Arrays.equals(retained.canonicalBytes(), requested.canonicalBytes())) throw new IllegalArgumentException("PUBLICATION_OPERATION_IDENTITY_CONFLICT"); + public static void exact( + GameDesignPublicationOperation retained, GameDesignPublicationOperation requested) { + if (!Arrays.equals(retained.canonicalBytes(), requested.canonicalBytes())) + throw new IllegalArgumentException("PUBLICATION_OPERATION_IDENTITY_CONFLICT"); } - private static byte[] receipt(GameDesignPublicationOperation operation, String outcome, String evidence) { + private static byte[] receipt( + GameDesignPublicationOperation operation, String outcome, String evidence) { var out = new ByteArrayOutputStream(); DraftAuthorizationFenceBinding.frame(out, "game-design-publication-owner-readback/v1"); DraftAuthorizationFenceBinding.frame(out, operation.canonicalBytes()); @@ -110,11 +153,19 @@ private static byte[] receipt(GameDesignPublicationOperation operation, String o } private static void requireTransaction() { - if (!TransactionSynchronizationManager.isActualTransactionActive()) throw new IllegalStateException("Publication owner transaction required"); + if (!TransactionSynchronizationManager.isActualTransactionActive()) + throw new IllegalStateException("Publication owner transaction required"); } - public record Readback(GameDesignPublicationOperation operation, String outcome, byte[] receiptBytes) { - public Readback { receiptBytes = receiptBytes == null ? null : receiptBytes.clone(); } - @Override public byte[] receiptBytes() { return receiptBytes == null ? null : receiptBytes.clone(); } + public record Readback( + GameDesignPublicationOperation operation, String outcome, byte[] receiptBytes) { + public Readback { + receiptBytes = receiptBytes == null ? null : receiptBytes.clone(); + } + + @Override + public byte[] receiptBytes() { + return receiptBytes == null ? null : receiptBytes.clone(); + } } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationService.java index be98a8096e..47fbce59e5 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationService.java @@ -7,13 +7,16 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; -/** Explicit local seam; upstream authentication/current authority must be established separately. */ +/** + * Explicit local seam; upstream authentication/current authority must be established separately. + */ public final class GameDesignPublicationOperationService { private final GameDesignPublicationOperationRepository repository; private final TransactionTemplate write; private final TransactionTemplate read; - public GameDesignPublicationOperationService(GameDesignPublicationOperationRepository repository, + public GameDesignPublicationOperationService( + GameDesignPublicationOperationRepository repository, PlatformTransactionManager transactions) { this.repository = Objects.requireNonNull(repository); write = new TransactionTemplate(transactions); @@ -24,23 +27,32 @@ public GameDesignPublicationOperationService(GameDesignPublicationOperationRepos read.setReadOnly(true); } - public GameDesignPublicationOperationRepository.Readback retainVerifiedOperation(GameDesignPublicationOperation operation) { + public GameDesignPublicationOperationRepository.Readback retainVerifiedOperation( + GameDesignPublicationOperation operation) { requireIndependent(); var retained = readExact(operation); if (retained.isPresent()) return retained.orElseThrow(); write.executeWithoutResult(status -> repository.reserve(operation)); - return readExact(operation).orElseThrow(() -> new IllegalStateException("Publication operation readback absent")); + return readExact(operation) + .orElseThrow(() -> new IllegalStateException("Publication operation readback absent")); } - public Optional readExact(GameDesignPublicationOperation operation) { + public Optional readExact( + GameDesignPublicationOperation operation) { requireIndependent(); - return read.execute(status -> repository.read(operation.workflowId()).map(result -> { - GameDesignPublicationOperationRepository.exact(result.operation(), operation); - return result; - })); + return read.execute( + status -> + repository + .read(operation.workflowId()) + .map( + result -> { + GameDesignPublicationOperationRepository.exact(result.operation(), operation); + return result; + })); } private static void requireIndependent() { - if (TransactionSynchronizationManager.isActualTransactionActive()) throw new IllegalStateException("Independent publication read/write boundary required"); + if (TransactionSynchronizationManager.isActualTransactionActive()) + throw new IllegalStateException("Independent publication read/write boundary required"); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java index e355d85b1b..21fc07fea5 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java @@ -68,18 +68,32 @@ public Optional findByPublishWorkflowIdForUpdate(String workflow Optional initial = findByPublishWorkflowId(workflow); if (initial.isEmpty()) return initial; dsl.fetchOne("SELECT id FROM game WHERE tenant_id = ? FOR UPDATE", initial.get().getTenantId()); - return Optional.ofNullable(dsl.selectFrom(PUBLISH_ATTEMPT_TABLE) - .where(PUBLISH_WORKFLOW_ID.eq(workflow)).forUpdate().fetchOne(this::toEntity)); + return Optional.ofNullable( + dsl.selectFrom(PUBLISH_ATTEMPT_TABLE) + .where(PUBLISH_WORKFLOW_ID.eq(workflow)) + .forUpdate() + .fetchOne(this::toEntity)); } - public net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence requirePublicationPending(PublishAttempt attempt) { - return new GameDesignPublicationOperationRepository(dsl).requirePending(attempt.getTenantId(), - attempt.getPublishWorkflowId(), attempt.getVersionId(), attempt.getRequestDigest()).world(); + public net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence + requirePublicationPending(PublishAttempt attempt) { + return new GameDesignPublicationOperationRepository(dsl) + .requirePending( + attempt.getTenantId(), + attempt.getPublishWorkflowId(), + attempt.getVersionId(), + attempt.getRequestDigest()) + .world(); } public void sealPublication(PublishAttempt attempt, boolean published) { - new GameDesignPublicationOperationRepository(dsl).seal(attempt.getTenantId(), - attempt.getPublishWorkflowId(), attempt.getVersionId(), attempt.getRequestDigest(), published); + new GameDesignPublicationOperationRepository(dsl) + .seal( + attempt.getTenantId(), + attempt.getPublishWorkflowId(), + attempt.getVersionId(), + attempt.getRequestDigest(), + published); } public void requirePublishedOperation(PublishAttempt attempt) { @@ -91,8 +105,10 @@ public void requireNoPublicationOperation(PublishAttempt attempt) { } private void requireTerminalOperation(PublishAttempt attempt, String outcome) { - var result = new GameDesignPublicationOperationRepository(dsl).read(attempt.getPublishWorkflowId()) - .orElseThrow(() -> new IllegalStateException("PUBLICATION_OPERATION_UNAVAILABLE")); + var result = + new GameDesignPublicationOperationRepository(dsl) + .read(attempt.getPublishWorkflowId()) + .orElseThrow(() -> new IllegalStateException("PUBLICATION_OPERATION_UNAVAILABLE")); if (!outcome.equals(result.outcome()) || !result.operation().selectionDigest().equals(attempt.getRequestDigest()) || result.operation().versionId() != attempt.getVersionId() @@ -179,24 +195,27 @@ public PublishAttempt save(PublishAttempt attempt) { } return toEntity(record); } - int changed = dsl.update(PUBLISH_ATTEMPT_TABLE) - .set(TENANT_ID, attempt.getTenantId()) - .set(PUBLISH_WORKFLOW_ID, attempt.getPublishWorkflowId()) - .set(PUBLISH_TYPE, attempt.getPublishType().name()) - .set(STATUS, attempt.getStatus().name()) - .set(REVISION, Math.addExact(attempt.getRevision(), 1L)) - .set(VERSION_ID, attempt.getVersionId()) - .set(VERSION_NUMBER, attempt.getVersionNumber()) - .set(SCRIPT_PATCH_VERSION, attempt.getScriptPatchVersion()) - .set(BASE_VERSION_ID, attempt.getBaseVersionId()) - .set(REQUEST_DIGEST, attempt.getRequestDigest()) - .set(FAILURE_CODE, attempt.getFailureCode()) - .set(FAILURE_MESSAGE, attempt.getFailureMessage()) - .set(CREATED_AT, JooqPersistenceSupport.toTimestamp(createdAt)) - .set(COMPLETED_AT, JooqPersistenceSupport.toTimestamp(attempt.getCompletedAt())) - .where(ID.eq(attempt.getId()).and(REVISION.eq(attempt.getRevision())) - .and(STATUS.eq(PublishAttemptStatus.PENDING.name()))) - .execute(); + int changed = + dsl.update(PUBLISH_ATTEMPT_TABLE) + .set(TENANT_ID, attempt.getTenantId()) + .set(PUBLISH_WORKFLOW_ID, attempt.getPublishWorkflowId()) + .set(PUBLISH_TYPE, attempt.getPublishType().name()) + .set(STATUS, attempt.getStatus().name()) + .set(REVISION, Math.addExact(attempt.getRevision(), 1L)) + .set(VERSION_ID, attempt.getVersionId()) + .set(VERSION_NUMBER, attempt.getVersionNumber()) + .set(SCRIPT_PATCH_VERSION, attempt.getScriptPatchVersion()) + .set(BASE_VERSION_ID, attempt.getBaseVersionId()) + .set(REQUEST_DIGEST, attempt.getRequestDigest()) + .set(FAILURE_CODE, attempt.getFailureCode()) + .set(FAILURE_MESSAGE, attempt.getFailureMessage()) + .set(CREATED_AT, JooqPersistenceSupport.toTimestamp(createdAt)) + .set(COMPLETED_AT, JooqPersistenceSupport.toTimestamp(attempt.getCompletedAt())) + .where( + ID.eq(attempt.getId()) + .and(REVISION.eq(attempt.getRevision())) + .and(STATUS.eq(PublishAttemptStatus.PENDING.name()))) + .execute(); if (changed != 1) throw new IllegalStateException("PUBLISH_ATTEMPT_CAS_CONFLICT"); return findByPublishWorkflowId(attempt.getPublishWorkflowId()).orElseThrow(); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java index 3b2e0f6b38..4c9e77c7bd 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java @@ -113,7 +113,8 @@ public void recordFullVersionParticipantDigests( private void recordParticipantDigestsInCurrentTransaction( String publishWorkflowId, List participantDigests) { PublishAttempt attempt = requireAttempt(publishWorkflowId); - if (attempt.getStatus() != PublishAttemptStatus.PENDING) throw new IllegalStateException("Publish attempt is terminal"); + if (attempt.getStatus() != PublishAttemptStatus.PENDING) + throw new IllegalStateException("Publish attempt is terminal"); participantDigestRepository.deleteByPublishAttemptId(attempt.getId()); participantDigests.forEach( digest -> participantDigestRepository.save(toEntity(attempt.getId(), digest))); @@ -134,7 +135,8 @@ public void markFullVersionSucceeded(String publishWorkflowId) { private void markSucceededInCurrentTransaction(String publishWorkflowId) { PublishAttempt attempt = requireAttempt(publishWorkflowId); if (attempt.getStatus() == PublishAttemptStatus.SUCCEEDED) return; - if (attempt.getStatus() != PublishAttemptStatus.PENDING) throw new IllegalStateException("Publish attempt is terminal"); + if (attempt.getStatus() != PublishAttemptStatus.PENDING) + throw new IllegalStateException("Publish attempt is terminal"); attempt.setStatus(PublishAttemptStatus.SUCCEEDED); attempt.setFailureCode(null); attempt.setFailureMessage(null); @@ -162,7 +164,8 @@ private void markFailedInCurrentTransaction( if (attempt.getStatus() == PublishAttemptStatus.FAILED && Objects.equals(attempt.getFailureCode(), failureCode) && Objects.equals(attempt.getFailureMessage(), failureMessage)) return; - if (attempt.getStatus() != PublishAttemptStatus.PENDING) throw new IllegalStateException("Publish attempt is terminal"); + if (attempt.getStatus() != PublishAttemptStatus.PENDING) + throw new IllegalStateException("Publish attempt is terminal"); attempt.setStatus(PublishAttemptStatus.FAILED); attempt.setFailureCode(failureCode); attempt.setFailureMessage(failureMessage); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java index 5946c22bae..0c814fa5c8 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java @@ -15,15 +15,15 @@ import java.util.UUID; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; +import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.AssetSelection; import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; import net.firedevops.firemud.gamedesign.repository.VersionRepository; -import net.firedevops.firemud.gamedesign.repository.GameRepository; -import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; -import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.VersionAssetExportCandidateService; @@ -122,11 +122,15 @@ private ExportedAssetManifest recordInOwnerTransaction( if (initiallyFound.getId() == null || initiallyFound.getId() <= 0) { throw new IllegalStateException(CANDIDATE_CONFLICT); } - var initialArtifact = artifactRepository.findByTenantIdAndVersionId(tenantId, initiallyFound.getId()) - .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); - var attempt = attemptRepository.findByPublishWorkflowIdForUpdate(initialArtifact.getLastWorkflowId()); + var initialArtifact = + artifactRepository + .findByTenantIdAndVersionId(tenantId, initiallyFound.getId()) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + var attempt = + attemptRepository.findByPublishWorkflowIdForUpdate(initialArtifact.getLastWorkflowId()); // Standalone private candidate recording is not publication authority. If an actual selected - // attempt exists, its immutable operation must still be open before any new candidate admission. + // attempt exists, its immutable operation must still be open before any new candidate + // admission. if (attempt.isPresent()) { var current = attempt.get(); if (!Objects.equals(current.getTenantId(), tenantId) diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java index 3447d22e51..633ff8a343 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java @@ -2,37 +2,41 @@ import java.math.BigInteger; import java.util.List; -import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import java.util.function.Supplier; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.gamedesign.entity.PublishAttempt; -import net.firedevops.firemud.gamedesign.model.PublishType; -import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; -import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; -import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; -import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; -import org.jooq.DSLContext; -import java.util.function.Supplier; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; +import net.firedevops.firemud.gamedesign.model.PublishType; import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; -import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import org.jooq.DSLContext; -/** ISOLATED upstream authority; executes actual GD synchronized selection/attempt/operation writes. */ +/** + * ISOLATED upstream authority; executes actual GD synchronized selection/attempt/operation writes. + */ public final class IsolatedPublicationOwnerSetup { private IsolatedPublicationOwnerSetup() {} - /** Caller supplies a writable READ_COMMITTED owner transaction and an actual Draft target/epoch. */ - public static GameDesignPublicationOperation retain(DSLContext dsl, DraftCommitBinding.TargetProof target, - long draftEpoch) throws Exception { + /** + * Caller supplies a writable READ_COMMITTED owner transaction and an actual Draft target/epoch. + */ + public static GameDesignPublicationOperation retain( + DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch) throws Exception { return retain(dsl, target, draftEpoch, "ISOLATED owner transaction proof"); } - public static GameDesignPublicationOperation retain(DSLContext dsl, DraftCommitBinding.TargetProof target, - long draftEpoch, String notes) throws Exception { + public static GameDesignPublicationOperation retain( + DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch, String notes) + throws Exception { var seed = IsolatedPublicationOperationFixtures.fresh(target); var draft = seed.account().input().selection().selectedCommit(); var coordinator = new DraftCommitCoordinatorRepository(dsl); @@ -40,28 +44,62 @@ public static GameDesignPublicationOperation retain(DSLContext dsl, DraftCommitB // GD Draft-authorization operation or live Account authority issued by this helper. coordinator.claim(draft); coordinator.claimApplicationSlot(draft); - var epochs = draft.affectedUnits().stream().map(unit -> new DraftCommitCoordinatorRepository.AppliedEpoch( - unit.aggregateType(), unit.aggregateId(), unit.scopeType(), unit.scopeId(), unit.expectedEpoch(), - new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())).toList(); - var outcome = new DraftCommitCoordinatorRepository.OwnerOutcome(DraftCommitBinding.Owner.WORLD_MANAGEMENT, - DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, draft.commitId(), draft.digest(), - "ISOLATED-world-applied", seed.world().appliedResultBytes(), epochs); + var epochs = + draft.affectedUnits().stream() + .map( + unit -> + new DraftCommitCoordinatorRepository.AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(); + var outcome = + new DraftCommitCoordinatorRepository.OwnerOutcome( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, + draft.commitId(), + draft.digest(), + "ISOLATED-world-applied", + seed.world().appliedResultBytes(), + epochs); coordinator.markOwnerInProgress(draft, DraftCommitBinding.Owner.WORLD_MANAGEMENT); coordinator.recordOwnerOutcome(draft, outcome); - coordinator.advanceVisibilityFence(draft, new DraftCommitCoordinatorRepository.CoordinatorProof(draft, List.of(outcome))); + coordinator.advanceVisibilityFence( + draft, new DraftCommitCoordinatorRepository.CoordinatorProof(draft, List.of(outcome))); coordinator.releaseApplicationSlot(draft); - var seedIntent = seed.account().input().selection().intent(); - var selection = new AuthoredDraftPublishSelectionRepository(dsl, coordinator).reserve( - new AuthoredDraftPublishSelection.PublishIntent(target.canonicalTenantId(), target.canonicalVersionId(), - java.util.UUID.randomUUID().toString(), Long.toString(draftEpoch), notes, draft.requestId(), draft.commitId(), draft.digest())).selection(); - var operation = IsolatedPublicationOperationFixtures.forSelection( - AuthoredDraftPublishSelectionBinding.fromStored(selection.canonicalJson(), selection.digest()), seed.world()); + var selection = + new AuthoredDraftPublishSelectionRepository(dsl, coordinator) + .reserve( + new AuthoredDraftPublishSelection.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + java.util.UUID.randomUUID().toString(), + Long.toString(draftEpoch), + notes, + draft.requestId(), + draft.commitId(), + draft.digest())) + .selection(); + var operation = + IsolatedPublicationOperationFixtures.forSelection( + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()), + seed.world()); var attempt = new PublishAttempt(); attempt.setTenantId(target.gameDesignVersionTenantKey()); attempt.setPublishWorkflowId(operation.workflowId()); attempt.setPublishType(PublishType.FULL_VERSION); attempt.setVersionId(target.gameDesignVersionRowId()); - attempt.setVersionNumber(dsl.fetchOne("SELECT version_number FROM version WHERE id = ?", target.gameDesignVersionRowId()).get(0, Integer.class)); + var versionRow = + dsl.fetchOne( + "SELECT version_number FROM version WHERE id = ?", target.gameDesignVersionRowId()); + if (versionRow == null) { + throw new IllegalStateException("Selected authored Version row is absent"); + } + attempt.setVersionNumber(versionRow.get(0, Integer.class)); attempt.setRequestDigest(selection.digest()); new PublishAttemptRepository(dsl).save(attempt); new GameDesignPublicationOperationRepository(dsl).reserve(operation); @@ -69,8 +107,11 @@ public static GameDesignPublicationOperation retain(DSLContext dsl, DraftCommitB } /** Storage fixture commit only; does not substitute for actual command finalization proof. */ - public static PublishedReleaseBundle commitStorage(DSLContext dsl, VersionRepository versions, - GameDesignPublicationOperation operation, Supplier releaseWrite) { + public static PublishedReleaseBundle commitStorage( + DSLContext dsl, + VersionRepository versions, + GameDesignPublicationOperation operation, + Supplier releaseWrite) { var attempts = new PublishAttemptRepository(dsl); var attempt = attempts.findByPublishWorkflowIdForUpdate(operation.workflowId()).orElseThrow(); if (attempt.getStatus() == PublishAttemptStatus.SUCCEEDED) { @@ -78,19 +119,28 @@ public static PublishedReleaseBundle commitStorage(DSLContext dsl, VersionReposi return releaseWrite.get(); } attempts.requirePublicationPending(attempt); - var version = versions.findByTenantIdAndIdForUpdate(operation.tenantKey(), operation.versionId()).orElseThrow(); + var version = + versions + .findByTenantIdAndIdForUpdate(operation.tenantKey(), operation.versionId()) + .orElseThrow(); PublishedReleaseBundle bundle = releaseWrite.get(); version.setVersionState(VersionLifecycleState.PUBLISHED); version.setVersionStateEpoch(Math.addExact(version.getVersionStateEpoch(), 1)); versions.save(version); var artifact = new VersionAssetArtifact(); - artifact.setTenantId(operation.tenantKey()); artifact.setVersionId(operation.versionId()); - artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); artifact.setStateEpoch(1); - artifact.setExportedVersionNumber(version.getVersionNumber()); artifact.setManifestHash(bundle.getManifestHash()); - artifact.setLastWorkflowId(operation.workflowId()); artifact.setManifestSchemaVersion(bundle.getManifestSchemaVersion()); - artifact.setArtifactDigestsJson(bundle.getArtifactDigestsJson()); artifact.setPublishedObjectProofsJson("[]"); + artifact.setTenantId(operation.tenantKey()); + artifact.setVersionId(operation.versionId()); + artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); + artifact.setStateEpoch(1); + artifact.setExportedVersionNumber(version.getVersionNumber()); + artifact.setManifestHash(bundle.getManifestHash()); + artifact.setLastWorkflowId(operation.workflowId()); + artifact.setManifestSchemaVersion(bundle.getManifestSchemaVersion()); + artifact.setArtifactDigestsJson(bundle.getArtifactDigestsJson()); + artifact.setPublishedObjectProofsJson("[]"); new VersionAssetArtifactRepository(dsl).save(artifact); - attempt.setStatus(PublishAttemptStatus.SUCCEEDED); attempts.save(attempt); + attempt.setStatus(PublishAttemptStatus.SUCCEEDED); + attempts.save(attempt); attempts.sealPublication(attempt, true); return bundle; } diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java index 7fd4477c1b..967d8e48fa 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java @@ -17,51 +17,146 @@ import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; import tools.jackson.databind.ObjectMapper; -/** ISOLATED stipulated upstream source/World bytes; only callers' GD owner writes are real proof. */ +/** + * ISOLATED stipulated upstream source/World bytes; only callers' GD owner writes are real proof. + */ public final class IsolatedPublicationOperationFixtures { private IsolatedPublicationOperationFixtures() {} - /** A new fixture operation and freeze, never a reinterpretation of retained publication history. */ - public static GameDesignPublicationOperation fresh(DraftCommitBinding.TargetProof target) throws Exception { + /** + * A new fixture operation and freeze, never a reinterpretation of retained publication history. + */ + public static GameDesignPublicationOperation fresh(DraftCommitBinding.TargetProof target) + throws Exception { var seed = PublishedWorldSelectorFixtures.evidence(target); - var originalDraftAccount = DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); - var draft = DraftCommitBinding.fromStored(new String(originalDraftAccount.gameDesignBinding(), StandardCharsets.UTF_8), originalDraftAccount.inputDigest()); - var appliedEpochs = draft.affectedUnits().stream().map(unit -> Map.of( - "aggregateType", unit.aggregateType(), "aggregateId", unit.aggregateId(), - "scopeType", unit.scopeType(), "scopeId", unit.scopeId(), - "expectedEpoch", unit.expectedEpoch(), "resultingEpoch", new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())).toList(); - String vector = new String(Rfc8785CanonicalJson.canonicalizeUtf8(new ObjectMapper().writeValueAsString(List.of(Map.of( - "owner", "WORLD_MANAGEMENT", "status", "APPLIED", "commitId", draft.commitId().toString(), - "bindingDigest", draft.digest(), "resultIdentity", "ISOLATED-world-applied", - "resultBytesBase64", Base64.getEncoder().encodeToString(seed.appliedResultBytes()), "appliedEpochs", appliedEpochs)))), StandardCharsets.UTF_8); - var intent = new AuthoredDraftPublishSelectionBinding.PublishIntent(target.canonicalTenantId(), target.canonicalVersionId(), - "ISOLATED-publication-request", "5", "ISOLATED owner transaction proof", draft.requestId(), draft.commitId(), draft.digest()); - var selected = AuthoredDraftPublishSelectionBinding.capture(intent, target, draft, - new AuthoredDraftPublishSelectionBinding.VisibilityFence(target, draft.requestId(), draft.commitId(), draft.digest(), vector, - OffsetDateTime.parse("2026-10-07T00:00:00Z"))); + var originalDraftAccount = + DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); + var draft = + DraftCommitBinding.fromStored( + new String(originalDraftAccount.gameDesignBinding(), StandardCharsets.UTF_8), + originalDraftAccount.inputDigest()); + var appliedEpochs = + draft.affectedUnits().stream() + .map( + unit -> + Map.of( + "aggregateType", + unit.aggregateType(), + "aggregateId", + unit.aggregateId(), + "scopeType", + unit.scopeType(), + "scopeId", + unit.scopeId(), + "expectedEpoch", + unit.expectedEpoch(), + "resultingEpoch", + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(); + String vector = + new String( + Rfc8785CanonicalJson.canonicalizeUtf8( + new ObjectMapper() + .writeValueAsString( + List.of( + Map.of( + "owner", + "WORLD_MANAGEMENT", + "status", + "APPLIED", + "commitId", + draft.commitId().toString(), + "bindingDigest", + draft.digest(), + "resultIdentity", + "ISOLATED-world-applied", + "resultBytesBase64", + Base64.getEncoder().encodeToString(seed.appliedResultBytes()), + "appliedEpochs", + appliedEpochs)))), + StandardCharsets.UTF_8); + var intent = + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + "ISOLATED-publication-request", + "5", + "ISOLATED owner transaction proof", + draft.requestId(), + draft.commitId(), + draft.digest()); + var selected = + AuthoredDraftPublishSelectionBinding.capture( + intent, + target, + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + draft.requestId(), + draft.commitId(), + draft.digest(), + vector, + OffsetDateTime.parse("2026-10-07T00:00:00Z"))); return forSelection(selected, seed); } - public static GameDesignPublicationOperation forSelection(AuthoredDraftPublishSelectionBinding selected, - WorldPublishedStartLocationEvidence seed) { - var originalDraftAccount = DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); + public static GameDesignPublicationOperation forSelection( + AuthoredDraftPublishSelectionBinding selected, WorldPublishedStartLocationEvidence seed) { + var originalDraftAccount = + DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); var target = selected.target(); var intent = selected.intent(); var draft = selected.selectedCommit(); - var account = new AccountPublicationAuthorizationBinding(UUID.randomUUID(), UUID.randomUUID(), - new AccountPublicationAuthorizationBinding.PreallocationInput(originalDraftAccount.actorAccountId(), selected), - java.util.Arrays.stream(DraftAuthorizationFenceBinding.SourceKind.values()).map(kind -> - new DraftAuthorizationFenceBinding.SourceEvidence(kind, switch (kind) { - case ACCOUNT, GLOBAL_ROLES -> originalDraftAccount.actorAccountId().toString(); - case TENANT -> target.canonicalTenantId().toString(); - case MEMBERSHIP -> originalDraftAccount.actorAccountId() + "/" + target.canonicalTenantId(); - default -> "ISOLATED-" + kind; - }, "1", "1", null, null, ("ISOLATED-stipulated-" + kind).getBytes(StandardCharsets.UTF_8))).toList()); - var world = new WorldPublishedStartLocationEvidence(new WorldPublishedStartLocationEvidence.Request("test", target.canonicalTenantId(), - target.canonicalVersionId(), seed.request().intakeRequestId(), UUID.randomUUID(), intent.publishRequestId(), selected.digest().substring(7), - Long.parseLong(intent.expectedVersionStateEpoch()), FiremudWorkflowIds.workflowId("publish", target.canonicalTenantId().toString(), "publish-request", intent.publishRequestId()), - draft.commitId().toString(), seed.request().contentDigest(), 3, seed.request().worldAffectedTuples()), - seed.selectorReceiptBytes(), seed.originalAccountBindingBytes(), seed.appliedResultBytes()); + var account = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + new AccountPublicationAuthorizationBinding.PreallocationInput( + originalDraftAccount.actorAccountId(), selected), + java.util.Arrays.stream(DraftAuthorizationFenceBinding.SourceKind.values()) + .map( + kind -> + new DraftAuthorizationFenceBinding.SourceEvidence( + kind, + switch (kind) { + case ACCOUNT, GLOBAL_ROLES -> + originalDraftAccount.actorAccountId().toString(); + case TENANT -> target.canonicalTenantId().toString(); + case MEMBERSHIP -> + originalDraftAccount.actorAccountId() + + "/" + + target.canonicalTenantId(); + default -> "ISOLATED-" + kind; + }, + "1", + "1", + null, + null, + ("ISOLATED-stipulated-" + kind).getBytes(StandardCharsets.UTF_8))) + .toList()); + var world = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + "test", + target.canonicalTenantId(), + target.canonicalVersionId(), + seed.request().intakeRequestId(), + UUID.randomUUID(), + intent.publishRequestId(), + selected.digest().substring(7), + Long.parseLong(intent.expectedVersionStateEpoch()), + FiremudWorkflowIds.workflowId( + "publish", + target.canonicalTenantId().toString(), + "publish-request", + intent.publishRequestId()), + draft.commitId().toString(), + seed.request().contentDigest(), + 3, + seed.request().worldAffectedTuples()), + seed.selectorReceiptBytes(), + seed.originalAccountBindingBytes(), + seed.appliedResultBytes()); return new GameDesignPublicationOperation(account, world); } } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java index a9453c25f7..132586e236 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java @@ -45,55 +45,121 @@ /** Actual GD owner DB guard proof; every upstream creator/source/freeze input is ISOLATED. */ @Testcontainers(disabledWithoutDocker = true) class GameDesignPublicationOperationPostgresIntegrationTest { - @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + private static final String MANIFEST = "sha256:" + "a".repeat(64); @Test - void noPublicationReceiptReplaysAfterLostResponseAndExcludesDelayedFinalizerAndRawInsert() throws Exception { + void noPublicationReceiptReplaysAfterLostResponseAndExcludesDelayedFinalizerAndRawInsert() + throws Exception { var fixture = fixture(); noPublication(fixture); var original = fixture.service().readExact(fixture.operation()).orElseThrow(); assertThat(original.outcome()).isEqualTo("NO_PUBLICATION"); - assertThat(fixture.service().retainVerifiedOperation(fixture.operation()).receiptBytes()).isEqualTo(original.receiptBytes()); - assertThatThrownBy(() -> fixture.write().executeWithoutResult(status -> fixture.operations().requirePending( - fixture.operation().tenantKey(), fixture.operation().workflowId(), fixture.operation().versionId(), fixture.operation().selectionDigest()))) - .isInstanceOf(IllegalStateException.class).hasMessageContaining("SEALED_OR_CHANGED"); - assertThatThrownBy(() -> fixture.write().executeWithoutResult(status -> rawReleaseInsert(fixture))) + assertThat(fixture.service().retainVerifiedOperation(fixture.operation()).receiptBytes()) + .isEqualTo(original.receiptBytes()); + assertThatThrownBy( + () -> + fixture + .write() + .executeWithoutResult( + status -> + fixture + .operations() + .requirePending( + fixture.operation().tenantKey(), + fixture.operation().workflowId(), + fixture.operation().versionId(), + fixture.operation().selectionDigest()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("SEALED_OR_CHANGED"); + assertThatThrownBy( + () -> fixture.write().executeWithoutResult(status -> rawReleaseInsert(fixture))) .hasMessageContaining("selected publication is absent, sealed, or changed"); - assertThat(fixture.releases().findByTenantIdAndVersionId(fixture.operation().tenantKey(), fixture.operation().versionId())).isEmpty(); - assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().receiptBytes()).isEqualTo(original.receiptBytes()); + assertThat( + fixture + .releases() + .findByTenantIdAndVersionId( + fixture.operation().tenantKey(), fixture.operation().versionId())) + .isEmpty(); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().receiptBytes()) + .isEqualTo(original.receiptBytes()); } @Test - void publishedReceiptCannotBeDemotedByStaleFailureAndRetainsOriginalFreezeEpoch() throws Exception { + void publishedReceiptCannotBeDemotedByStaleFailureAndRetainsOriginalFreezeEpoch() + throws Exception { var fixture = fixture(); - var staleFailure = fixture.attempts().findByPublishWorkflowId(fixture.operation().workflowId()).orElseThrow(); + var staleFailure = + fixture.attempts().findByPublishWorkflowId(fixture.operation().workflowId()).orElseThrow(); publish(fixture); var original = fixture.service().readExact(fixture.operation()).orElseThrow(); assertThat(original.outcome()).isEqualTo("PUBLISHED"); - assertThat(fixture.service().retainVerifiedOperation(fixture.operation()).receiptBytes()).isEqualTo(original.receiptBytes()); - assertThat(fixture.versions().findByTenantIdAndId(fixture.operation().tenantKey(), fixture.operation().versionId()).orElseThrow().getVersionStateEpoch()) + assertThat(fixture.service().retainVerifiedOperation(fixture.operation()).receiptBytes()) + .isEqualTo(original.receiptBytes()); + assertThat( + fixture + .versions() + .findByTenantIdAndId( + fixture.operation().tenantKey(), fixture.operation().versionId()) + .orElseThrow() + .getVersionStateEpoch()) .isEqualTo(fixture.operation().world().request().versionStateEpoch() + 1); staleFailure.setStatus(PublishAttemptStatus.FAILED); - assertThatThrownBy(() -> fixture.write().executeWithoutResult(status -> fixture.attempts().save(staleFailure))) - .isInstanceOf(IllegalStateException.class).hasMessageContaining("CAS_CONFLICT"); + assertThatThrownBy( + () -> + fixture + .write() + .executeWithoutResult(status -> fixture.attempts().save(staleFailure))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("CAS_CONFLICT"); assertThatThrownBy(() -> noPublication(fixture)).isInstanceOf(IllegalStateException.class); - assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().receiptBytes()).isEqualTo(original.receiptBytes()); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().receiptBytes()) + .isEqualTo(original.receiptBytes()); } @Test - void failedAtomicCommitLeavesAttemptOperationVersionAndReleasePendingForExactRetry() throws Exception { + void failedAtomicCommitLeavesAttemptOperationVersionAndReleasePendingForExactRetry() + throws Exception { var fixture = fixture(); - assertThatThrownBy(() -> fixture.write().executeWithoutResult(status -> { - publishInTransaction(fixture); - throw new IllegalStateException("ISOLATED rollback after all owner writes"); - })).hasMessageContaining("rollback after all owner writes"); - assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().outcome()).isEqualTo("PENDING"); - assertThat(fixture.releases().findByTenantIdAndVersionId(fixture.operation().tenantKey(), fixture.operation().versionId())).isEmpty(); - assertThat(fixture.attempts().findByPublishWorkflowId(fixture.operation().workflowId()).orElseThrow().getStatus()).isEqualTo(PublishAttemptStatus.PENDING); - assertThat(fixture.versions().findByTenantIdAndId(fixture.operation().tenantKey(), fixture.operation().versionId()).orElseThrow().getVersionState()).isEqualTo(VersionLifecycleState.DRAFT); + assertThatThrownBy( + () -> + fixture + .write() + .executeWithoutResult( + status -> { + publishInTransaction(fixture); + throw new IllegalStateException( + "ISOLATED rollback after all owner writes"); + })) + .hasMessageContaining("rollback after all owner writes"); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().outcome()) + .isEqualTo("PENDING"); + assertThat( + fixture + .releases() + .findByTenantIdAndVersionId( + fixture.operation().tenantKey(), fixture.operation().versionId())) + .isEmpty(); + assertThat( + fixture + .attempts() + .findByPublishWorkflowId(fixture.operation().workflowId()) + .orElseThrow() + .getStatus()) + .isEqualTo(PublishAttemptStatus.PENDING); + assertThat( + fixture + .versions() + .findByTenantIdAndId( + fixture.operation().tenantKey(), fixture.operation().versionId()) + .orElseThrow() + .getVersionState()) + .isEqualTo(VersionLifecycleState.DRAFT); publish(fixture); - assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().outcome()).isEqualTo("PUBLISHED"); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().outcome()) + .isEqualTo("PUBLISHED"); } @Test @@ -102,112 +168,234 @@ void noPublicationSerializesAgainstAnAlreadyScheduledLatePublisher() throws Exce var sealed = new CountDownLatch(1); var releaseSeal = new CountDownLatch(1); try (var executor = Executors.newFixedThreadPool(2)) { - var winner = executor.submit(() -> fixture.write().executeWithoutResult(status -> { - noPublicationInTransaction(fixture); - sealed.countDown(); - await(releaseSeal); - })); + var winner = + executor.submit( + () -> + fixture + .write() + .executeWithoutResult( + status -> { + noPublicationInTransaction(fixture); + sealed.countDown(); + await(releaseSeal); + })); assertThat(sealed.await(10, TimeUnit.SECONDS)).isTrue(); - var loser = executor.submit(() -> { - assertThatThrownBy(() -> publish(fixture)).isInstanceOf(IllegalStateException.class); - }); + var loser = + executor.submit( + () -> { + assertThatThrownBy(() -> publish(fixture)) + .isInstanceOf(IllegalStateException.class); + }); releaseSeal.countDown(); winner.get(10, TimeUnit.SECONDS); loser.get(10, TimeUnit.SECONDS); - } finally { releaseSeal.countDown(); } - assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().outcome()).isEqualTo("NO_PUBLICATION"); + } finally { + releaseSeal.countDown(); + } + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().outcome()) + .isEqualTo("NO_PUBLICATION"); + } + + private void noPublication(Fixture fixture) { + fixture.write().executeWithoutResult(status -> noPublicationInTransaction(fixture)); } - private void noPublication(Fixture fixture) { fixture.write().executeWithoutResult(status -> noPublicationInTransaction(fixture)); } private void noPublicationInTransaction(Fixture fixture) { var op = fixture.operation(); - fixture.operations().requirePending(op.tenantKey(), op.workflowId(), op.versionId(), op.selectionDigest()); - var attempt = fixture.attempts().findByPublishWorkflowIdForUpdate(op.workflowId()).orElseThrow(); + fixture + .operations() + .requirePending(op.tenantKey(), op.workflowId(), op.versionId(), op.selectionDigest()); + var attempt = + fixture.attempts().findByPublishWorkflowIdForUpdate(op.workflowId()).orElseThrow(); attempt.setStatus(PublishAttemptStatus.FAILED); attempt.setFailureCode("ISOLATED_BUSINESS_DENIAL"); fixture.attempts().save(attempt); - fixture.operations().seal(op.tenantKey(), op.workflowId(), op.versionId(), op.selectionDigest(), false); + fixture + .operations() + .seal(op.tenantKey(), op.workflowId(), op.versionId(), op.selectionDigest(), false); } - private void publish(Fixture fixture) { fixture.write().executeWithoutResult(status -> publishInTransaction(fixture)); } + + private void publish(Fixture fixture) { + fixture.write().executeWithoutResult(status -> publishInTransaction(fixture)); + } + private void publishInTransaction(Fixture fixture) { var op = fixture.operation(); - fixture.operations().requirePending(op.tenantKey(), op.workflowId(), op.versionId(), op.selectionDigest()); + fixture + .operations() + .requirePending(op.tenantKey(), op.workflowId(), op.versionId(), op.selectionDigest()); fixture.releases().save(bundle(fixture)); - var version = fixture.versions().findByTenantIdAndIdForUpdate(op.tenantKey(), op.versionId()).orElseThrow(); + var version = + fixture + .versions() + .findByTenantIdAndIdForUpdate(op.tenantKey(), op.versionId()) + .orElseThrow(); version.setVersionState(VersionLifecycleState.PUBLISHED); version.setVersionStateEpoch(version.getVersionStateEpoch() + 1); fixture.versions().save(version); var artifact = new VersionAssetArtifact(); - artifact.setTenantId(op.tenantKey()); artifact.setVersionId(op.versionId()); - artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); artifact.setStateEpoch(1); - artifact.setExportedVersionNumber(version.getVersionNumber()); artifact.setManifestHash(MANIFEST); - artifact.setLastWorkflowId(op.workflowId()); artifact.setManifestSchemaVersion(1); - artifact.setArtifactDigestsJson("[]"); artifact.setPublishedObjectProofsJson("[]"); + artifact.setTenantId(op.tenantKey()); + artifact.setVersionId(op.versionId()); + artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); + artifact.setStateEpoch(1); + artifact.setExportedVersionNumber(version.getVersionNumber()); + artifact.setManifestHash(MANIFEST); + artifact.setLastWorkflowId(op.workflowId()); + artifact.setManifestSchemaVersion(1); + artifact.setArtifactDigestsJson("[]"); + artifact.setPublishedObjectProofsJson("[]"); fixture.artifacts().save(artifact); - var attempt = fixture.attempts().findByPublishWorkflowIdForUpdate(op.workflowId()).orElseThrow(); - attempt.setStatus(PublishAttemptStatus.SUCCEEDED); fixture.attempts().save(attempt); - fixture.operations().seal(op.tenantKey(), op.workflowId(), op.versionId(), op.selectionDigest(), true); + var attempt = + fixture.attempts().findByPublishWorkflowIdForUpdate(op.workflowId()).orElseThrow(); + attempt.setStatus(PublishAttemptStatus.SUCCEEDED); + fixture.attempts().save(attempt); + fixture + .operations() + .seal(op.tenantKey(), op.workflowId(), op.versionId(), op.selectionDigest(), true); } private PublishedReleaseBundle bundle(Fixture fixture) { var op = fixture.operation(); var bundle = new PublishedReleaseBundle(); - bundle.setTenantId(op.tenantKey()); bundle.setVersionId(op.versionId()); bundle.setVersionNumber(1); - bundle.setCanonicalTenantId(op.account().tenantId()); bundle.setCanonicalVersionId(op.world().request().canonicalVersionId()); - bundle.setAttestationSchemaVersion("v2"); bundle.setPublishWorkflowId(op.workflowId()); - bundle.setManifestHash(MANIFEST); bundle.setManifestSchemaVersion(1); bundle.setArtifactDigestsJson("[]"); - bundle.setRequiredManifestAssetKeysJson("[]"); bundle.setCommandDefinitionsJson("[]"); + bundle.setTenantId(op.tenantKey()); + bundle.setVersionId(op.versionId()); + bundle.setVersionNumber(1); + bundle.setCanonicalTenantId(op.account().tenantId()); + bundle.setCanonicalVersionId(op.world().request().canonicalVersionId()); + bundle.setAttestationSchemaVersion("v2"); + bundle.setPublishWorkflowId(op.workflowId()); + bundle.setManifestHash(MANIFEST); + bundle.setManifestSchemaVersion(1); + bundle.setArtifactDigestsJson("[]"); + bundle.setRequiredManifestAssetKeysJson("[]"); + bundle.setCommandDefinitionsJson("[]"); bundle.setGenerationConfigRevision("generation-1"); - bundle.setParticipantDigestsJson(new ObjectMapper().writeValueAsString(PublishedWorldSelectorFixtures.participants(op.versionId(), op.world()))); - bundle.setWorldPublishedStartLocationEvidenceJson(new String(op.world().canonicalBytes(), StandardCharsets.UTF_8)); + bundle.setParticipantDigestsJson( + new ObjectMapper() + .writeValueAsString( + PublishedWorldSelectorFixtures.participants(op.versionId(), op.world()))); + bundle.setWorldPublishedStartLocationEvidenceJson( + new String(op.world().canonicalBytes(), StandardCharsets.UTF_8)); return bundle; } private void rawReleaseInsert(Fixture fixture) { var bundle = bundle(fixture); - fixture.dsl().execute("INSERT INTO published_release_bundle (tenant_id, version_id, version_number, canonical_tenant_id, canonical_version_id, " - + "published_release_bundle_ref, attestation_schema_version, publish_workflow_id, manifest_hash, generation_config_revision, manifest_schema_version, " - + "artifact_digests_json, required_manifest_asset_keys_json, participant_digests_json, command_definitions_json, script_only, world_published_start_location_evidence_json) " - + "VALUES (?, ?, 1, ?, ?, ?, 'v2', ?, ?, ?, 1, '[]', '[]', ?, '[]', FALSE, ?)", bundle.getTenantId(), bundle.getVersionId(), - bundle.getCanonicalTenantId(), bundle.getCanonicalVersionId(), UUID.randomUUID().toString(), bundle.getPublishWorkflowId(), MANIFEST, - bundle.getGenerationConfigRevision(), bundle.getParticipantDigestsJson(), bundle.getWorldPublishedStartLocationEvidenceJson()); + fixture + .dsl() + .execute( + "INSERT INTO published_release_bundle (tenant_id, version_id, version_number, canonical_tenant_id, canonical_version_id, " + + "published_release_bundle_ref, attestation_schema_version, publish_workflow_id, manifest_hash, generation_config_revision, manifest_schema_version, " + + "artifact_digests_json, required_manifest_asset_keys_json, participant_digests_json, command_definitions_json, script_only, world_published_start_location_evidence_json) " + + "VALUES (?, ?, 1, ?, ?, ?, 'v2', ?, ?, ?, 1, '[]', '[]', ?, '[]', FALSE, ?)", + bundle.getTenantId(), + bundle.getVersionId(), + bundle.getCanonicalTenantId(), + bundle.getCanonicalVersionId(), + UUID.randomUUID().toString(), + bundle.getPublishWorkflowId(), + MANIFEST, + bundle.getGenerationConfigRevision(), + bundle.getParticipantDigestsJson(), + bundle.getWorldPublishedStartLocationEvidenceJson()); } private Fixture fixture() throws Exception { String schema = "gd_pub_op_" + UUID.randomUUID().toString().replace("-", ""); - var source = new DriverManagerDataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); source.setSchema(schema); - Flyway.configure().dataSource(source).schemas(schema).defaultSchema(schema) + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) .placeholders(java.util.Map.of("serviceSchema", schema)) - .locations("classpath:db/migration").table("flyway_schema_history_game_design_service").load().migrate(); + .locations("classpath:db/migration") + .table("flyway_schema_history_game_design_service") + .load() + .migrate(); var transactions = new DataSourceTransactionManager(source); - var write = new TransactionTemplate(transactions); write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var write = new TransactionTemplate(transactions); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); var configuration = new org.jooq.impl.DefaultConfiguration(); configuration.set(SQLDialect.POSTGRES); - configuration.set(new org.jooq.impl.DataSourceConnectionProvider(new TransactionAwareDataSourceProxy(source))); - configuration.set(new org.springframework.boot.jooq.autoconfigure.SpringTransactionProvider(transactions)); + configuration.set( + new org.jooq.impl.DataSourceConnectionProvider( + new TransactionAwareDataSourceProxy(source))); + configuration.set( + new org.springframework.boot.jooq.autoconfigure.SpringTransactionProvider(transactions)); var dsl = DSL.using(configuration); var games = new GameRepository(dsl); - var properties = new PostgresProperties(); properties.setSchema(schema); + var properties = new PostgresProperties(); + properties.setSchema(schema); var versions = new VersionRepository(dsl, properties); - Game game = write.execute(status -> { var requested = new Game(); requested.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); requested.setName("ISOLATED publication owner"); return games.save(requested); }); - Version version = write.execute(status -> { var requested = new Version(); requested.setTenantId(game.getTenantId()); requested.setVersionNumber(1); return versions.save(requested); }); - var target = new TargetProof(version.getCanonicalTenantId(), version.getCanonicalVersionId(), version.getId(), version.getTenantId(), - version.getIdentitySourceGameRowId(), version.getIdentitySourceGameTenantKey(), version.getIdentitySourceProvenanceKind()); - var operation = write.execute(status -> { - try { return IsolatedPublicationOwnerSetup.retain(dsl, target, version.getVersionStateEpoch()); } - catch (Exception failure) { throw new IllegalStateException(failure); } - }); + Game game = + write.execute( + status -> { + var requested = new Game(); + requested.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); + requested.setName("ISOLATED publication owner"); + return games.save(requested); + }); + Version version = + write.execute( + status -> { + var requested = new Version(); + requested.setTenantId(game.getTenantId()); + requested.setVersionNumber(1); + return versions.save(requested); + }); + var target = + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + var operation = + write.execute( + status -> { + try { + return IsolatedPublicationOwnerSetup.retain( + dsl, target, version.getVersionStateEpoch()); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); var operations = new GameDesignPublicationOperationRepository(dsl); - return new Fixture(dsl, write, versions, new PublishAttemptRepository(dsl), new PublishedReleaseBundleRepository(dsl), - new VersionAssetArtifactRepository(dsl), operations, new GameDesignPublicationOperationService(operations, transactions), operation); + return new Fixture( + dsl, + write, + versions, + new PublishAttemptRepository(dsl), + new PublishedReleaseBundleRepository(dsl), + new VersionAssetArtifactRepository(dsl), + operations, + new GameDesignPublicationOperationService(operations, transactions), + operation); } private static void await(CountDownLatch latch) { - try { if (!latch.await(10, TimeUnit.SECONDS)) throw new IllegalStateException("ISOLATED barrier timed out"); } - catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw new IllegalStateException(interrupted); } + try { + if (!latch.await(10, TimeUnit.SECONDS)) + throw new IllegalStateException("ISOLATED barrier timed out"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } } - private record Fixture(DSLContext dsl, TransactionTemplate write, VersionRepository versions, PublishAttemptRepository attempts, - PublishedReleaseBundleRepository releases, VersionAssetArtifactRepository artifacts, GameDesignPublicationOperationRepository operations, - GameDesignPublicationOperationService service, GameDesignPublicationOperation operation) {} + + private record Fixture( + DSLContext dsl, + TransactionTemplate write, + VersionRepository versions, + PublishAttemptRepository attempts, + PublishedReleaseBundleRepository releases, + VersionAssetArtifactRepository artifacts, + GameDesignPublicationOperationRepository operations, + GameDesignPublicationOperationService service, + GameDesignPublicationOperation operation) {} } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java index 55a5302b2a..f61277a04e 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java @@ -580,9 +580,17 @@ void selectorV2RetainsCompleteOriginalEvidenceAndExactlyReplaysWithoutReplacingR var operation = selectorOperation(fixture, version); WorldPublishedStartLocationEvidence evidence = operation.world(); PublishedReleaseBundle requested = selectorBundle(version, evidence); - PublishedReleaseBundle saved = fixture.transactionTemplate().execute(status -> - net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup.commitStorage( - fixture.dsl(), fixture.versionRepository(), operation, () -> fixture.releaseBundleRepository().save(requested))); + PublishedReleaseBundle saved = + fixture + .transactionTemplate() + .execute( + status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .commitStorage( + fixture.dsl(), + fixture.versionRepository(), + operation, + () -> fixture.releaseBundleRepository().save(requested))); String beforeXmin = bundleXmin(fixture.dsl(), saved.getId()); String original = new String(evidence.canonicalBytes(), StandardCharsets.UTF_8); assertThat(saved.getWorldPublishedStartLocationEvidenceJson()).isEqualTo(original); @@ -639,10 +647,18 @@ void concurrentExactSelectorRetriesCommitOneImmutableBundle() throws Exception { java.util.concurrent.Callable save = () -> { start.await(); - return fixture.transactionTemplate().execute(status -> - net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup.commitStorage( - fixture.dsl(), fixture.versionRepository(), operation, () -> new PublishedReleaseBundleRepository(fixture.dsl()) - .save(selectorBundle(version, evidence)))); + return fixture + .transactionTemplate() + .execute( + status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .commitStorage( + fixture.dsl(), + fixture.versionRepository(), + operation, + () -> + new PublishedReleaseBundleRepository(fixture.dsl()) + .save(selectorBundle(version, evidence)))); }; var first = executor.submit(save); var second = executor.submit(save); @@ -740,12 +756,21 @@ void sqlGuardRejectsMissingInjectedAndMismatchedSelectorBindingsWithoutAnyReleas fixture, version, "v2", original, json.writeValueAsString(changedParticipants))) .isInstanceOf(DataAccessException.class); assertThat(bundleCount(fixture.dsl())).isZero(); - fixture.transactionTemplate().executeWithoutResult(status -> - net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup.commitStorage( - fixture.dsl(), fixture.versionRepository(), operation, () -> { - insertRawSelector(fixture, version, "v2", original, participants); - return fixture.releaseBundleRepository().findByTenantIdAndVersionId(version.getTenantId(), version.getId()).orElseThrow(); - })); + fixture + .transactionTemplate() + .executeWithoutResult( + status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup.commitStorage( + fixture.dsl(), + fixture.versionRepository(), + operation, + () -> { + insertRawSelector(fixture, version, "v2", original, participants); + return fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(version.getTenantId(), version.getId()) + .orElseThrow(); + })); assertThat( new PublishedReleaseBundleRepository(fixture.dsl()) .findByTenantIdAndVersionId(version.getTenantId(), version.getId()) @@ -766,16 +791,32 @@ private WorldPublishedStartLocationEvidence selectorEvidence(Version version) th version.getIdentitySourceProvenanceKind())); } - /** ISOLATED upstream sources/freeze; synchronized selection and terminal GD rows are actual DB writes. */ - private net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation selectorOperation( - Fixture fixture, Version version) { - var target = new TargetProof(version.getCanonicalTenantId(), version.getCanonicalVersionId(), version.getId(), version.getTenantId(), - version.getIdentitySourceGameRowId(), version.getIdentitySourceGameTenantKey(), version.getIdentitySourceProvenanceKind()); - return fixture.transactionTemplate().execute(status -> { - try { - return net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup.retain(fixture.dsl(), target, version.getVersionStateEpoch()); - } catch (Exception failure) { throw new IllegalStateException(failure); } - }); + /** + * ISOLATED upstream sources/freeze; synchronized selection and terminal GD rows are actual DB + * writes. + */ + private net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation + selectorOperation(Fixture fixture, Version version) { + var target = + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + return fixture + .transactionTemplate() + .execute( + status -> { + try { + return net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup.retain( + fixture.dsl(), target, version.getVersionStateEpoch()); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); } private PublishedReleaseBundle selectorBundle( @@ -794,6 +835,17 @@ private PublishedReleaseBundle selectorBundle( private void insertRawSelector( Fixture fixture, Version version, String schema, String evidence, String participants) { + var operationRow = + fixture + .dsl() + .fetchOne( + "SELECT publish_workflow_id FROM game_design_publication_operation WHERE tenant_id = ? AND version_id = ?", + version.getTenantId(), + version.getId()); + if (operationRow == null) { + throw new IllegalStateException( + "Selected publication operation row is absent for release selector fixture"); + } fixture .dsl() .execute( @@ -808,7 +860,7 @@ private void insertRawSelector( version.getCanonicalVersionId(), UUID.randomUUID().toString(), schema, - fixture.dsl().fetchOne("SELECT publish_workflow_id FROM game_design_publication_operation WHERE tenant_id = ? AND version_id = ?", version.getTenantId(), version.getId()).get(0, String.class), + operationRow.get(0, String.class), MANIFEST_HASH, GENERATION_CONFIG_REVISION, participants, @@ -825,7 +877,8 @@ private Fixture fixture(MigrationVersion target) { private Fixture fixtureFromMigratedSchema(String schema, DriverManagerDataSource dataSource) { DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); - transactionTemplate.setIsolationLevel(org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); + transactionTemplate.setIsolationLevel( + org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); DefaultConfiguration jooqConfiguration = new DefaultConfiguration(); jooqConfiguration.set(SQLDialect.POSTGRES); jooqConfiguration.set( diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index 097b16bfe5..15f0d373d2 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -12,19 +12,12 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; -import net.firedevops.firemud.common.authoring.DraftCommitBinding; -import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; -import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; -import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; -import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository.SelectionSnapshot; -import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.PublicationEvidence; -import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.VisibilityFence; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.entity.Game; @@ -49,7 +42,6 @@ import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.repository.VersionTemplateRemapSetRepository; import net.firedevops.firemud.gamedesign.service.impl.PublishAttemptServiceImpl; -import net.firedevops.firemud.gamedesign.service.impl.TemporalVersionPublishWorkflow; import net.firedevops.firemud.gamedesign.service.impl.VersionPublishCommandServiceImpl; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; @@ -378,8 +370,8 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth .thenAnswer( invocation -> { VersionDto version = invocation.getArgument(0); - return net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures.participants( - version.id(), fixture.operation().world()); + return net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures + .participants(version.id(), fixture.operation().world()); }); Mockito.when(assetExportService.exportAssets(tenantId, 1)) .thenAnswer( @@ -515,8 +507,8 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( VersionDto candidate = invocation.getArgument(0); candidateVersionId.set(candidate.id()); candidateVersionNumber.set(candidate.versionNumber()); - return net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures.participants( - candidate.id(), fixture.operation().world()); + return net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures + .participants(candidate.id(), fixture.operation().world()); }); Mockito.doAnswer( invocation -> { @@ -698,14 +690,19 @@ private SelectedDraftFixture createSelectedDraftFixture( game.getId(), game.getTenantId(), "NEW_GAME_ROW"); - var operation = publishAttemptService.executeFullVersionTransaction(() -> { - try { - return net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup.retain( - dsl, target, savedVersion.getVersionStateEpoch(), notes); - } catch (Exception failure) { throw new IllegalStateException(failure); } - }); + var operation = + publishAttemptService.executeFullVersionTransaction( + () -> { + try { + return net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup.retain( + dsl, target, savedVersion.getVersionStateEpoch(), notes); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); var retained = operation.account().input().selection(); - AuthoredDraftPublishSelection selection = AuthoredDraftPublishSelection.fromStored(retained.canonicalJson(), retained.digest()); + AuthoredDraftPublishSelection selection = + AuthoredDraftPublishSelection.fromStored(retained.canonicalJson(), retained.digest()); String publishRequestId = selection.intent().publishRequestId(); Mockito.when( authoredSelectionRepository.readByPublishRequest( @@ -715,7 +712,13 @@ private SelectedDraftFixture createSelectedDraftFixture( String workflowId = operation.workflowId(); return new SelectedDraftFixture( - game.getTenantId(), notes, publishRequestId, workflowId, savedVersion, selection, operation); + game.getTenantId(), + notes, + publishRequestId, + workflowId, + savedVersion, + selection, + operation); } private Object invokeSelectedPublicationMechanics(SelectedDraftFixture fixture) { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionTest.java index 636291f6cd..3663aada47 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionTest.java @@ -5,22 +5,22 @@ import java.time.OffsetDateTime; import java.util.List; +import java.util.Map; import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; -import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; -import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; -import java.util.Map; -import tools.jackson.databind.ObjectMapper; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.PublicationEvidence; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.VisibilityFence; import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; class AuthoredDraftPublishSelectionTest { private static final String LARGE_COUNTER = "900719925474099312345678901234567890"; @@ -74,29 +74,68 @@ void selectionRetainsExactIntentFullCommitAndSynchronizedEvidence() throws Excep assertThat(restored.fenceResultVectorJson()).isEqualTo(fence.resultVectorJson()); assertThat(restored.fenceCreatedAt()).isEqualTo("2026-10-05T00:00:00Z"); // Independent original V43 object layout. Extraction must preserve its exact bytes/digest. - byte[] legacy = Rfc8785CanonicalJson.canonicalizeUtf8(new ObjectMapper().writeValueAsString( - Map.of("schemaVersion", "1", - "intent", Map.of("canonicalTenantId", intent.canonicalTenantId().toString(), - "canonicalVersionId", intent.canonicalVersionId().toString(), - "publishRequestId", intent.publishRequestId(), - "expectedVersionStateEpoch", intent.expectedVersionStateEpoch(), - "notes", intent.notes(), "selectedCommitRequestId", intent.selectedCommitRequestId().toString(), - "selectedCommitId", intent.selectedCommitId().toString(), - "selectedCommitDigest", intent.selectedCommitDigest()), - "target", Map.of("canonicalTenantId", target.canonicalTenantId().toString(), - "canonicalVersionId", target.canonicalVersionId().toString(), - "gameDesignVersionRowId", Long.toString(target.gameDesignVersionRowId()), - "gameDesignVersionTenantKey", target.gameDesignVersionTenantKey(), - "sourceGameRowId", Long.toString(target.sourceGameRowId()), - "sourceGameTenantKey", target.sourceGameTenantKey(), - "sourceProvenanceKind", target.sourceProvenanceKind()), - "selectedCommitBindingJson", binding.canonicalJson(), "selectedCommitDigest", binding.digest(), - "synchronizedFence", Map.of("requestId", fence.requestId().toString(), - "commitId", fence.commitId().toString(), "inputDigest", fence.inputDigest(), - "resultVectorJson", fence.resultVectorJson(), "createdAt", "2026-10-05T00:00:00Z")))); + byte[] legacy = + Rfc8785CanonicalJson.canonicalizeUtf8( + new ObjectMapper() + .writeValueAsString( + Map.of( + "schemaVersion", + "1", + "intent", + Map.of( + "canonicalTenantId", + intent.canonicalTenantId().toString(), + "canonicalVersionId", + intent.canonicalVersionId().toString(), + "publishRequestId", + intent.publishRequestId(), + "expectedVersionStateEpoch", + intent.expectedVersionStateEpoch(), + "notes", + intent.notes(), + "selectedCommitRequestId", + intent.selectedCommitRequestId().toString(), + "selectedCommitId", + intent.selectedCommitId().toString(), + "selectedCommitDigest", + intent.selectedCommitDigest()), + "target", + Map.of( + "canonicalTenantId", + target.canonicalTenantId().toString(), + "canonicalVersionId", + target.canonicalVersionId().toString(), + "gameDesignVersionRowId", + Long.toString(target.gameDesignVersionRowId()), + "gameDesignVersionTenantKey", + target.gameDesignVersionTenantKey(), + "sourceGameRowId", + Long.toString(target.sourceGameRowId()), + "sourceGameTenantKey", + target.sourceGameTenantKey(), + "sourceProvenanceKind", + target.sourceProvenanceKind()), + "selectedCommitBindingJson", + binding.canonicalJson(), + "selectedCommitDigest", + binding.digest(), + "synchronizedFence", + Map.of( + "requestId", + fence.requestId().toString(), + "commitId", + fence.commitId().toString(), + "inputDigest", + fence.inputDigest(), + "resultVectorJson", + fence.resultVectorJson(), + "createdAt", + "2026-10-05T00:00:00Z")))); assertThat(selection.canonicalBytes()).containsExactly(legacy); assertThat(selection.digest()).isEqualTo(DraftAuthorizationFenceBinding.digest(legacy)); - var shared = AuthoredDraftPublishSelectionBinding.fromStored(selection.canonicalJson(), selection.digest()); + var shared = + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()); assertThat(shared.canonicalBytes()).containsExactly(legacy); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationTest.java index 76a5fabc5e..437c43ebbe 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationTest.java @@ -14,32 +14,56 @@ class GameDesignPublicationOperationTest { @Test - void exactCodecPreservesDistinctAccountOperationCompleteSelectionAndOriginalWorldBytes() throws Exception { + void exactCodecPreservesDistinctAccountOperationCompleteSelectionAndOriginalWorldBytes() + throws Exception { var operation = fixture(); var restored = GameDesignPublicationOperation.fromStored(operation.canonicalBytes()); assertThat(restored.canonicalBytes()).isEqualTo(operation.canonicalBytes()); assertThat(restored.account().canonicalBytes()).isEqualTo(operation.account().canonicalBytes()); assertThat(restored.world().canonicalBytes()).isEqualTo(operation.world().canonicalBytes()); - assertThat(restored.selectionDigest()).isEqualTo("sha256:" + restored.world().request().requestDigest()); + assertThat(restored.selectionDigest()) + .isEqualTo("sha256:" + restored.world().request().requestDigest()); GameDesignPublicationOperationRepository.exact(operation, restored); } @Test - void changedAccountAllocationAndWorldFenceConflictInsteadOfReplacingOriginalOperation() throws Exception { + void changedAccountAllocationAndWorldFenceConflictInsteadOfReplacingOriginalOperation() + throws Exception { var operation = fixture(); var account = operation.account(); - var changedAccount = new GameDesignPublicationOperation(new AccountPublicationAuthorizationBinding( - UUID.randomUUID(), account.fenceId(), account.input(), account.sources()), operation.world()); - assertThatThrownBy(() -> GameDesignPublicationOperationRepository.exact(operation, changedAccount)) + var changedAccount = + new GameDesignPublicationOperation( + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), account.fenceId(), account.input(), account.sources()), + operation.world()); + assertThatThrownBy( + () -> GameDesignPublicationOperationRepository.exact(operation, changedAccount)) .isInstanceOf(IllegalArgumentException.class); var original = operation.world(); var request = original.request(); - var changedWorld = new GameDesignPublicationOperation(account, new WorldPublishedStartLocationEvidence( - new WorldPublishedStartLocationEvidence.Request(request.targetNamespace(), request.canonicalTenantId(), request.canonicalVersionId(), - request.intakeRequestId(), UUID.randomUUID(), request.publicationRequestId(), request.requestDigest(), request.versionStateEpoch(), - request.publishWorkflowId(), request.appliedCommitId(), request.contentDigest(), request.digestSchemaVersion(), request.worldAffectedTuples()), - original.selectorReceiptBytes(), original.originalAccountBindingBytes(), original.appliedResultBytes())); - assertThatThrownBy(() -> GameDesignPublicationOperationRepository.exact(operation, changedWorld)) + var changedWorld = + new GameDesignPublicationOperation( + account, + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + UUID.randomUUID(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + request.worldAffectedTuples()), + original.selectorReceiptBytes(), + original.originalAccountBindingBytes(), + original.appliedResultBytes())); + assertThatThrownBy( + () -> GameDesignPublicationOperationRepository.exact(operation, changedWorld)) .isInstanceOf(IllegalArgumentException.class); } @@ -48,22 +72,63 @@ void changedWorkflowOrSelectionDigestCannotConstructOwnerOperation() throws Exce var operation = fixture(); var original = operation.world(); var request = original.request(); - assertThatThrownBy(() -> new GameDesignPublicationOperation(operation.account(), new WorldPublishedStartLocationEvidence( - new WorldPublishedStartLocationEvidence.Request(request.targetNamespace(), request.canonicalTenantId(), request.canonicalVersionId(), - request.intakeRequestId(), request.publicationFence(), request.publicationRequestId(), "f".repeat(64), request.versionStateEpoch(), - request.publishWorkflowId(), request.appliedCommitId(), request.contentDigest(), request.digestSchemaVersion(), request.worldAffectedTuples()), - original.selectorReceiptBytes(), original.originalAccountBindingBytes(), original.appliedResultBytes()))) + assertThatThrownBy( + () -> + new GameDesignPublicationOperation( + operation.account(), + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + request.publicationFence(), + request.publicationRequestId(), + "f".repeat(64), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + request.worldAffectedTuples()), + original.selectorReceiptBytes(), + original.originalAccountBindingBytes(), + original.appliedResultBytes()))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new GameDesignPublicationOperation(operation.account(), new WorldPublishedStartLocationEvidence( - new WorldPublishedStartLocationEvidence.Request(request.targetNamespace(), request.canonicalTenantId(), request.canonicalVersionId(), - request.intakeRequestId(), request.publicationFence(), request.publicationRequestId(), request.requestDigest(), request.versionStateEpoch(), - "changed-workflow", request.appliedCommitId(), request.contentDigest(), request.digestSchemaVersion(), request.worldAffectedTuples()), - original.selectorReceiptBytes(), original.originalAccountBindingBytes(), original.appliedResultBytes()))) + assertThatThrownBy( + () -> + new GameDesignPublicationOperation( + operation.account(), + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + request.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + "changed-workflow", + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + request.worldAffectedTuples()), + original.selectorReceiptBytes(), + original.originalAccountBindingBytes(), + original.appliedResultBytes()))) .isInstanceOf(IllegalArgumentException.class); } private GameDesignPublicationOperation fixture() throws Exception { - return IsolatedPublicationOperationFixtures.fresh(new TargetProof(UUID.randomUUID(), UUID.randomUUID(), 7L, - "ISOLATED-tenant", 3L, "ISOLATED-tenant", "NEW_GAME_ROW")); + return IsolatedPublicationOperationFixtures.fresh( + new TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 7L, + "ISOLATED-tenant", + 3L, + "ISOLATED-tenant", + "NEW_GAME_ROW")); } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SelectedAuthoredDraftPublishWorkflowTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SelectedAuthoredDraftPublishWorkflowTest.java index 07579ab94c..ad889602fc 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SelectedAuthoredDraftPublishWorkflowTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SelectedAuthoredDraftPublishWorkflowTest.java @@ -18,6 +18,7 @@ import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository.SelectionSnapshot; +import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.PublishAttempt; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.mapper.VersionMapper; @@ -66,6 +67,7 @@ void newAttemptBindsExistingSelectedVersionAndDeniesBeforeUnreadyOwnerCarrier() when(f.versions.findByTenantIdAndIdForUpdate(request.tenantId(), 47L)) .thenReturn(Optional.of(version)); when(f.versions.findByTenantIdAndId(request.tenantId(), 47L)).thenReturn(Optional.of(version)); + when(f.games.findByTenantIdForUpdate(request.tenantId())).thenReturn(mock(Game.class)); PublishAttempt attempt = new PublishAttempt(); attempt.setTenantId(request.tenantId()); attempt.setVersionId(47L); @@ -120,6 +122,7 @@ private static final class Fixture { final AuthoredDraftPublishSelectionRepository selections = mock(AuthoredDraftPublishSelectionRepository.class); final VersionRepository versions = mock(VersionRepository.class); + final GameRepository games = mock(GameRepository.class); final PublishAttemptRepository attempts = mock(PublishAttemptRepository.class); final PublishAttemptService attemptService = mock(PublishAttemptService.class); final PublishGateService gate = mock(PublishGateService.class); @@ -152,7 +155,7 @@ private static final class Fixture { command = new VersionPublishCommandServiceImpl( versions, - mock(GameRepository.class), + games, attempts, Mappers.getMapper(VersionMapper.class), exports, diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java index f46b8c1578..ee3c457a0a 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java @@ -48,7 +48,10 @@ class VersionAssetExportCandidateServiceImplTest { @Mock private VersionRepository versionRepository; @Mock private net.firedevops.firemud.gamedesign.repository.GameRepository gameRepository; - @Mock private net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository attemptRepository; + + @Mock + private net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository attemptRepository; + @Mock private VersionAssetArtifactRepository artifactRepository; @Mock private VersionAssetPublicationService publicationService; @Mock private PlatformTransactionManager transactionManager; @@ -61,7 +64,8 @@ class VersionAssetExportCandidateServiceImplTest { @BeforeEach void setUp() { - lenient().when(gameRepository.findByTenantIdForUpdate(TENANT_ID)) + lenient() + .when(gameRepository.findByTenantIdForUpdate(TENANT_ID)) .thenReturn(new net.firedevops.firemud.gamedesign.entity.Game()); TransactionStatus transactionStatus = new SimpleTransactionStatus(); when(transactionManager.getTransaction(any(TransactionDefinition.class))) diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index b13fb6ebc1..fd49b0548e 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -347,7 +347,9 @@ private record SelectorReadback( void setup() { MockitoAnnotations.openMocks(this); when(publishAttemptRepository.findByPublishWorkflowIdForUpdate(any(String.class))) - .thenAnswer(invocation -> publishAttemptRepository.findByPublishWorkflowId(invocation.getArgument(0))); + .thenAnswer( + invocation -> + publishAttemptRepository.findByPublishWorkflowId(invocation.getArgument(0))); when(publishedReleaseBundleService.findPublishedReleaseBundle( any(String.class), any(Long.class))) .thenReturn(Optional.empty()); From df64052c4e21d98a5148009c74971383a4161f37 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 06:40:48 +1300 Subject: [PATCH 06/13] test(publication): retain exact export snapshot and prove legacy lifecycle denial --- .github/workflows/ci.yml | 2 +- .../draft/IsolatedPublicationOwnerSetup.java | 25 +++++++++++++++- ...aphApplicationPostgresIntegrationTest.java | 29 ++++++++++++------- 3 files changed, 43 insertions(+), 13 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4f57e4e0d3..96ff11b218 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2248,7 +2248,7 @@ jobs: bash dev-tools/validation/inspect-test-results.sh \ --strict \ --require-suite net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest \ - --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#lifecycleReadFollowsCurrentWorldEpochAndReturnsExactCanonicalServiceEcho()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#lifecycleReadPreservesPreparingStateAndDeniesLegacyNumericFailureWithExactCanonicalServiceEcho()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#releaseSelectorMaterializesItsOriginalRoomAndExactlyRetriesWithSeparateRuntimeMapping()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#releaseSelectorRejectsChangedFrozenRequestAndSqlSubstitutionWithoutRuntimeWrites()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#inertV1PreparationRetainsOriginalBytesAndCannotGainSelectorOnRetry()' \ diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java index 633ff8a343..eb70cc2937 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java @@ -17,6 +17,7 @@ import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import org.jooq.DSLContext; @@ -123,7 +124,21 @@ public static PublishedReleaseBundle commitStorage( versions .findByTenantIdAndIdForUpdate(operation.tenantKey(), operation.versionId()) .orElseThrow(); + var snapshot = + new VersionAssetPublicationRepository(dsl) + .freezeOrReadSnapshot(operation.tenantKey(), version.getVersionNumber()); PublishedReleaseBundle bundle = releaseWrite.get(); + if (snapshot.versionId() != operation.versionId() + || !snapshot.items().isEmpty() + || bundle.getManifestSchemaVersion() == null + || bundle.getManifestSchemaVersion() != 1 + || !"[]".equals(bundle.getArtifactDigestsJson()) + || !"[]".equals(bundle.getRequiredManifestAssetKeysJson()) + || bundle.getManifestHash() == null + || !bundle.getManifestHash().matches("sha256:[0-9a-f]{64}")) { + throw new IllegalStateException( + "Isolated publication fixture requires the exact empty asset candidate for its Version"); + } version.setVersionState(VersionLifecycleState.PUBLISHED); version.setVersionStateEpoch(Math.addExact(version.getVersionStateEpoch(), 1)); versions.save(version); @@ -137,7 +152,15 @@ public static PublishedReleaseBundle commitStorage( artifact.setLastWorkflowId(operation.workflowId()); artifact.setManifestSchemaVersion(bundle.getManifestSchemaVersion()); artifact.setArtifactDigestsJson(bundle.getArtifactDigestsJson()); - artifact.setPublishedObjectProofsJson("[]"); + artifact.setExportedManifestAssetKeysJson(bundle.getRequiredManifestAssetKeysJson()); + String manifestDigest = bundle.getManifestHash(); + artifact.setPublishedObjectProofsJson( + "[{\"immutableObjectKey\":\"manifests/sha256/" + + manifestDigest.substring("sha256:".length()) + + "\",\"contentDigest\":\"" + + manifestDigest + + "\"}]"); + artifact.setCandidateSnapshotVersionId(snapshot.versionId()); new VersionAssetArtifactRepository(dsl).save(artifact); attempt.setStatus(PublishAttemptStatus.SUCCEEDED); attempts.save(attempt); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index bf1e7b0ffb..a1270ebd16 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -204,7 +204,8 @@ void releaseSelectorMaterializesItsOriginalRoomAndExactlyRetriesWithSeparateRunt } @Test - void lifecycleReadFollowsCurrentWorldEpochAndReturnsExactCanonicalServiceEcho() { + void + lifecycleReadPreservesPreparingStateAndDeniesLegacyNumericFailureWithExactCanonicalServiceEcho() { Fixture f = fixture(); var original = application(generationFreePlan(f)); var roomTemplateId = @@ -365,20 +366,26 @@ void lifecycleReadFollowsCurrentWorldEpochAndReturnsExactCanonicalServiceEcho() .isTrue(); var prepareFields = materialized.association().worldPrepareFields(); - lifecycleCommandService.failPreparedWorldInstance( - prepareFields.privateTenantKey(), - prepareFields.privateGameInstanceKey(), - preparing.lifecycleEpoch(), - "integration lifecycle read movement"); - var failedCurrent = lifecycleRepository.read(request).orElseThrow(); - assertThat(failedCurrent.lifecycleStatus()).isEqualTo("FAILED_PRE_ACTIVATION"); - assertThat(failedCurrent.lifecycleEpoch()).isEqualTo(2L); - assertThat(failedCurrent.rowVersion()).isGreaterThan(preparing.rowVersion()); + // Successful ACTIVE epoch movement and historical retry after a later lifecycle move belong + // to the canonical activation proof, including + // canonicalActivationCommitsOneOwnerCasAndReplaysItsImmutableResultAfterLaterLifecycleMove. + // This front owns preparation storage and lifecycle read only; its legacy numeric writer must + // remain denied for the reserved canonical tenant. + assertThatThrownBy( + () -> + lifecycleCommandService.failPreparedWorldInstance( + prepareFields.privateTenantKey(), + prepareFields.privateGameInstanceKey(), + preparing.lifecycleEpoch(), + "integration lifecycle read movement")) + .hasStackTraceContaining("no exact transaction execution manifest"); + var afterDeniedFailure = lifecycleRepository.read(request).orElseThrow(); + assertThat(afterDeniedFailure).isEqualTo(preparing); // The real V35 retry preserves immutable preparation history and does not rewrite lifecycle. assertThat(preparation.prepare(input)).isEqualTo(materialized); var afterRetry = lifecycleRepository.read(request).orElseThrow(); - assertThat(afterRetry).isEqualTo(failedCurrent); + assertThat(afterRetry).isEqualTo(preparing); // Explicitly injected peer identity is a transport double; this does not prove production mTLS. var adapter = From 45445bcbf994839ebf0f3f0c79821ada714495d1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 06:42:48 +1300 Subject: [PATCH 07/13] ci(publication): bind strict operation proof to actual suite identity --- .github/workflows/ci.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 96ff11b218..f8d93f4837 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2316,11 +2316,11 @@ jobs: run: | bash dev-tools/validation/inspect-test-results.sh \ --strict \ - --require-suite net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest \ - --require-case 'net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#noPublicationReceiptReplaysAfterLostResponseAndExcludesDelayedFinalizerAndRawInsert()' \ - --require-case 'net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#publishedReceiptCannotBeDemotedByStaleFailureAndRetainsOriginalFreezeEpoch()' \ - --require-case 'net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#failedAtomicCommitLeavesAttemptOperationVersionAndReleasePendingForExactRetry()' \ - --require-case 'net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#noPublicationSerializesAgainstAnAlreadyScheduledLatePublisher()' \ + --require-suite integration.net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#noPublicationReceiptReplaysAfterLostResponseAndExcludesDelayedFinalizerAndRawInsert()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#publishedReceiptCannotBeDemotedByStaleFailureAndRetainsOriginalFreezeEpoch()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#failedAtomicCommitLeavesAttemptOperationVersionAndReleasePendingForExactRetry()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#noPublicationSerializesAgainstAnAlreadyScheduledLatePublisher()' \ game-design-service - name: Capture World authored-graph snapshot PostgreSQL XML From d83a41a4896006dbb71d355ca379f48dbb116377 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 06:43:21 +1300 Subject: [PATCH 08/13] ci(account): require the actual publication participation suite --- .github/workflows/ci.yml | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f8d93f4837..a4051e5e72 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2218,19 +2218,19 @@ jobs: run: | bash dev-tools/validation/inspect-test-results.sh \ --strict \ - --require-suite net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest \ - --require-case 'net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#exactReserveOrderAndRestartReadbackPreserveOriginalBytes()' \ - --require-case 'net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#changedRequestCaptureActorOrAllocatedIdentityCannotReplaceOriginal()' \ - --require-case 'net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#sourceChangeRevokesReservedPublicationButCannotCommitOrAbortWithoutItsOwnTerminalContract()' \ - --require-case 'net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#publicationOrderRemainsUnresolvedAfterOriginalDraftTerminalResults()' \ - --require-case 'net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#waitingChangeDeniesNewReservationAndUnrelatedScopeStillProceeds()' \ - --require-case 'net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#concurrentPublicationClaimAndSourceChangeChooseOneDurableOrder()' \ - --require-case 'net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#rawSqlCannotReplaceOriginalSourceBindingOrOrderOrTruncateEvidence()' \ - --require-case 'net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#failedOwnerTransactionRollsBackReservationAndParticipation()' \ - --require-case 'net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#concurrentExactReservationReturnsOneImmutableOperation()' \ - --require-case 'net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#rawSqlCannotReserveIncompleteSourceParticipationOrSubstituteRequestIdentity()' \ - --require-case 'net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#sqlPreservesJavaSourceLockOrderingForSupplementaryUnicodeScopes()' \ - --require-case 'net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#missingCurrentSchemaFailsClosedAndUpgradePreservesOriginalDraftEvidence()' \ + --require-suite integration.net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#exactReserveOrderAndRestartReadbackPreserveOriginalBytes()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#changedRequestCaptureActorOrAllocatedIdentityCannotReplaceOriginal()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#sourceChangeRevokesReservedPublicationButCannotCommitOrAbortWithoutItsOwnTerminalContract()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#publicationOrderRemainsUnresolvedAfterOriginalDraftTerminalResults()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#waitingChangeDeniesNewReservationAndUnrelatedScopeStillProceeds()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#concurrentPublicationClaimAndSourceChangeChooseOneDurableOrder()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#rawSqlCannotReplaceOriginalSourceBindingOrOrderOrTruncateEvidence()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#failedOwnerTransactionRollsBackReservationAndParticipation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#concurrentExactReservationReturnsOneImmutableOperation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#rawSqlCannotReserveIncompleteSourceParticipationOrSubstituteRequestIdentity()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#sqlPreservesJavaSourceLockOrderingForSupplementaryUnicodeScopes()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#missingCurrentSchemaFailsClosedAndUpgradePreservesOriginalDraftEvidence()' \ account-service - name: Capture World Account-bound graph application PostgreSQL raw XML From c51596a42bd42d03cc29c2d58442bfb79d4fdfc6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 07:42:34 +1300 Subject: [PATCH 09/13] fix(publication): preserve canonical no-publication receipts and executed proof --- .github/workflows/ci.yml | 16 ++++- .../game-design-service/operations.md | 8 +-- dev-tools/tests/architecture-doc-contracts.sh | 3 +- ...eDesignPublicationOperationRepository.java | 6 +- ...aunchDescriptorServiceIntegrationTest.java | 58 ++++++++++++++++--- .../GameDesignPublicationOperationTest.java | 39 +++++++++++++ 6 files changed, 114 insertions(+), 16 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a4051e5e72..c70edd6db4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -962,6 +962,7 @@ jobs: --tests integration.net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepositoryIntegrationTest \ --tests integration.net.firedevops.firemud.gamedesign.service.impl.VersionAssetExportCandidateServiceIntegrationTest \ --tests net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepositoryIntegrationTest \ + --tests integration.net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest \ -PfullCheck --no-build-cache --no-configuration-cache bash dev-tools/validation/inspect-test-results.sh \ --strict \ @@ -973,6 +974,7 @@ jobs: --require-suite integration.net.firedevops.firemud.gamedesign.service.impl.VersionAssetExportCandidateServiceIntegrationTest \ --require-suite net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepositoryIntegrationTest \ --require-suite net.firedevops.firemud.gamedesign.service.EntityDigestBaselineMigrationIntegrationTest \ + --require-suite integration.net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest#appliesAuditedAssociationForFreshAndRetainedGameSources()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest#versionLockRepositoryUsesConfiguredIsolatedOwnerSchema()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest#concurrentExactFirstWritersReturnOneImmutableReceipt()' \ @@ -1015,8 +1017,19 @@ jobs: --require-case 'net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepositoryIntegrationTest#saveAndFindRoundTripTimestampFields()' \ --require-case 'net.firedevops.firemud.gamedesign.service.EntityDigestBaselineMigrationIntegrationTest#exactRetryReadsCommittedEvidenceWithoutCallingEntityAgain()' \ --require-case 'net.firedevops.firemud.gamedesign.service.EntityDigestBaselineMigrationIntegrationTest#databaseMigrationRolesHaveOnlyTheirDirectTablePrivileges()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#noPublicationReceiptReplaysAfterLostResponseAndExcludesDelayedFinalizerAndRawInsert()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#publishedReceiptCannotBeDemotedByStaleFailureAndRetainsOriginalFreezeEpoch()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#failedAtomicCommitLeavesAttemptOperationVersionAndReleasePendingForExactRetry()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#noPublicationSerializesAgainstAnAlreadyScheduledLatePublisher()' \ game-design-service + - name: Preserve Game Design publication operation XML before later selectors + if: ${{ always() && matrix.module == 'game-design-service' }} + run: | + preserved_results=services/game-design-service/build/publication-operation-proof/services/game-design-service/build/test-results/integrationTest + mkdir -p "$preserved_results" + cp services/game-design-service/build/test-results/integrationTest/TEST-*GameDesignPublicationOperationPostgresIntegrationTest.xml "$preserved_results/" + - name: Verify Game Design fresh tenant creation PostgreSQL proof if: ${{ !cancelled() && matrix.module == 'game-design-service' }} run: | @@ -2307,7 +2320,7 @@ jobs: uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 with: name: game-design-publication-operation-postgresql-proof-${{ github.sha }}-${{ github.run_attempt }} - path: services/game-design-service/build/test-results/integrationTest/TEST-*GameDesignPublicationOperationPostgresIntegrationTest.xml + path: services/game-design-service/build/publication-operation-proof/services/game-design-service/build/test-results/integrationTest/TEST-*GameDesignPublicationOperationPostgresIntegrationTest.xml if-no-files-found: error retention-days: 7 @@ -2316,6 +2329,7 @@ jobs: run: | bash dev-tools/validation/inspect-test-results.sh \ --strict \ + --root services/game-design-service/build/publication-operation-proof \ --require-suite integration.net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest \ --require-case 'integration.net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#noPublicationReceiptReplaysAfterLostResponseAndExcludesDelayedFinalizerAndRawInsert()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#publishedReceiptCannotBeDemotedByStaleFailureAndRetainsOriginalFreezeEpoch()' \ diff --git a/design/architecture/microservices/game-design-service/operations.md b/design/architecture/microservices/game-design-service/operations.md index 075ff65367..812cdee1e2 100644 --- a/design/architecture/microservices/game-design-service/operations.md +++ b/design/architecture/microservices/game-design-service/operations.md @@ -8,17 +8,17 @@ ### Publish request identity and digest binding -Full-version `PublishVersion` selects an existing authored Draft. The immutable `AuthoredDraftPublishSelection` is the canonical binding for the complete caller selection and the synchronized Draft evidence; its `versionId` is supplied at request admission, and reservation does not allocate a replacement Version. Exact retries retain that first selection, while changed or omitted selection input conflicts before workflow attachment. The [Game Design API contract](./api-contracts.md#draft-commit-and-proposal-semantics-target-state) owns the selection fields and evidence. The separate, approved Account publication authorization and complete publication-operation identity must bind to that selection without replacing it; Account's [hosted-terms and creator-party contract](../account-service/api-contracts.md#account-owned-hosted-terms-and-creator-party) owns currentness authority, and World Management's [publication freeze and terminal handoff](../world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state) owns the World fence. These publication-level bindings remain unimplemented. This adopter behavior follows [ADR 0078](../../decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md). +Full-version `PublishVersion` selects an existing authored Draft. The immutable `AuthoredDraftPublishSelection` is the canonical binding for the complete caller selection and the synchronized Draft evidence; its `versionId` is supplied at request admission, and reservation does not allocate a replacement Version. Exact retries retain that first selection, while changed or omitted selection input conflicts before workflow attachment. The [Game Design API contract](./api-contracts.md#draft-commit-and-proposal-semantics-target-state) owns the selection fields and evidence. The approved Account publication authorization and complete publication-operation identity must bind to that selection without replacing it; Account's [hosted-terms and creator-party contract](../account-service/api-contracts.md#account-owned-hosted-terms-and-creator-party) owns currentness authority, and World Management's [publication freeze and terminal handoff](../world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state) owns the World fence. The authenticated producers and composed Account/World handoff remain unavailable; the current partial storage boundary is summarized below and tracked in [Game authoring, publishing, and activation](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) and [Player access and session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). This adopter behavior follows [ADR 0078](../../decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md). -**Current implementation status:** the selected full-version `publish_attempt` stores and exact-validates `AuthoredDraftPublishSelection.digest()`, which binds the complete caller selection together with its retained target and synchronized-Draft evidence. The selection and its canonical bytes are stored separately and immutably. This is distinct from `publicationDigestRequest/v1`, which remains the owner-to-owner digest-read request binding and does not replace the selected attempt digest. Public full-version publication still denies before workflow dispatch when Account authorization is unavailable; the separate Account publication operation and complete publication-operation identity are not implemented. +**Current implementation status:** the selected full-version `publish_attempt` stores and exact-validates `AuthoredDraftPublishSelection.digest()`, which binds the complete caller selection together with its retained target and synchronized-Draft evidence. The selection and its canonical bytes are stored separately and immutably. This is distinct from `publicationDigestRequest/v1`, which remains the owner-to-owner digest-read request binding and does not replace the selected attempt digest. The #3029 candidate also contains unwired Account V79 publication-participation storage and a shared selected-Draft codec, plus Game Design's unregistered V50 publication-operation store and terminal-seal guard. These are partial owner-local persistence primitives; they do not provide an authenticated current-source producer, public publication dispatch, a verified World freeze handoff, or composed owner terminal verification and settlement. Public full-version publication still denies before workflow dispatch when Account authorization is unavailable. Current implementation and proof gaps remain in [Game authoring, publishing, and activation](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) and [Player access and session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). ### Publication terminality and attempt ownership The publication artifact/release-bundle state, allocated version state, participant/release evidence, and publish-attempt terminal state must commit atomically in one Game Design owner-local transaction. If the workflow boundary cannot provide that transaction, the adopter must use an explicit durable state machine with readback reconciliation; it must never expose `SUCCEEDED` until the artifact and version commit is durably readable and bound to the same immutable request and attempt evidence. A terminal attempt is therefore not an acknowledgement that a separate transaction was started: it is the commit/readback proof of the publication state. -**Current implementation status:** full-version publication reserves the selected existing Draft and PENDING attempt in one owner-local transaction. After participant reads and object export, its final owner-local transaction records participant evidence, artifact state, release bundle, Published version, verified digests, and the SUCCEEDED attempt together. An ambiguous final commit is resolved by exact attempt/version/bundle/artifact readback rather than an independent terminal-success transaction. This success path is behind the required participant digest gate: ordinary full-version requests currently cannot reach it because Game Logic rejects the required full-version participant request without an owner-local manifest/provenance digest. The canonical participant gate and current availability are documented in [Version Control](./version-control.md#owner-to-owner-digest-authorization-and-tenant-identity); script-patch publication does not require the Game Logic participant. The ordinary-byte exporter now commits and independently reads its exact private candidate before conditional content-addressed writes and byte readback. This does not prove complete publication-attempt ownership, authenticated terminal settlement, abandonment or cleanup; those gates remain separately open in [Asset Storage](./asset-storage.md#implementation-status). +**Current implementation status:** full-version publication reserves the selected existing Draft and PENDING attempt in one owner-local transaction. After participant reads and object export, its final owner-local transaction records participant evidence, artifact state, release bundle, Published version, verified digests, and the SUCCEEDED attempt together. An ambiguous final commit is resolved by exact attempt/version/bundle/artifact readback rather than an independent terminal-success transaction. This implemented success path is behind the required participant digest gate: ordinary full-version requests currently cannot reach it because Game Logic rejects the required full-version participant request without an owner-local manifest/provenance digest. The canonical participant gate and current availability are documented in [Version Control](./version-control.md#owner-to-owner-digest-authorization-and-tenant-identity); script-patch publication does not require the Game Logic participant. For a definitive publication failure, `VersionPublishCommandServiceImpl` returns the attempt snapshot as terminal `FAILED` only after exact owner-transaction readback confirms there is no release, any exported candidate has exact staged evidence, and the same transaction records the failure and `NO_PUBLICATION` seal. If transaction settlement, readback, or sealing is uncertain or contradictory, the outcome remains reconciliation-required; `TemporalVersionPublishActivitiesImpl` maps only `PendingReconciliationException` to `PENDING`. A timeout, failure exception, absent release row, or `FAILED` status without the committed seal does not authorize terminal no-publication or World Management's `ABORTED` handoff. The ordinary-byte exporter now commits and independently reads its exact private candidate before conditional content-addressed writes and byte readback. This does not prove complete publication-attempt ownership, authenticated terminal settlement, abandonment or cleanup; those gates remain separately open in [Asset Storage](./asset-storage.md#implementation-status). -The existing attempt `FAILED` status and a read showing no release evidence are not immutable publication no-publication proof. Game Design has no publication-specific authenticated terminal readback that fences a delayed finalizer; its [authored-Draft terminal readback](./api-contracts.md#exact-authored-draft-terminal-readback) covers Draft commits, not publication. A missing row or artifact, a `FAILED` status, or a Temporal timeout must therefore remain pending/reconciliation evidence and must not authorize World Management's `ABORTED` handoff. The required publication-specific readback and full-operation binding remain owner-contract and implementation gaps; see the [World publication handoff](../world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state) and the [Account hosted-creator authority contract](../account-service/api-contracts.md#account-owned-hosted-terms-and-creator-party). +The existing attempt `FAILED` status and a read showing no release evidence are not immutable publication no-publication proof. Game Design has no production-wired or registered publication-specific authenticated terminal readback that fences a delayed finalizer; the partial V50 operation store and terminal-seal guard described above do not provide that reader. Its [authored-Draft terminal readback](./api-contracts.md#exact-authored-draft-terminal-readback) covers Draft commits, not publication. A missing row or artifact, a `FAILED` status, or a Temporal timeout must therefore remain pending/reconciliation evidence and must not authorize World Management's `ABORTED` handoff. The production-wired owner readback and complete current Account/World handoff and terminal settlement remain implementation gaps; see the [World publication handoff](../world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state) and the [Account hosted-creator authority contract](../account-service/api-contracts.md#account-owned-hosted-terms-and-creator-party). The target publication operation must retain the exact selected-Draft binding and keep its Account authorization and World freeze identity bound to the same stable workflow/request. Allocated artifact/release identity, participant evidence, and the final owner outcome are result evidence for that operation, not replacement caller-input digests; the selected existing Version remains part of the original input. Every attempt transition must CAS the expected status and monotonic attempt revision; only the still-current attempt owner may publish a terminal result. Failure cleanup must conditionally own the same nonterminal attempt and prove the target has not been won or published. Every transition must prevent a delayed finalizer from publishing after an immutable no-publication outcome is recorded. That outcome requires authenticated Game Design owner evidence for the exact operation and World fence; failed status, absent evidence, or timeout alone is never terminal. Same-identity exact retries read back the original selection and operation outcome; changed binding, stale attempt status/revision or contradictory release/Version readback fails closed. Focused proof must cover crashes before and after each commit/readback boundary, concurrent exact retries, changed selection, a losing failure cleanup racing a winning publisher, and a no-publication outcome racing a delayed finalizer. diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index 8fac6f243a..cfc1e62e32 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -2648,7 +2648,8 @@ require_contains( require_contains( "design/architecture/microservices/game-design-service/operations.md", [ - "`VersionPublishCommandServiceImpl` normally records terminal `FAILED` and returns the attempt snapshot for publication failures; `TemporalVersionPublishActivitiesImpl` catches only `PendingReconciliationException` and returns `PENDING`.", + "For a definitive publication failure, `VersionPublishCommandServiceImpl` returns the attempt snapshot as terminal `FAILED` only after exact owner-transaction readback confirms there is no release, any exported candidate has exact staged evidence, and the same transaction records the failure and `NO_PUBLICATION` seal.", + "If transaction settlement, readback, or sealing is uncertain or contradictory, the outcome remains reconciliation-required; `TemporalVersionPublishActivitiesImpl` maps only `PendingReconciliationException` to `PENDING`.", ], ) require_contains( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java index 5f1e20c4fe..7e66d84041 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java @@ -148,7 +148,11 @@ private static byte[] receipt( DraftAuthorizationFenceBinding.frame(out, "game-design-publication-owner-readback/v1"); DraftAuthorizationFenceBinding.frame(out, operation.canonicalBytes()); DraftAuthorizationFenceBinding.frame(out, outcome); - DraftAuthorizationFenceBinding.frame(out, evidence == null ? "" : evidence); + if (evidence == null) { + DraftAuthorizationFenceBinding.frame(out, new byte[0]); + } else { + DraftAuthorizationFenceBinding.frame(out, evidence); + } return out.toByteArray(); } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java index 8862c7874a..5a1088a3a8 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.time.LocalDateTime; +import java.util.LinkedHashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.CountDownLatch; @@ -521,6 +522,7 @@ void v39MigrationPreservesRetainedPublicationEvidenceAndStoresLongDiagnostics() migrate(dataSource, schema, MigrationVersion.fromVersion("38")); String retainedFailure = "retained-failure-雪-" + suffix; String retainedArtifactError = "retained-artifact-error-🧭-" + suffix; + String attemptWorkflowId = "v38-retained-attempt-" + suffix; long attemptId = requiredId( isolatedDsl @@ -531,7 +533,7 @@ void v39MigrationPreservesRetainedPublicationEvidenceAndStoresLongDiagnostics() + "VALUES (?, ?, 'FULL_VERSION', 'FAILED', ?, 1, 'PUBLISH_FAILED', ?, " + "TIMESTAMP '2026-09-30 12:34:56') RETURNING id", tenantId, - "v38-retained-attempt-" + suffix, + attemptWorkflowId, versionId, retainedFailure) .fetchOne(0, Long.class), @@ -557,10 +559,28 @@ void v39MigrationPreservesRetainedPublicationEvidenceAndStoresLongDiagnostics() publicationEvidenceRows( isolatedDsl, versionId, bundleId, descriptorId, attemptId, artifactId); migrate(dataSource, schema, null); + Map> migratedRows = + publicationEvidenceRows( + isolatedDsl, versionId, bundleId, descriptorId, attemptId, artifactId); + assertThat(priorPublicationEvidenceColumns(migratedRows)) + .isEqualTo(priorPublicationEvidenceColumns(retainedRows)); + assertThat(requiredSnapshot(migratedRows, "publish_attempt").get("revision")).isEqualTo(1L); assertThat( - publicationEvidenceRows( - isolatedDsl, versionId, bundleId, descriptorId, attemptId, artifactId)) - .isEqualTo(retainedRows); + requiredSnapshot(migratedRows, "published_release_bundle") + .get("world_published_start_location_evidence_json")) + .isNull(); + var publicationOperationCount = + isolatedDsl.fetchOne( + "SELECT count(*) FROM game_design_publication_operation WHERE publish_workflow_id = ?", + attemptWorkflowId); + if (publicationOperationCount == null) { + throw new IllegalStateException("Publication operation count query returned no row"); + } + Long publicationOperationCountValue = publicationOperationCount.get(0, Long.class); + if (publicationOperationCountValue == null) { + throw new IllegalStateException("Publication operation count query returned no count"); + } + assertThat(publicationOperationCountValue).isZero(); assertThat( requiredSnapshot(retainedRows, "published_release_bundle") .get("generation_config_revision")) @@ -1184,33 +1204,53 @@ private Map> publicationEvidenceRows( long artifactId) { return Map.of( "version", - requiredRow(isolatedDsl, "SELECT * FROM version WHERE id = ?", versionId, "Version"), + requiredRow( + isolatedDsl, + "SELECT *, xmin::text AS xmin FROM version WHERE id = ?", + versionId, + "Version"), "published_release_bundle", requiredRow( isolatedDsl, - "SELECT * FROM published_release_bundle WHERE id = ?", + "SELECT *, xmin::text AS xmin FROM published_release_bundle WHERE id = ?", bundleId, "published release bundle"), "launch_descriptor", requiredRow( isolatedDsl, - "SELECT * FROM launch_descriptor WHERE id = ?", + "SELECT *, xmin::text AS xmin FROM launch_descriptor WHERE id = ?", descriptorId, "launch descriptor"), "publish_attempt", requiredRow( isolatedDsl, - "SELECT * FROM publish_attempt WHERE id = ?", + "SELECT *, xmin::text AS xmin FROM publish_attempt WHERE id = ?", attemptId, "publish attempt"), "version_asset_artifact", requiredRow( isolatedDsl, - "SELECT * FROM version_asset_artifact WHERE id = ?", + "SELECT *, xmin::text AS xmin FROM version_asset_artifact WHERE id = ?", artifactId, "version asset artifact")); } + private Map> priorPublicationEvidenceColumns( + Map> snapshots) { + Map> originalColumns = new LinkedHashMap<>(); + snapshots.forEach( + (table, snapshot) -> { + Map original = new LinkedHashMap<>(snapshot); + if ("published_release_bundle".equals(table)) { + original.remove("world_published_start_location_evidence_json"); + } else if ("publish_attempt".equals(table)) { + original.remove("revision"); + } + originalColumns.put(table, original); + }); + return originalColumns; + } + private Map requiredRow( DSLContext isolatedDsl, String query, long rowId, String description) { var row = isolatedDsl.fetchOne(query, rowId); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationTest.java index 437c43ebbe..fe3b7a37f4 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationTest.java @@ -3,7 +3,11 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; @@ -120,6 +124,32 @@ void changedWorkflowOrSelectionDigestCannotConstructOwnerOperation() throws Exce .isInstanceOf(IllegalArgumentException.class); } + @Test + void ownerReceiptUsesEmptyByteFrameForNoPublicationAndPreservesExactPublishedTextEvidence() + throws Exception { + var operation = fixture(); + byte[] noPublication = invokeReceipt(operation, "NO_PUBLICATION", null); + var absentReader = new DraftAuthorizationFenceBinding.FrameReader(noPublication); + absentReader.expect("game-design-publication-owner-readback/v1"); + assertThat(absentReader.bytes()).isEqualTo(operation.canonicalBytes()); + assertThat(absentReader.text()).isEqualTo("NO_PUBLICATION"); + assertThat(absentReader.bytes()).isEmpty(); + absentReader.requireEnd(); + + String releaseEvidence = "{\"release\":\"published-雪-🧭\"}"; + byte[] published = invokeReceipt(operation, "PUBLISHED", releaseEvidence); + var publishedReader = new DraftAuthorizationFenceBinding.FrameReader(published); + publishedReader.expect("game-design-publication-owner-readback/v1"); + assertThat(publishedReader.bytes()).isEqualTo(operation.canonicalBytes()); + assertThat(publishedReader.text()).isEqualTo("PUBLISHED"); + assertThat(publishedReader.bytes()).isEqualTo(releaseEvidence.getBytes(StandardCharsets.UTF_8)); + publishedReader.requireEnd(); + + assertThatThrownBy(() -> invokeReceipt(operation, "PUBLISHED", "")) + .isInstanceOf(InvocationTargetException.class) + .hasCauseInstanceOf(IllegalArgumentException.class); + } + private GameDesignPublicationOperation fixture() throws Exception { return IsolatedPublicationOperationFixtures.fresh( new TargetProof( @@ -131,4 +161,13 @@ private GameDesignPublicationOperation fixture() throws Exception { "ISOLATED-tenant", "NEW_GAME_ROW")); } + + private byte[] invokeReceipt( + GameDesignPublicationOperation operation, String outcome, String evidence) throws Exception { + Method method = + GameDesignPublicationOperationRepository.class.getDeclaredMethod( + "receipt", GameDesignPublicationOperation.class, String.class, String.class); + method.setAccessible(true); + return (byte[]) method.invoke(null, operation, outcome, evidence); + } } From 7325099e5b7f98e7e2a53d552ef51e245e0f6453 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 08:16:28 +1300 Subject: [PATCH 10/13] fix: stage durable publication candidate proof and preserve CI ordering --- .github/workflows/ci.yml | 14 +- ...ationOperationPostgresIntegrationTest.java | 148 +++++++++++++++--- 2 files changed, 136 insertions(+), 26 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c70edd6db4..e4320c0fdc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1023,13 +1023,6 @@ jobs: --require-case 'integration.net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#noPublicationSerializesAgainstAnAlreadyScheduledLatePublisher()' \ game-design-service - - name: Preserve Game Design publication operation XML before later selectors - if: ${{ always() && matrix.module == 'game-design-service' }} - run: | - preserved_results=services/game-design-service/build/publication-operation-proof/services/game-design-service/build/test-results/integrationTest - mkdir -p "$preserved_results" - cp services/game-design-service/build/test-results/integrationTest/TEST-*GameDesignPublicationOperationPostgresIntegrationTest.xml "$preserved_results/" - - name: Verify Game Design fresh tenant creation PostgreSQL proof if: ${{ !cancelled() && matrix.module == 'game-design-service' }} run: | @@ -1065,6 +1058,13 @@ jobs: if-no-files-found: error retention-days: 7 + - name: Preserve Game Design publication operation XML before later selectors + if: ${{ always() && matrix.module == 'game-design-service' }} + run: | + preserved_results=services/game-design-service/build/publication-operation-proof/services/game-design-service/build/test-results/integrationTest + mkdir -p "$preserved_results" + cp services/game-design-service/build/test-results/integrationTest/TEST-*GameDesignPublicationOperationPostgresIntegrationTest.xml "$preserved_results/" + - name: Run Game Design authored-source launch descriptor PostgreSQL and socket mTLS proof if: ${{ matrix.module == 'game-design-service' }} run: | diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java index 132586e236..b38be50aca 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java @@ -4,6 +4,10 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.List; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; @@ -12,21 +16,28 @@ import net.firedevops.firemud.common.config.PostgresProperties; import net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup; import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.GameAsset; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.entity.Version; -import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationService; +import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; +import net.firedevops.firemud.gamedesign.service.impl.VersionAssetArtifactServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.VersionAssetExportCandidateServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.VersionAssetPublicationServiceImpl; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -48,7 +59,11 @@ class GameDesignPublicationOperationPostgresIntegrationTest { @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); - private static final String MANIFEST = "sha256:" + "a".repeat(64); + private static final String ASSET_FILE_NAME = "publication-operation-logo.png"; + private static final String ASSET_CONTENT_TYPE = "image/png"; + private static final byte[] ASSET_BYTES = + "isolated publication asset bytes".getBytes(StandardCharsets.UTF_8); + private static final String PUBLIC_BASE_URL = "https://assets.example.invalid/assets"; @Test void noPublicationReceiptReplaysAfterLostResponseAndExcludesDelayedFinalizerAndRawInsert() @@ -233,17 +248,13 @@ private void publishInTransaction(Fixture fixture) { version.setVersionState(VersionLifecycleState.PUBLISHED); version.setVersionStateEpoch(version.getVersionStateEpoch() + 1); fixture.versions().save(version); - var artifact = new VersionAssetArtifact(); - artifact.setTenantId(op.tenantKey()); - artifact.setVersionId(op.versionId()); + var artifact = + fixture + .artifacts() + .findByTenantIdAndVersionIdForUpdate(op.tenantKey(), op.versionId()) + .orElseThrow(); artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); - artifact.setStateEpoch(1); - artifact.setExportedVersionNumber(version.getVersionNumber()); - artifact.setManifestHash(MANIFEST); - artifact.setLastWorkflowId(op.workflowId()); - artifact.setManifestSchemaVersion(1); - artifact.setArtifactDigestsJson("[]"); - artifact.setPublishedObjectProofsJson("[]"); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); fixture.artifacts().save(artifact); var attempt = fixture.attempts().findByPublishWorkflowIdForUpdate(op.workflowId()).orElseThrow(); @@ -264,10 +275,12 @@ private PublishedReleaseBundle bundle(Fixture fixture) { bundle.setCanonicalVersionId(op.world().request().canonicalVersionId()); bundle.setAttestationSchemaVersion("v2"); bundle.setPublishWorkflowId(op.workflowId()); - bundle.setManifestHash(MANIFEST); + bundle.setManifestHash(fixture.candidate().manifestHash()); bundle.setManifestSchemaVersion(1); - bundle.setArtifactDigestsJson("[]"); - bundle.setRequiredManifestAssetKeysJson("[]"); + bundle.setArtifactDigestsJson( + new ObjectMapper().writeValueAsString(fixture.candidate().artifactDigests())); + bundle.setRequiredManifestAssetKeysJson( + new ObjectMapper().writeValueAsString(fixture.candidate().requiredManifestAssetKeys())); bundle.setCommandDefinitionsJson("[]"); bundle.setGenerationConfigRevision("generation-1"); bundle.setParticipantDigestsJson( @@ -294,7 +307,7 @@ private void rawReleaseInsert(Fixture fixture) { bundle.getCanonicalVersionId(), UUID.randomUUID().toString(), bundle.getPublishWorkflowId(), - MANIFEST, + bundle.getManifestHash(), bundle.getGenerationConfigRevision(), bundle.getParticipantDigestsJson(), bundle.getWorldPublishedStartLocationEvidenceJson()); @@ -366,16 +379,112 @@ private Fixture fixture() throws Exception { } }); var operations = new GameDesignPublicationOperationRepository(dsl); + var gameAssets = new GameAssetRepository(dsl); + var asset = + write.execute( + status -> { + var requested = new GameAsset(); + requested.setTenantId(game.getTenantId()); + requested.setFileName(ASSET_FILE_NAME); + requested.setContentType(ASSET_CONTENT_TYPE); + requested.setData(ASSET_BYTES); + return gameAssets.save(requested); + }); + var publicationRepository = new VersionAssetPublicationRepository(dsl); + var publicationService = + new VersionAssetPublicationServiceImpl(transactions, publicationRepository); + publicationService.associateDraftAsset( + game.getTenantId(), version.getId(), asset.getId(), "logo"); + var snapshot = + publicationService.freezeOrReadSnapshot(game.getTenantId(), version.getVersionNumber()); + var artifactService = + new VersionAssetArtifactServiceImpl( + new VersionAssetArtifactRepository(dsl), + null, + versions, + null, + null, + null, + null, + null, + new ObjectMapper()); + write.execute( + status -> + artifactService.stageExport( + game.getTenantId(), + version.getId(), + version.getVersionNumber(), + operation.workflowId())); + var artifacts = new VersionAssetArtifactRepository(dsl); + var candidateService = + new VersionAssetExportCandidateServiceImpl( + versions, + games, + new PublishAttemptRepository(dsl), + artifacts, + publicationService, + transactions, + new ObjectMapper()); + var requestedCandidate = candidate(snapshot); + var committedCandidate = + candidateService.recordExportCandidate( + game.getTenantId(), version.getVersionNumber(), requestedCandidate); + var readCandidate = + candidateService.readExportCandidate(game.getTenantId(), version.getVersionNumber()); + assertThat(committedCandidate).isEqualTo(requestedCandidate); + assertThat(readCandidate).isEqualTo(committedCandidate); return new Fixture( dsl, write, versions, new PublishAttemptRepository(dsl), new PublishedReleaseBundleRepository(dsl), - new VersionAssetArtifactRepository(dsl), + artifacts, operations, new GameDesignPublicationOperationService(operations, transactions), - operation); + operation, + readCandidate); + } + + private ExportedAssetManifest candidate( + VersionAssetPublicationRepository.ExportSnapshot snapshot) { + var source = snapshot.items().get(0); + String contentDigest = source.contentDigest(); + String objectKey = "artifacts/sha256/" + contentDigest.substring("sha256:".length()); + var digest = + new PublishedArtifactDigest( + source.usageKey(), "BINARY", objectKey, contentDigest, source.contentType(), 1); + String url = PUBLIC_BASE_URL + "/" + objectKey; + String manifestJson = + "{\"schemaVersion\":1,\"assets\":{\"" + + source.usageKey() + + "\":{\"usageKey\":\"" + + source.usageKey() + + "\",\"artifactKind\":\"BINARY\",\"immutableObjectKey\":\"" + + objectKey + + "\",\"contentDigest\":\"" + + contentDigest + + "\",\"contentType\":\"" + + source.contentType() + + "\",\"artifactSchemaVersion\":1,\"producerService\":\"game-design-service\",\"versionId\":\"" + + snapshot.canonicalVersionId() + + "\",\"url\":\"" + + url + + "\"}}}"; + return new ExportedAssetManifest( + sha256(manifestJson.getBytes(StandardCharsets.UTF_8)), + 1, + List.of(source.usageKey()), + List.of(digest)); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } } private static void await(CountDownLatch latch) { @@ -397,5 +506,6 @@ private record Fixture( VersionAssetArtifactRepository artifacts, GameDesignPublicationOperationRepository operations, GameDesignPublicationOperationService service, - GameDesignPublicationOperation operation) {} + GameDesignPublicationOperation operation, + ExportedAssetManifest candidate) {} } From 6a588f446f2290de19462480585adba04448597d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 08:29:54 +1300 Subject: [PATCH 11/13] test: reconcile Account source fixtures with publication participation schema --- ...IssuanceIntentPostgresIntegrationTest.java | 11 +++++++++ ...StateOperationPostgresIntegrationTest.java | 24 +++++++++---------- ...horityProducerPostgresIntegrationTest.java | 13 ++++++++-- ...rojectionPostgresRedisIntegrationTest.java | 2 +- ...iCurrentSourcePostgresIntegrationTest.java | 2 +- ...orizationFencePostgresIntegrationTest.java | 16 +++++++------ 6 files changed, 45 insertions(+), 23 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceIntentPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceIntentPostgresIntegrationTest.java index 7d9c0c41e8..0d974ab44a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceIntentPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceIntentPostgresIntegrationTest.java @@ -483,6 +483,17 @@ private static Fixture fixture(boolean enroll) { .target(MigrationVersion.fromVersion("74")) .load() .migrate(); + // Preserve the original V74 seed boundary while giving current source collaborators V79's + // publication participation schema. + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion("79")) + .load() + .migrate(); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); var accounts = new AccountRepository(dsl); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java index c4e5630d85..c58288d774 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java @@ -55,7 +55,7 @@ class AccountSecurityStateOperationPostgresIntegrationTest { @Test void pendingClaimAndExactRetryRetainOneOriginalCaptureWithoutSourceMutation() { - Fixture fixture = fixture("67"); + Fixture fixture = fixture("79"); Seed seed = seed(fixture); Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); var first = tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); @@ -92,7 +92,7 @@ void pendingClaimAndExactRetryRetainOneOriginalCaptureWithoutSourceMutation() { @Test void originalCallerAndFamilyBindingsCannotBeChangedOnRetry() { - Fixture fixture = fixture("67"); + Fixture fixture = fixture("79"); Seed seed = seed(fixture); Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); @@ -128,7 +128,7 @@ void originalCallerAndFamilyBindingsCannotBeChangedOnRetry() { @Test void concurrentExactClaimsSerializeToOneOriginalRequest() throws Exception { - Fixture fixture = fixture("67"); + Fixture fixture = fixture("79"); Seed seed = seed(fixture); Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); CountDownLatch ready = new CountDownLatch(2); @@ -168,7 +168,7 @@ void concurrentExactClaimsSerializeToOneOriginalRequest() throws Exception { @Test void exactExistingOutboxReceiptCompletesOnceAndHistoricalImagesSurviveLaterAdvance() { - Fixture fixture = fixture("67"); + Fixture fixture = fixture("79"); Seed seed = seed(fixture); Pending first = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); tx(fixture, () -> fixture.operations().claim(first.request(), first.capture())); @@ -232,7 +232,7 @@ void exactExistingOutboxReceiptCompletesOnceAndHistoricalImagesSurviveLaterAdvan @Test void lawfulPrivateFenceAdvanceKeepsLatestSourceEventAndOriginalReceiptUnchanged() { - Fixture fixture = fixture("67"); + Fixture fixture = fixture("79"); Seed seed = seed(fixture); Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); @@ -298,7 +298,7 @@ void lawfulPrivateFenceAdvanceKeepsLatestSourceEventAndOriginalReceiptUnchanged( @Test void lateReceiptFailureRollsBackEntireFixtureProducerButRetainsOriginalWaitingIntent() { - Fixture fixture = fixture("67"); + Fixture fixture = fixture("79"); Seed seed = seed(fixture); Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); @@ -347,7 +347,7 @@ void lateReceiptFailureRollsBackEntireFixtureProducerButRetainsOriginalWaitingIn @Test void requestCaptureResultsDeletesAndTruncationRemainGuarded() { - Fixture fixture = fixture("67"); + Fixture fixture = fixture("79"); Seed seed = seed(fixture); Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); @@ -373,7 +373,7 @@ void requestCaptureResultsDeletesAndTruncationRemainGuarded() { @Test void substitutedEventStateCannotBecomeTheOriginalReceipt() { - Fixture fixture = fixture("67"); + Fixture fixture = fixture("79"); Seed seed = seed(fixture); Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); @@ -430,7 +430,7 @@ void corruptPositiveCheckpointMetadataAndPayloadDenyBeforeNewIntentOrSourceMutat "request_id = 'substituted'", "event_digest = 'sha256:' || repeat('b',64)", "payload = convert_to('{}','UTF8')")) { - Fixture fixture = fixture("67"); + Fixture fixture = fixture("79"); Seed seed = seed(fixture); Pending first = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); tx(fixture, () -> fixture.operations().claim(first.request(), first.capture())); @@ -475,7 +475,7 @@ void corruptPositiveCheckpointMetadataAndPayloadDenyBeforeNewIntentOrSourceMutat void retainedReceiptCannotLeadRegressedCurrentAuthorityOrCheckpoint() { for (String table : List.of("account_authority_generations", "account_authority_outbox_streams")) { - Fixture fixture = fixture("67"); + Fixture fixture = fixture("79"); Seed seed = seed(fixture); Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); @@ -499,7 +499,7 @@ void retainedReceiptCannotLeadRegressedCurrentAuthorityOrCheckpoint() { @Test void actualReaderDeniesUncommittedOperationAndChangedCurrentPoststate() { - Fixture missing = fixture("67"); + Fixture missing = fixture("79"); Seed seed = seed(missing); Pending pending = pending(missing, seed, state(false), state(true), 0L, new byte[0]); tx(missing, () -> missing.operations().claim(pending.request(), pending.capture())); @@ -532,7 +532,7 @@ void actualReaderDeniesUncommittedOperationAndChangedCurrentPoststate() { })) .isInstanceOf(IllegalStateException.class); - Fixture changed = fixture("67"); + Fixture changed = fixture("79"); Seed other = seed(changed); Pending original = pending(changed, other, state(false), state(true), 0L, new byte[0]); tx(changed, () -> changed.operations().claim(original.request(), original.capture())); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java index 6ba786bd7b..b6bf7a0433 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java @@ -502,8 +502,8 @@ void v59PreservesV58HistoryAndExactKeysBeforeV67ProducerInteractionsWithFullMult assertThat(SourceChange.fromStored(retainedBinding).canonicalBytes()) .containsExactly(oldChange.canonicalBytes()); - // V59's retained-data proof is complete above. Current source ordering also consumes the - // distinct CREATE_TENANT family, so advance to V67 before current producer interactions. + // V59's retained-data proof is complete above. Current source ordering consumes the distinct + // CREATE_TENANT family, and current fence participation also requires V79. Flyway.configure() .dataSource(dataSource) .schemas(schema) @@ -513,6 +513,15 @@ void v59PreservesV58HistoryAndExactKeysBeforeV67ProducerInteractionsWithFullMult .target("67") .load() .migrate(); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target("79") + .load() + .migrate(); assertThat(fixture.producer().advance(ISSUER_ID, oldRequest, 1, 1).requestId()) .isEqualTo(oldRequest.toString()); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerGenerationProjectionPostgresRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerGenerationProjectionPostgresRedisIntegrationTest.java index ae4d4a4505..f2fb6dbc03 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerGenerationProjectionPostgresRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerGenerationProjectionPostgresRedisIntegrationTest.java @@ -314,7 +314,7 @@ private static Fixture fixture(boolean enroll) { .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) .locations("classpath:db/migration") - .target("67") + .target("79") .load() .migrate(); DSLContext dsl = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourcePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourcePostgresIntegrationTest.java index 1d7a601ff1..b2be1d4df4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourcePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourcePostgresIntegrationTest.java @@ -453,7 +453,7 @@ private static Fixture fixture(boolean enrollAuthority) { .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) .locations("classpath:db/migration") - .target(MigrationVersion.fromVersion("67")) + .target(MigrationVersion.fromVersion("79")) .load() .migrate(); DSLContext dsl = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/tenantcreation/TenantCreationAuthorizationFencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/tenantcreation/TenantCreationAuthorizationFencePostgresIntegrationTest.java index 35ac21b822..1fd76a48ec 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/tenantcreation/TenantCreationAuthorizationFencePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/tenantcreation/TenantCreationAuthorizationFencePostgresIntegrationTest.java @@ -57,7 +57,7 @@ class TenantCreationAuthorizationFencePostgresIntegrationTest { @Test void revokeFirstRetainsBothFamilyFencesUntilExactAborts() { - Context c = context("67"); + Context c = context("79"); var b = binding(); var draft = draft(b.sources().getFirst()); var change = new SourceChange(UUID.randomUUID(), b.sources(), new byte[] {7}); @@ -94,7 +94,7 @@ void revokeFirstRetainsBothFamilyFencesUntilExactAborts() { @Test void commitFirstRequiresBothExactOutcomesAndMixedVectorDoesNotQualifySuccess() { - Context c = context("67"); + Context c = context("79"); var b = binding(); var change = new SourceChange(UUID.randomUUID(), b.sources(), new byte[] {8}); tx( @@ -143,7 +143,7 @@ void commitFirstRequiresBothExactOutcomesAndMixedVectorDoesNotQualifySuccess() { @Test void contradictoryRevokeOutcomeNeverReleasesSourceOrdering() { - Context c = context("67"); + Context c = context("79"); var b = binding(); var change = new SourceChange(UUID.randomUUID(), b.sources(), new byte[] {9}); tx(c, () -> c.creation.reserve(b)); @@ -157,7 +157,7 @@ void contradictoryRevokeOutcomeNeverReleasesSourceOrdering() { @Test void exactRetryAndDatabaseGuardsPreserveBindingAndFinalizedResults() { - Context c = context("67"); + Context c = context("79"); var b = binding(); tx(c, () -> c.creation.reserve(b)); assertThatThrownBy(() -> owner(c, b, Owner.ACCOUNT, Outcome.COMMITTED)) @@ -213,7 +213,7 @@ void exactRetryAndDatabaseGuardsPreserveBindingAndFinalizedResults() { @Test void lateFailureRollsBackSourceTransitionWithOwnersRemainingImmutable() { - Context c = context("67"); + Context c = context("79"); var b = binding(); var change = new SourceChange(UUID.randomUUID(), b.sources(), new byte[] {10}); tx( @@ -247,7 +247,7 @@ void lateFailureRollsBackSourceTransitionWithOwnersRemainingImmutable() { @Test void sharedSourceLocksSerializeBothCompetingInterleavings() throws Exception { for (boolean commitFirst : List.of(true, false)) { - Context c = context("67"); + Context c = context("79"); var b = binding(); var change = new SourceChange(UUID.randomUUID(), b.sources(), new byte[] {11}); tx(c, () -> c.creation.reserve(b)); @@ -296,7 +296,7 @@ void migrationRetainsV66AndDraftImagesAndOriginalDraftBindingBytes() { var b = binding(); var draft = draft(b.sources().getFirst()); // These existing Draft-only methods do not call the common source-change/settlement engine. - // Keep V66's populated image intact before migrating; current source interactions require V67. + // Keep V66's populated image intact before migrating; current source interactions require V79. tx( c, () -> { @@ -359,6 +359,8 @@ void migrationRetainsV66AndDraftImagesAndOriginalDraftBindingBytes() { Map> images = retainedImages(c); migration(c.source, c.schema, "67").migrate(); assertThat(retainedImages(c)).isEqualTo(images); + migration(c.source, c.schema, "79").migrate(); + assertThat(retainedImages(c)).isEqualTo(images); assertThat(tx(c, () -> c.draft.read(draft).binding())).containsExactly(draft.canonicalBytes()); assertThat(tx(c, () -> c.draft.readSettlement(draft))) .isEqualTo(Settlement.FAILED_NONPUBLICATION); From df35da130e46db892cf745d45bb9e69c0b83ea6d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 10:47:43 +1300 Subject: [PATCH 12/13] test: stage historical diagnostics before publication terminal immutability --- ...aunchDescriptorServiceIntegrationTest.java | 86 ++++++++++++++----- 1 file changed, 66 insertions(+), 20 deletions(-) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java index 5a1088a3a8..394e94ea27 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -558,29 +558,12 @@ void v39MigrationPreservesRetainedPublicationEvidenceAndStoresLongDiagnostics() Map> retainedRows = publicationEvidenceRows( isolatedDsl, versionId, bundleId, descriptorId, attemptId, artifactId); - migrate(dataSource, schema, null); - Map> migratedRows = + migrate(dataSource, schema, MigrationVersion.fromVersion("39")); + Map> v39Rows = publicationEvidenceRows( isolatedDsl, versionId, bundleId, descriptorId, attemptId, artifactId); - assertThat(priorPublicationEvidenceColumns(migratedRows)) + assertThat(priorPublicationEvidenceColumns(v39Rows)) .isEqualTo(priorPublicationEvidenceColumns(retainedRows)); - assertThat(requiredSnapshot(migratedRows, "publish_attempt").get("revision")).isEqualTo(1L); - assertThat( - requiredSnapshot(migratedRows, "published_release_bundle") - .get("world_published_start_location_evidence_json")) - .isNull(); - var publicationOperationCount = - isolatedDsl.fetchOne( - "SELECT count(*) FROM game_design_publication_operation WHERE publish_workflow_id = ?", - attemptWorkflowId); - if (publicationOperationCount == null) { - throw new IllegalStateException("Publication operation count query returned no row"); - } - Long publicationOperationCountValue = publicationOperationCount.get(0, Long.class); - if (publicationOperationCountValue == null) { - throw new IllegalStateException("Publication operation count query returned no count"); - } - assertThat(publicationOperationCountValue).isZero(); assertThat( requiredSnapshot(retainedRows, "published_release_bundle") .get("generation_config_revision")) @@ -601,6 +584,15 @@ void v39MigrationPreservesRetainedPublicationEvidenceAndStoresLongDiagnostics() "UPDATE version_asset_artifact SET last_error_message = ? WHERE id = ?", longArtifactError, artifactId); + Map> v39LongDiagnosticsRows = + publicationEvidenceRows( + isolatedDsl, versionId, bundleId, descriptorId, attemptId, artifactId); + assertThat(requiredSnapshot(v39LongDiagnosticsRows, "publish_attempt").get("failure_message")) + .isEqualTo(longFailure); + assertThat( + requiredSnapshot(v39LongDiagnosticsRows, "version_asset_artifact") + .get("last_error_message")) + .isEqualTo(longArtifactError); assertThat( requiredRow( isolatedDsl, @@ -633,6 +625,60 @@ void v39MigrationPreservesRetainedPublicationEvidenceAndStoresLongDiagnostics() "artifact state readback")) .containsEntry("artifact_state", "FAILED") .containsEntry("state_epoch", 11L); + + migrate(dataSource, schema, null); + Map> migratedRows = + publicationEvidenceRows( + isolatedDsl, versionId, bundleId, descriptorId, attemptId, artifactId); + assertThat(priorPublicationEvidenceColumns(migratedRows)) + .isEqualTo(priorPublicationEvidenceColumns(v39LongDiagnosticsRows)); + assertThat(requiredSnapshot(migratedRows, "publish_attempt").get("revision")).isEqualTo(1L); + assertThat( + requiredSnapshot(migratedRows, "published_release_bundle") + .get("world_published_start_location_evidence_json")) + .isNull(); + var publicationOperationCount = + isolatedDsl.fetchOne( + "SELECT count(*) FROM game_design_publication_operation WHERE publish_workflow_id = ?", + attemptWorkflowId); + if (publicationOperationCount == null) { + throw new IllegalStateException("Publication operation count query returned no row"); + } + Long publicationOperationCountValue = publicationOperationCount.get(0, Long.class); + if (publicationOperationCountValue == null) { + throw new IllegalStateException("Publication operation count query returned no count"); + } + assertThat(publicationOperationCountValue).isZero(); + assertThat(requiredSnapshot(migratedRows, "publish_attempt").get("failure_message")) + .isEqualTo(longFailure); + assertThat(requiredSnapshot(migratedRows, "version_asset_artifact").get("last_error_message")) + .isEqualTo(longArtifactError); + + assertThatThrownBy( + () -> + isolatedDsl.execute( + "UPDATE publish_attempt SET failure_message = ? WHERE id = ?", + "forbidden-terminal-rewrite-" + suffix, + attemptId)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining("publish attempt is stale or terminal"); + Map> afterRejectedTerminalRewrite = + publicationEvidenceRows( + isolatedDsl, versionId, bundleId, descriptorId, attemptId, artifactId); + assertThat(afterRejectedTerminalRewrite).isEqualTo(migratedRows); + var publicationOperationCountAfterRejectedRewrite = + isolatedDsl.fetchOne( + "SELECT count(*) FROM game_design_publication_operation WHERE publish_workflow_id = ?", + attemptWorkflowId); + if (publicationOperationCountAfterRejectedRewrite == null) { + throw new IllegalStateException("Publication operation count query returned no row"); + } + Long publicationOperationCountAfterRejectedRewriteValue = + publicationOperationCountAfterRejectedRewrite.get(0, Long.class); + if (publicationOperationCountAfterRejectedRewriteValue == null) { + throw new IllegalStateException("Publication operation count query returned no count"); + } + assertThat(publicationOperationCountAfterRejectedRewriteValue).isZero(); } @Test From 2961b48875070d5d445384588a923ca2bb6cc99b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 11:20:05 +1300 Subject: [PATCH 13/13] test: preserve V45 history assertions across publication revision migration --- ...ishSelectionRepositoryIntegrationTest.java | 31 ++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepositoryIntegrationTest.java index 7e2c860a31..d20140c872 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepositoryIntegrationTest.java @@ -116,9 +116,26 @@ void v45PreservesRetainedAttemptDigestsAndStoresExactSelectionDigest() { assertThat(retainedCoordinatorRows(retained)) .usingRecursiveComparison() .isEqualTo(coordinatorBeforeLatest); + assertThat( + retained + .dsl() + .fetch( + "SELECT id, tenant_id, publish_workflow_id, publish_type, status, version_id, " + + "version_number, script_patch_version, failure_code, failure_message, " + + "created_at, completed_at, base_version_id, request_digest " + + "FROM publish_attempt ORDER BY id") + .intoMaps()) + .isEqualTo(before); + assertThat( + retained + .dsl() + .fetchCount(DSL.table(DSL.name("publish_attempt")), DSL.field("revision").ne(1L))) + .isZero(); assertThat( retained.dsl().fetchCount(DSL.table(DSL.name("game_design_draft_terminal_operation")))) .isZero(); + assertThat(retained.dsl().fetchCount(DSL.table(DSL.name("game_design_publication_operation")))) + .isZero(); assertThat(reserve(retained, intent)).isEqualTo(selected); String workflowId = "selected-attempt-" + UUID.randomUUID(); retained @@ -138,14 +155,26 @@ void v45PreservesRetainedAttemptDigestsAndStoresExactSelectionDigest() { "SELECT request_digest FROM publish_attempt WHERE publish_workflow_id = ?", workflowId)) .isEqualTo(selected.selection().digest()); + assertThat( + retained + .dsl() + .fetchValue( + "SELECT revision FROM publish_attempt WHERE publish_workflow_id = ?", + workflowId)) + .isEqualTo(1L); assertThat( retained .dsl() .fetch( - "SELECT * FROM publish_attempt WHERE publish_workflow_id <> ? ORDER BY id", + "SELECT id, tenant_id, publish_workflow_id, publish_type, status, version_id, " + + "version_number, script_patch_version, failure_code, failure_message, " + + "created_at, completed_at, base_version_id, request_digest " + + "FROM publish_attempt WHERE publish_workflow_id <> ? ORDER BY id", workflowId) .intoMaps()) .isEqualTo(before); + assertThat(retained.dsl().fetchCount(DSL.table(DSL.name("game_design_publication_operation")))) + .isZero(); } @Test