From c51b035c041981a6a3a90c69fd99e3aecee20bd9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 05:53:54 +1300 Subject: [PATCH 01/12] Fence canonical World activation to independent owner evidence and immutable outcome --- .github/workflows/ci.yml | 4 + .../world-management-service/api-contracts.md | 8 +- .../world-runtime-and-movement.md | 4 + .../WorldLifecycleCommandServiceImpl.java | 57 +-- .../WorldAuthoredSourceIntakeRepository.java | 30 ++ ...orldAuthoredVersionIdentityRepository.java | 32 ++ .../WorldCanonicalInstanceActivation.java | 252 ++++++++++ ...CanonicalInstanceActivationRepository.java | 294 ++++++++++++ ...rldCanonicalInstanceActivationService.java | 84 ++++ ...anonicalInstanceAssociationRepository.java | 68 ++- ...onicalInstanceLifecycleReadRepository.java | 102 ++-- .../WorldCompleteLaunchBindingRepository.java | 30 ++ ...anonical_instance_activation_operation.sql | 453 ++++++++++++++++++ ...aphApplicationPostgresIntegrationTest.java | 435 +++++++++++++++++ .../WorldLifecycleCommandServiceImplTest.java | 37 +- ...nicalInstanceActivationRepositoryTest.java | 80 ++++ ...anonicalInstanceActivationServiceTest.java | 102 ++++ .../WorldCanonicalInstanceActivationTest.java | 69 +++ 18 files changed, 2065 insertions(+), 76 deletions(-) create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivation.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationService.java create mode 100644 services/world-management-service/src/main/resources/db/migration/V43__canonical_instance_activation_operation.sql create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepositoryTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4f57e4e0d3..0108f8dd02 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2249,6 +2249,10 @@ jobs: --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#canonicalActivationCommitsOneOwnerCasAndReplaysItsImmutableResultAfterLaterLifecycleMove()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#canonicalActivationStoresStaleFailedOutcomeAndFreshLifecycleReadRemainsCurrent()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#canonicalActivationRejectsSelfConsistentForgedOwnerBindingsBeforeActiveCas()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#lostHeldAuthorityAfterOperationInsertRollsBackActivationAndLedger()' \ --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 67db5cd9b1..aad88182fb 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -312,7 +312,7 @@ The retained graph/2 payload preserves World's original UTF-8 owner serializatio 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 +## Canonical Instance Activation and Lifecycle Readback 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. @@ -320,6 +320,12 @@ Canonical preparation verifies Game Design's exact [authored-source-bound launch 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. +Canonical activation is a distinct exact World owner operation. Its stable non-nil activation request UUID and normalized request digest bind the complete original `PREPARING` evidence, including the canonical association, source/release, capture, graph/input, selector/runtime-room identity, lifecycle epoch and row version. The lifecycle-read correlation UUID is excluded from that operation identity; the original complete evidence bytes remain retained in the immutable result. Current source/release and applicable Account operation authority must be verified outside the World transaction, with a distinct operation-specific local fence continuously held through the owner commit. That Account authority is the separate tenant-scoped lifecycle and serving predicate, including explicit capacity classification, owned by [Versioning and Runtime](../../system-architecture-versioning-runtime.md#tenant-owned-runtime-lifecycle-authority); it is not renewed creator permission merely to derive the unchanged immutable published result. Original authorized application and complete publication/release evidence remain necessary, but earlier Draft or publication authorization cannot authorize activation. Covered content, rights or reachability changes require their own current authorization. An unavailable or unproved lifecycle verifier denies new activation before mutation. + +World atomically commits the immutable operation result with the exact `PREPARING -> ACTIVE` compare-and-set, advancing its lifecycle epoch and row version by one. A changed or stale precondition records an immutable non-activating failure only from the actual associated current lifecycle state; missing owner evidence is not a fabricated failure result. A committed-result ledger without its actual lifecycle transition is invalid. Exact or lost-response recovery returns the original operation result byte-for-byte even after later lifecycle movement; changed normalized input conflicts. That historical result is not current `ACTIVE` eligibility: Game Session still requires fresh authenticated lifecycle and admission evidence. Numeric legacy lifecycle commands cannot activate a canonically associated row outside this operation. The unregistered component and its default-denied verifier do not enable a runtime writer; implementation and executed proof limits belong to the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). + +## Initial Admission Hold Contract + [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/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index 66e519a7e4..9f3b726d6c 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +The local World delivery correction behind #3029 adds an unregistered, default-denied V43 canonical activation operation and an immutable exact-retry result. The owner transaction independently reconstructs the same complete association/materialization evidence, locks the actual lifecycle row and commits its `PREPARING -> ACTIVE` CAS with the result; raw SQL cannot commit a success ledger without that CAS or activate the canonical row through the legacy numeric writer. New definitions cover stale outcomes, exact concurrent retry, lost held-authority rollback, self-consistent forged evidence rejected against independent owner rows, and historical recovery after later lifecycle movement. Validation and PostgreSQL execution for this unpublished batch remain pending; these definitions and an explicitly isolated verifier do not supply authenticated live activation, placement, region preparation or admission. The [World API contract](../../architecture/microservices/world-management-service/api-contracts.md#canonical-instance-activation-and-lifecycle-readback) owns the operation and historical-versus-current evidence distinction. + +Fresh Account lifecycle/serving authority remains a concrete missing producer, distinct from original Draft and publication authorization. Account's existing fresh-control bootstrap capture supplies committed exact-tenant `tenantAdmin` source evidence, but does not authenticate a lifecycle caller or produce fresh serving entitlement, billing/quota classification or capacity commitment. The gameplay-only numeric entitlement DTO and source-lock primitives cannot supply those missing facts. No `CommitTenantCapacityAdmission`, lifecycle participant hold, capacity usage/reservation ledger or complete canonical fresh-tenant billing source exists in this candidate; production activation therefore remains denied under [Versioning and Runtime](../../architecture/system-architecture-versioning-runtime.md#serving-entitlement-and-shutdown-gates). A clearly labeled isolated upstream authority composition can exercise real owner transitions for bounded fixture proof, but cannot count as any of those production producers or authorize player admission. + 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. diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java index 7ca8879625..8b18e7c0aa 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java @@ -35,6 +35,7 @@ import net.firedevops.firemud.worldmanagement.repository.ZoneInstanceRepository; import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; import net.firedevops.firemud.worldmanagement.service.WorldLifecycleCommandService; +import org.jooq.DSLContext; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -72,6 +73,7 @@ private record SelectedRoomTopology(List zones, List rooms, List readInOwnerReadOnlyRepeatableRead( return readValidated(namespace, intakeRequestId); } + /** + * Reconstructs the same immutable intake inside the writable canonical activation transaction. + */ + Optional readInOwnerActivationTransaction( + String namespace, UUID intakeRequestId) { + requireWritableActivationTransaction(); + return readValidated(namespace, intakeRequestId); + } + private Optional readValidated( String namespace, UUID intakeRequestId) { validateReadKey(namespace, intakeRequestId); @@ -518,6 +527,27 @@ private void requireReadOnlyRepeatableReadOwnerTransaction() { } } + private void requireWritableActivationTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World authored-source activation read requires a writable READ COMMITTED owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + if (!"read committed".equals(state.get("isolation", String.class)) + || !"off".equals(state.get("read_only", String.class))) { + throw new IllegalStateException( + "World authored-source activation read requires a writable READ COMMITTED 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 22a745a934..a842eb9005 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 @@ -93,6 +93,17 @@ Optional readByCanonicalVersionInOwnerReadO namespace, canonicalTenantId, worldSlug, canonicalVersionId); } + /** + * Reconstructs the same immutable Version receipt inside canonical activation's owner + * transaction. + */ + Optional readByCanonicalVersionInOwnerActivationTransaction( + String namespace, UUID canonicalTenantId, String worldSlug, UUID canonicalVersionId) { + requireWritableActivationTransaction(); + return readByCanonicalVersionValidated( + namespace, canonicalTenantId, worldSlug, canonicalVersionId); + } + private Optional readByCanonicalVersionValidated( String namespace, UUID canonicalTenantId, String worldSlug, UUID canonicalVersionId) { validateIdentityKey(namespace, canonicalTenantId, worldSlug); @@ -386,6 +397,27 @@ private void requireReadOnlyRepeatableReadOwnerTransaction() { } } + private void requireWritableActivationTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World authored-Version activation read requires a writable READ COMMITTED owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + if (!"read committed".equals(state.get("isolation", String.class)) + || !"off".equals(state.get("read_only", String.class))) { + throw new IllegalStateException( + "World authored-Version activation read requires a writable READ COMMITTED owner transaction"); + } + } + private static void requireWritableReadCommittedOwnerTransaction() { if (!TransactionSynchronizationManager.isActualTransactionActive()) { throw new IllegalStateException( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivation.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivation.java new file mode 100644 index 0000000000..c061d6ad2e --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivation.java @@ -0,0 +1,252 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +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.Base64; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable operation identity and result for the default-denied canonical World activation cut. + */ +public final class WorldCanonicalInstanceActivation { + private static final String REQUEST_SCHEMA = "world-canonical-instance-activation-request/v1"; + private static final String RESULT_SCHEMA = "world-canonical-instance-activation-result/v1"; + private static final Set RESULT_FIELDS = + Set.of( + "schema", + "activationRequestId", + "requestDigest", + "requestBytesBase64", + "preparingEvidenceBytesBase64", + "outcome", + "terminalCode", + "lifecycleEvidenceBytesBase64"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + private WorldCanonicalInstanceActivation() {} + + /** + * Stable operation identity. The nested World lifecycle read UUID is correlation metadata and is + * excluded from {@link #canonicalRequestBytes()}, while the original complete proof remains in + * {@link #preparingEvidenceBytes()} and the immutable operation result. + */ + public record Request( + UUID activationRequestId, WorldCanonicalInstanceLifecycleEvidence preparing) { + public Request { + requireNonNil(activationRequestId, "activationRequestId"); + Objects.requireNonNull(preparing, "preparing"); + if (!"PREPARING".equals(preparing.lifecycleStatus())) { + throw new IllegalArgumentException( + "Canonical activation requires exact PREPARING evidence"); + } + } + + public UUID canonicalGameInstanceId() { + return preparing.request().canonicalGameInstanceId(); + } + + public long expectedLifecycleEpoch() { + return preparing.lifecycleEpoch(); + } + + public long expectedRowVersion() { + return preparing.rowVersion(); + } + + /** Canonical operation bytes omit only the transport lifecycle-read UUID. */ + public byte[] canonicalRequestBytes() { + try { + JsonNode evidence = JSON.readTree(preparing.canonicalBytes()); + JsonNode lifecycleRequest = evidence.path("request"); + if (!lifecycleRequest.isObject()) { + throw new IllegalArgumentException("Canonical PREPARING proof has no closed request"); + } + ((tools.jackson.databind.node.ObjectNode) lifecycleRequest).remove("readRequestId"); + Map request = new LinkedHashMap<>(); + request.put("schema", REQUEST_SCHEMA); + request.put("activationRequestId", activationRequestId.toString()); + request.put("preparingEvidence", evidence); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(request)); + } catch (IOException invalid) { + throw new IllegalArgumentException("Canonical activation request is invalid", invalid); + } + } + + public byte[] preparingEvidenceBytes() { + return preparing.canonicalBytes(); + } + + public String requestDigest() { + return digest(canonicalRequestBytes()); + } + } + + public enum Outcome { + COMMITTED, + ABORTED + } + + /** Immutable success or terminal stale-precondition outcome; ABORTED never grants admission. */ + public record Result( + Request request, + Outcome outcome, + String terminalCode, + WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence) { + public Result { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(outcome, "outcome"); + Objects.requireNonNull(lifecycleEvidence, "lifecycleEvidence"); + if (!request.preparing().request().equals(lifecycleEvidence.request())) { + throw new IllegalArgumentException( + "Canonical activation result differs from its original lifecycle-read request"); + } + if (outcome == Outcome.COMMITTED) { + if (terminalCode != null + || !"ACTIVE".equals(lifecycleEvidence.lifecycleStatus()) + || lifecycleEvidence.lifecycleEpoch() + != Math.addExact(request.expectedLifecycleEpoch(), 1L) + || lifecycleEvidence.rowVersion() != Math.addExact(request.expectedRowVersion(), 1L)) { + throw new IllegalArgumentException( + "Committed activation result is not the exact next ACTIVE state"); + } + } else if (terminalCode == null || terminalCode.isBlank()) { + throw new IllegalArgumentException("Aborted activation result requires a terminal code"); + } + } + + public byte[] canonicalBytes() { + Map result = new LinkedHashMap<>(); + result.put("schema", RESULT_SCHEMA); + result.put("activationRequestId", request.activationRequestId().toString()); + result.put("requestDigest", request.requestDigest()); + result.put( + "requestBytesBase64", + Base64.getEncoder().encodeToString(request.canonicalRequestBytes())); + result.put( + "preparingEvidenceBytesBase64", + Base64.getEncoder().encodeToString(request.preparingEvidenceBytes())); + result.put("outcome", outcome.name()); + result.put("terminalCode", terminalCode); + result.put( + "lifecycleEvidenceBytesBase64", + Base64.getEncoder().encodeToString(lifecycleEvidence.canonicalBytes())); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(result)); + } catch (IOException impossible) { + throw new IllegalStateException( + "Canonical activation result cannot be encoded", impossible); + } + } + + public static Result 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 root = JSON.readTree(json); + requireFields(root, RESULT_FIELDS, "Canonical World activation result"); + if (!RESULT_SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException("Unsupported canonical activation result schema"); + } + UUID activationId = UUID.fromString(text(root, "activationRequestId")); + WorldCanonicalInstanceLifecycleEvidence preparing = + WorldCanonicalInstanceLifecycleEvidence.fromStored( + decodeBase64(root, "preparingEvidenceBytesBase64")); + Request request = new Request(activationId, preparing); + if (!request.requestDigest().equals(text(root, "requestDigest")) + || !Arrays.equals( + request.canonicalRequestBytes(), decodeBase64(root, "requestBytesBase64"))) { + throw new IllegalArgumentException("Stored activation request digest or bytes differ"); + } + Outcome outcome = Outcome.valueOf(text(root, "outcome")); + JsonNode terminal = root.get("terminalCode"); + if (terminal != null && !terminal.isNull() && !terminal.isTextual()) { + throw new IllegalArgumentException("Stored activation terminalCode must be text or null"); + } + String terminalCode = terminal == null || terminal.isNull() ? null : terminal.textValue(); + Result result = + new Result( + request, + outcome, + terminalCode, + WorldCanonicalInstanceLifecycleEvidence.fromStored( + decodeBase64(root, "lifecycleEvidenceBytesBase64"))); + if (!Arrays.equals(stored, result.canonicalBytes())) { + throw new IllegalArgumentException("Stored canonical activation result is not canonical"); + } + return result; + } catch (IOException invalid) { + throw new IllegalArgumentException( + "Stored canonical activation result is invalid", invalid); + } + } + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private static byte[] decodeBase64(JsonNode node, String field) { + try { + return Base64.getDecoder().decode(text(node, field)); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Stored activation " + field + " is invalid", invalid); + } + } + + private static String text(JsonNode node, String field) { + JsonNode value = node.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException("Stored activation " + field + " must be text"); + } + return value.textValue(); + } + + private static void requireFields(JsonNode node, Set fields, String label) { + if (node == null || !node.isObject() || node.size() != fields.size()) { + throw new IllegalArgumentException(label + " has an invalid closed object shape"); + } + for (String name : node.propertyNames()) { + if (!fields.contains(name)) { + throw new IllegalArgumentException(label + " has an unknown field"); + } + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(label + " must be non-nil"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java new file mode 100644 index 0000000000..8f569ac156 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java @@ -0,0 +1,294 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +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 net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Owner-local immutable activation ledger and exact World lifecycle CAS. */ +public final class WorldCanonicalInstanceActivationRepository { + private final DSLContext dsl; + private final TransactionTemplate readTransaction; + private final TransactionTemplate writeTransaction; + private final WorldCanonicalInstanceLifecycleReadRepository lifecycleRepository; + + public WorldCanonicalInstanceActivationRepository( + DSLContext dsl, + PlatformTransactionManager transactionManager, + WorldCanonicalInstanceLifecycleReadRepository lifecycleRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.lifecycleRepository = Objects.requireNonNull(lifecycleRepository, "lifecycleRepository"); + PlatformTransactionManager manager = + Objects.requireNonNull(transactionManager, "transactionManager"); + readTransaction = new TransactionTemplate(manager); + readTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + readTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + readTransaction.setReadOnly(true); + writeTransaction = new TransactionTemplate(manager); + writeTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + writeTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + /** + * Independently reads an immutable result; exact retries intentionally do not require current + * authority. + */ + public Optional readResult( + WorldCanonicalInstanceActivation.Request request) { + Objects.requireNonNull(request, "request"); + requireNoActiveTransaction("World canonical activation result read"); + return Optional.ofNullable( + readTransaction.execute( + status -> { + requireReadOnlyRepeatableReadTransaction(); + return readResultInCurrentTransaction(request).orElse(null); + })); + } + + /** + * Commits one exact PREPARING-to-ACTIVE CAS or stores a terminal stale-precondition result. The + * caller has already verified remote/current authorities outside this transaction. + */ + public WorldCanonicalInstanceActivation.Result activate( + WorldCanonicalInstanceActivation.Request request, + WorldCanonicalInstanceActivationService.HeldActivationAuthority held) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(held, "held"); + requireNoActiveTransaction("World canonical activation"); + return writeTransaction.execute( + status -> { + requireWritableTransaction(); + held.requireHeld(); + WorldCanonicalInstanceLifecycleEvidence current = + lifecycleRepository + .readForActivationInOwnerTransaction(request.preparing().request()) + .orElseThrow( + () -> + new ActivationConflictException( + "Canonical World activation no longer has its exact materialized owner association")); + Optional existing = + readResultInCurrentTransaction(request); + if (existing.isPresent()) return existing.orElseThrow(); + + boolean exactPrecondition = + "PREPARING".equals(current.lifecycleStatus()) + && current.lifecycleEpoch() == request.expectedLifecycleEpoch() + && current.rowVersion() == request.expectedRowVersion() + && Arrays.equals( + request.canonicalRequestBytes(), + new WorldCanonicalInstanceActivation.Request( + request.activationRequestId(), current) + .canonicalRequestBytes()); + if (!exactPrecondition) { + WorldCanonicalInstanceActivation.Result aborted = + new WorldCanonicalInstanceActivation.Result( + request, + WorldCanonicalInstanceActivation.Outcome.ABORTED, + "PRECONDITION_FAILED", + current); + insertResult(request, aborted); + held.requireHeld(); + return aborted; + } + + WorldCanonicalInstanceLifecycleEvidence predicted = nextActiveEvidence(request, current); + WorldCanonicalInstanceActivation.Result committed = + new WorldCanonicalInstanceActivation.Result( + request, WorldCanonicalInstanceActivation.Outcome.COMMITTED, null, predicted); + insertResult(request, committed); + held.requireHeld(); + int updated = + dsl.execute( + "UPDATE world_instance SET status='ACTIVE', lifecycle_epoch=lifecycle_epoch+1, " + + "row_version=row_version+1, updated_at=CURRENT_TIMESTAMP " + + "WHERE id=(SELECT world_instance_id FROM world_canonical_instance_association " + + "WHERE canonical_game_instance_id=?) AND canonical_game_instance_id=? " + + "AND status='PREPARING' AND lifecycle_epoch=? AND row_version=?", + request.canonicalGameInstanceId(), + request.canonicalGameInstanceId(), + request.expectedLifecycleEpoch(), + request.expectedRowVersion()); + if (updated != 1) { + throw new ActivationConflictException( + "Canonical World lifecycle changed before its exact activation compare-and-set"); + } + WorldCanonicalInstanceLifecycleEvidence actual = + lifecycleRepository + .readForActivationInOwnerTransaction(request.preparing().request()) + .orElseThrow( + () -> + new InvalidActivationEvidenceException( + "Canonical World activation lost its owner readback")); + if (!Arrays.equals(predicted.canonicalBytes(), actual.canonicalBytes())) { + throw new InvalidActivationEvidenceException( + "Canonical World activation result differs from its exact committed owner readback"); + } + held.requireHeld(); + return committed; + }); + } + + private Optional readResultInCurrentTransaction( + WorldCanonicalInstanceActivation.Request request) { + Record row = + dsl.fetchOne( + "SELECT request_digest, request_bytes, result_bytes, result_digest " + + "FROM world_canonical_instance_activation_operation WHERE activation_request_id=?", + request.activationRequestId()); + if (row == null) return Optional.empty(); + byte[] requestBytes = required(row, "request_bytes", byte[].class); + String digest = required(row, "request_digest", String.class); + byte[] resultBytes = required(row, "result_bytes", byte[].class); + if (!digest.equals(request.requestDigest()) + || !Arrays.equals(requestBytes, request.canonicalRequestBytes())) { + throw new ActivationConflictException( + "Canonical World activation request ID was reused with changed immutable bindings"); + } + if (!required(row, "result_digest", String.class).equals(digest(resultBytes))) { + throw new InvalidActivationEvidenceException( + "Stored canonical World activation result digest is inconsistent"); + } + try { + WorldCanonicalInstanceActivation.Result result = + WorldCanonicalInstanceActivation.Result.fromStored(resultBytes); + if (!result.request().activationRequestId().equals(request.activationRequestId()) + || !Arrays.equals(result.request().canonicalRequestBytes(), requestBytes)) { + throw new InvalidActivationEvidenceException( + "Stored canonical World activation result differs from its exact operation identity"); + } + return Optional.of(result); + } catch (IllegalArgumentException invalid) { + throw new InvalidActivationEvidenceException( + "Stored canonical World activation result is invalid", invalid); + } + } + + private void insertResult( + WorldCanonicalInstanceActivation.Request request, + WorldCanonicalInstanceActivation.Result result) { + byte[] resultBytes = result.canonicalBytes(); + dsl.execute( + "INSERT INTO world_canonical_instance_activation_operation " + + "(activation_request_id,request_digest,request_bytes,preparing_evidence_bytes," + + "canonical_game_instance_id,world_instance_id,expected_lifecycle_epoch,expected_row_version," + + "outcome,terminal_code,result_lifecycle_epoch,result_row_version,result_bytes,result_digest) " + + "VALUES (?,?,?,?,?,(SELECT world_instance_id FROM world_canonical_instance_association " + + "WHERE canonical_game_instance_id=?),?,?,?,?,?,?,?,?)", + request.activationRequestId(), + request.requestDigest(), + request.canonicalRequestBytes(), + request.preparingEvidenceBytes(), + request.canonicalGameInstanceId(), + request.canonicalGameInstanceId(), + request.expectedLifecycleEpoch(), + request.expectedRowVersion(), + result.outcome().name(), + result.terminalCode(), + result.lifecycleEvidence().lifecycleEpoch(), + result.lifecycleEvidence().rowVersion(), + resultBytes, + digest(resultBytes)); + } + + private static WorldCanonicalInstanceLifecycleEvidence nextActiveEvidence( + WorldCanonicalInstanceActivation.Request request, + WorldCanonicalInstanceLifecycleEvidence current) { + return new WorldCanonicalInstanceLifecycleEvidence( + request.preparing().request(), + current.launchBinding(), + current.startLocation(), + current.runtimeRoomInstanceId(), + "ACTIVE", + Math.addExact(request.expectedLifecycleEpoch(), 1L), + Math.addExact(request.expectedRowVersion(), 1L), + current.captureId(), + current.graphSha256(), + current.preparationInputDigest()); + } + + private void requireReadOnlyRepeatableReadTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World activation result read requires a read-only REPEATABLE READ transaction"); + } + Record state = transactionState(); + if (!"repeatable read".equals(required(state, "isolation", String.class)) + || !"on".equals(required(state, "read_only", String.class))) { + throw new IllegalStateException( + "World activation result read requires a read-only REPEATABLE READ transaction"); + } + } + + private void requireWritableTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World activation requires a writable READ COMMITTED transaction"); + } + Record state = transactionState(); + String actualIsolation = required(state, "isolation", String.class); + if (!"read committed".equals(actualIsolation) + || !"off".equals(required(state, "read_only", String.class))) { + throw new IllegalStateException( + "World activation requires a writable READ COMMITTED transaction"); + } + } + + private Record transactionState() { + return 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"); + } + + private static void requireNoActiveTransaction(String label) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException(label + " must not join an ambient transaction"); + } + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(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"); + } + + public static final class ActivationConflictException extends IllegalStateException { + public ActivationConflictException(String message) { + super(message); + } + } + + public static final class InvalidActivationEvidenceException extends IllegalStateException { + public InvalidActivationEvidenceException(String message) { + super(message); + } + + public InvalidActivationEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationService.java new file mode 100644 index 0000000000..d8d29ed7ad --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationService.java @@ -0,0 +1,84 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Default-denied, unregistered canonical World lifecycle operation. No transport or production + * source/current-Account verifier is installed by this component slice. + */ +public final class WorldCanonicalInstanceActivationService { + private final WorldCanonicalInstanceActivationRepository repository; + private final ActivationAuthorityVerifier verifier; + + /** + * Production-safe default: new activations remain denied until an explicit verifier is supplied. + */ + public WorldCanonicalInstanceActivationService( + WorldCanonicalInstanceActivationRepository repository) { + this(repository, WorldCanonicalInstanceActivationService::denyByDefault); + } + + /** Constructor for an explicitly supplied owner verifier, including isolated proof fixtures. */ + public WorldCanonicalInstanceActivationService( + WorldCanonicalInstanceActivationRepository repository, ActivationAuthorityVerifier verifier) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.verifier = Objects.requireNonNull(verifier, "verifier"); + } + + /** + * Replays an exact immutable prior result without rechecking current lifecycle state. A new + * operation verifies all remote/current authority outside World transactions and keeps its + * operation-specific local fence held through commit. + */ + public WorldCanonicalInstanceActivation.Result activate( + WorldCanonicalInstanceActivation.Request request) { + Objects.requireNonNull(request, "request"); + requireNoActiveTransaction(); + var prior = repository.readResult(request); + if (prior.isPresent()) return prior.orElseThrow(); + + HeldActivationAuthority held = + Objects.requireNonNull( + verifier.verifyAndHold(request), + "Canonical activation verifier returned no held operation authority"); + try (held) { + held.requireHeld(); + WorldCanonicalInstanceActivation.Result result = repository.activate(request, held); + held.requireHeld(); + return result; + } + } + + private static HeldActivationAuthority denyByDefault( + WorldCanonicalInstanceActivation.Request request) { + throw new ActivationDeniedException( + "Canonical World activation has no authenticated current source/release and Account operation-authority verifier"); + } + + private static void requireNoActiveTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical World activation must verify outside an ambient transaction"); + } + } + + @FunctionalInterface + public interface ActivationAuthorityVerifier { + HeldActivationAuthority verifyAndHold(WorldCanonicalInstanceActivation.Request request); + } + + /** Distinct, operation-specific fence; a Draft/publication fence is not activation authority. */ + public interface HeldActivationAuthority extends AutoCloseable { + void requireHeld(); + + @Override + void close(); + } + + public static final class ActivationDeniedException extends IllegalStateException { + public ActivationDeniedException(String message) { + super(message); + } + } +} 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 53f96728ac..d34748d9c6 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 @@ -379,17 +379,30 @@ Optional readOwnerAssociationInOwnerTransacti return readOwnerAssociation(canonicalGameInstanceId, true); } + /** Reuses the exact immutable source reconstruction inside a writable activation transaction. */ + Optional readOwnerAssociationInActivationTransaction( + UUID canonicalGameInstanceId) { + requireWritableActivationTransaction(); + return readOwnerAssociation(canonicalGameInstanceId, true, true); + } + private Optional readOwnerAssociation( UUID canonicalGameInstanceId, boolean inOwnerSnapshot) { + return readOwnerAssociation(canonicalGameInstanceId, inOwnerSnapshot, false); + } + + private Optional readOwnerAssociation( + UUID canonicalGameInstanceId, boolean inOwnerSnapshot, boolean inActivationTransaction) { requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); Record row = findByCanonicalGameInstance(canonicalGameInstanceId); if (row == null) { return Optional.empty(); } - return Optional.of(toAssociation(row, inOwnerSnapshot)); + return Optional.of(toAssociation(row, inOwnerSnapshot, inActivationTransaction)); } - private WorldCanonicalInstanceAssociation toAssociation(Record row, boolean inOwnerSnapshot) { + private WorldCanonicalInstanceAssociation toAssociation( + Record row, boolean inOwnerSnapshot, boolean inActivationTransaction) { try { short schemaVersion = required(row, SCHEMA_VERSION); if (schemaVersion != 1) { @@ -403,10 +416,13 @@ private WorldCanonicalInstanceAssociation toAssociation(Record row, boolean inOw UUID bindingOperationId = required(row, LAUNCH_BINDING_OPERATION_ID); UUID intakeRequestId = required(row, INTAKE_REQUEST_ID); WorldCompleteLaunchBindingRepository.StoredBinding storedBinding = - (inOwnerSnapshot - ? launchBindingRepository.readInOwnerReadOnlyRepeatableRead( + (inActivationTransaction + ? launchBindingRepository.readInOwnerActivationTransaction( namespace, tenantId, controlRequestId) - : launchBindingRepository.read(namespace, tenantId, controlRequestId)) + : inOwnerSnapshot + ? launchBindingRepository.readInOwnerReadOnlyRepeatableRead( + namespace, tenantId, controlRequestId) + : launchBindingRepository.read(namespace, tenantId, controlRequestId)) .orElseThrow( () -> new InvalidAssociationEvidenceException( @@ -416,10 +432,13 @@ private WorldCanonicalInstanceAssociation toAssociation(Record row, boolean inOw "World canonical association substituted its complete launch binding"); } WorldAuthoredSourceIntakeReceipt sourceReceipt = - (inOwnerSnapshot - ? sourceIntakeRepository.readInOwnerReadOnlyRepeatableRead( + (inActivationTransaction + ? sourceIntakeRepository.readInOwnerActivationTransaction( namespace, intakeRequestId) - : sourceIntakeRepository.read(namespace, intakeRequestId)) + : inOwnerSnapshot + ? sourceIntakeRepository.readInOwnerReadOnlyRepeatableRead( + namespace, intakeRequestId) + : sourceIntakeRepository.read(namespace, intakeRequestId)) .orElseThrow( () -> new InvalidAssociationEvidenceException( @@ -428,11 +447,15 @@ private WorldCanonicalInstanceAssociation toAssociation(Record row, boolean inOw launchBindingRepository.toReceipt(storedBinding, sourceReceipt); UUID canonicalVersionId = required(row, CANONICAL_VERSION_ID); WorldAuthoredVersionIdentityReceipt versionIdentity = - (inOwnerSnapshot - ? versionIdentityRepository.readByCanonicalVersionInOwnerReadOnlyRepeatableRead( + (inActivationTransaction + ? versionIdentityRepository.readByCanonicalVersionInOwnerActivationTransaction( namespace, tenantId, worldSlug, canonicalVersionId) - : versionIdentityRepository.readByCanonicalVersion( - namespace, tenantId, worldSlug, canonicalVersionId)) + : inOwnerSnapshot + ? versionIdentityRepository + .readByCanonicalVersionInOwnerReadOnlyRepeatableRead( + namespace, tenantId, worldSlug, canonicalVersionId) + : versionIdentityRepository.readByCanonicalVersion( + namespace, tenantId, worldSlug, canonicalVersionId)) .orElseThrow( () -> new InvalidAssociationEvidenceException( @@ -853,6 +876,27 @@ private void requireReadOnlyRepeatableReadOwnerTransaction() { } } + private void requireWritableActivationTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World canonical association activation read requires a writable READ COMMITTED owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + if (!"read committed".equals(state.get("isolation", String.class)) + || !"off".equals(state.get("read_only", String.class))) { + throw new IllegalStateException( + "World canonical association activation read requires a writable READ COMMITTED 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/WorldCanonicalInstanceLifecycleReadRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java index f493d154e9..22f2677b6e 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 @@ -84,38 +84,57 @@ public Optional read( 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); - } + return readInCurrentOwnerTransaction(request, false); })); } + /** + * Reconstructs the same exact owner evidence while a writable activation transaction holds it. + */ + Optional readForActivationInOwnerTransaction( + WorldCanonicalInstanceLifecycleEvidence.Request request) { + Objects.requireNonNull(request, "request"); + requireWritableOwnerTransaction(); + return Optional.ofNullable(readInCurrentOwnerTransaction(request, true)); + } + + private WorldCanonicalInstanceLifecycleEvidence readInCurrentOwnerTransaction( + WorldCanonicalInstanceLifecycleEvidence.Request request, boolean lockLifecycleRow) { + try { + Optional maybeAssociation = + lockLifecycleRow + ? associationRepository.readOwnerAssociationInActivationTransaction( + request.canonicalGameInstanceId()) + : 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, lockLifecycleRow); + } 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) { + Record preparation, + boolean lockLifecycleRow) { try { UUID canonicalGameInstanceId = request.canonicalGameInstanceId(); UUID captureId = required(preparation, "capture_id", UUID.class); @@ -168,7 +187,7 @@ private WorldCanonicalInstanceLifecycleEvidence readMaterialized( } requireOriginalSelector(selector, receipt, graphBytes); RoomMapping mapping = requireMappedRoom(association, startLocation, selectorBytes); - Record lifecycle = readLifecycleRow(association, request); + Record lifecycle = readLifecycleRow(association, request, lockLifecycleRow); return new WorldCanonicalInstanceLifecycleEvidence( request, @@ -422,9 +441,12 @@ private RoomMapping requireMappedRoom( private Record readLifecycleRow( WorldCanonicalInstanceAssociation association, - WorldCanonicalInstanceLifecycleEvidence.Request request) { + WorldCanonicalInstanceLifecycleEvidence.Request request, + boolean lockLifecycleRow) { Record row = - dsl.fetchOne("SELECT * FROM world_instance WHERE id=?", association.worldInstanceId()); + dsl.fetchOne( + "SELECT * FROM world_instance WHERE id=?" + (lockLifecycleRow ? " FOR UPDATE" : ""), + association.worldInstanceId()); if (row == null || required(row, "id", Long.class) != association.worldInstanceId() || !request @@ -635,6 +657,28 @@ private void requireReadOnlyRepeatableReadOwnerTransaction() { } } + private void requireWritableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World activation evidence requires a writable READ COMMITTED owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + String actualIsolation = required(state, "isolation", String.class); + if (!"read committed".equals(actualIsolation) + || !"off".equals(required(state, "read_only", String.class))) { + throw new IllegalStateException( + "World activation evidence requires a writable READ COMMITTED owner transaction"); + } + } + private static InvalidLifecycleEvidenceException invalid(String message) { return new InvalidLifecycleEvidenceException(message); } 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 e967e16b8c..9a5b9509fe 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 @@ -86,6 +86,15 @@ Optional readInOwnerReadOnlyRepeatableRead( return readValidated(namespace, canonicalTenantId, controlPlaneRequestId); } + /** + * Reconstructs the same immutable binding inside the writable canonical activation transaction. + */ + Optional readInOwnerActivationTransaction( + String namespace, UUID canonicalTenantId, String controlPlaneRequestId) { + requireWritableActivationTransaction(); + return readValidated(namespace, canonicalTenantId, controlPlaneRequestId); + } + private Optional readValidated( String namespace, UUID canonicalTenantId, String controlPlaneRequestId) { validateKey(namespace, canonicalTenantId, controlPlaneRequestId); @@ -408,6 +417,27 @@ private void requireReadOnlyRepeatableReadOwnerTransaction() { } } + private void requireWritableActivationTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World complete launch binding activation read requires a writable READ COMMITTED owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + if (!"read committed".equals(state.get("isolation", String.class)) + || !"off".equals(state.get("read_only", String.class))) { + throw new IllegalStateException( + "World complete launch binding activation read requires a writable READ COMMITTED owner transaction"); + } + } + private static void requireWritableReadCommittedOwnerTransaction() { if (!TransactionSynchronizationManager.isActualTransactionActive()) { throw new IllegalStateException( diff --git a/services/world-management-service/src/main/resources/db/migration/V43__canonical_instance_activation_operation.sql b/services/world-management-service/src/main/resources/db/migration/V43__canonical_instance_activation_operation.sql new file mode 100644 index 0000000000..7ea2082cfe --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V43__canonical_instance_activation_operation.sql @@ -0,0 +1,453 @@ +-- Canonical World activation is one immutable owner operation. A row can become ACTIVE only +-- through the exact PREPARING epoch/row-version CAS retained here. +CREATE TABLE world_canonical_instance_activation_operation ( + activation_request_id UUID PRIMARY KEY, + request_digest VARCHAR(71) NOT NULL CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'), + request_bytes BYTEA NOT NULL CHECK (octet_length(request_bytes) > 0), + preparing_evidence_bytes BYTEA NOT NULL CHECK (octet_length(preparing_evidence_bytes) > 0), + canonical_game_instance_id UUID NOT NULL, + world_instance_id BIGINT NOT NULL, + expected_lifecycle_epoch BIGINT NOT NULL CHECK (expected_lifecycle_epoch > 0), + expected_row_version BIGINT NOT NULL CHECK (expected_row_version >= 0), + outcome VARCHAR(16) NOT NULL CHECK (outcome IN ('COMMITTED', 'ABORTED')), + terminal_code VARCHAR(64), + result_lifecycle_epoch BIGINT NOT NULL CHECK (result_lifecycle_epoch > 0), + result_row_version BIGINT NOT NULL CHECK (result_row_version >= 0), + result_bytes BYTEA NOT NULL CHECK (octet_length(result_bytes) > 0), + result_digest VARCHAR(71) NOT NULL CHECK (result_digest ~ '^sha256:[0-9a-f]{64}$'), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_world_activation_association + FOREIGN KEY (canonical_game_instance_id) + REFERENCES world_canonical_instance_association(canonical_game_instance_id) + ON DELETE RESTRICT, + CONSTRAINT ck_world_activation_outcome_shape CHECK ( + (outcome = 'COMMITTED' AND terminal_code IS NULL + AND result_lifecycle_epoch = expected_lifecycle_epoch + 1 + AND result_row_version = expected_row_version + 1) + OR (outcome = 'ABORTED' AND terminal_code IS NOT NULL + AND length(btrim(terminal_code)) BETWEEN 1 AND 64) + ), + CONSTRAINT ck_world_activation_request_id_non_nil + CHECK (activation_request_id <> '00000000-0000-0000-0000-000000000000'::UUID) +); +CREATE UNIQUE INDEX uq_world_activation_one_commit_per_instance + ON world_canonical_instance_activation_operation(canonical_game_instance_id) + WHERE outcome = 'COMMITTED'; +CREATE INDEX idx_world_activation_world_row + ON world_canonical_instance_activation_operation(world_instance_id, activation_request_id); + +-- [jooq ignore start] +REVOKE ALL ON world_canonical_instance_activation_operation FROM PUBLIC; + +CREATE FUNCTION world_validate_canonical_activation_operation() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + association_row "${serviceSchema}".world_canonical_instance_association%ROWTYPE; + instance "${serviceSchema}".world_instance%ROWTYPE; + preparing JSONB; + normalized_request JSONB; + result JSONB; + lifecycle JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Canonical World activation operation evidence is immutable' + USING ERRCODE = '55000'; + END IF; + preparing := convert_from(NEW.preparing_evidence_bytes, 'UTF8')::JSONB; + normalized_request := convert_from(NEW.request_bytes, 'UTF8')::JSONB; + result := convert_from(NEW.result_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(preparing) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(preparing)) <> 11 + OR (SELECT count(*) FROM jsonb_object_keys(preparing->'request')) <> 14 + OR preparing->>'schema' IS DISTINCT FROM 'world-canonical-instance-lifecycle-evidence/v1' + OR preparing->>'lifecycleStatus' IS DISTINCT FROM 'PREPARING' + OR (preparing->'request'->>'canonicalGameInstanceId') IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR (preparing->>'lifecycleEpoch') IS DISTINCT FROM NEW.expected_lifecycle_epoch::TEXT + OR (preparing->>'rowVersion') IS DISTINCT FROM NEW.expected_row_version::TEXT + OR jsonb_typeof(normalized_request) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(normalized_request)) <> 3 + OR (SELECT count(*) FROM jsonb_object_keys(normalized_request->'preparingEvidence')) <> 11 + OR (SELECT count(*) FROM jsonb_object_keys(normalized_request->'preparingEvidence'->'request')) <> 13 + OR normalized_request->>'schema' IS DISTINCT FROM 'world-canonical-instance-activation-request/v1' + OR normalized_request->>'activationRequestId' IS DISTINCT FROM NEW.activation_request_id::TEXT + OR NEW.request_digest IS DISTINCT FROM + ('sha256:' || encode(sha256(NEW.request_bytes), 'hex')) + OR NEW.result_digest IS DISTINCT FROM + ('sha256:' || encode(sha256(NEW.result_bytes), 'hex')) + OR normalized_request->'preparingEvidence' IS DISTINCT FROM + (preparing - 'request' || jsonb_build_object( + 'request', (preparing->'request') - 'readRequestId')) THEN + RAISE EXCEPTION 'Canonical activation request differs from its exact retained PREPARING evidence' + USING ERRCODE = '23514'; + END IF; + IF jsonb_typeof(result) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(result)) <> 8 + OR result->>'schema' IS DISTINCT FROM 'world-canonical-instance-activation-result/v1' + OR result->>'activationRequestId' IS DISTINCT FROM NEW.activation_request_id::TEXT + OR result->>'requestDigest' IS DISTINCT FROM NEW.request_digest + OR result->>'outcome' IS DISTINCT FROM NEW.outcome + OR result->>'terminalCode' IS DISTINCT FROM NEW.terminal_code + OR (NEW.terminal_code IS NULL AND jsonb_typeof(result->'terminalCode') IS DISTINCT FROM 'null') + OR (NEW.terminal_code IS NOT NULL AND jsonb_typeof(result->'terminalCode') IS DISTINCT FROM 'string') + OR decode(result->>'requestBytesBase64', 'base64') IS DISTINCT FROM NEW.request_bytes + OR decode(result->>'preparingEvidenceBytesBase64', 'base64') IS DISTINCT FROM NEW.preparing_evidence_bytes THEN + RAISE EXCEPTION 'Canonical activation result differs from its immutable request outcome' + USING ERRCODE = '23514'; + END IF; + lifecycle := convert_from(decode(result->>'lifecycleEvidenceBytesBase64', 'base64'), 'UTF8')::JSONB; + IF jsonb_typeof(lifecycle) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(lifecycle)) <> 11 + OR (SELECT count(*) FROM jsonb_object_keys(lifecycle->'request')) <> 14 + OR lifecycle->>'schema' IS DISTINCT FROM 'world-canonical-instance-lifecycle-evidence/v1' + OR lifecycle->'request' IS DISTINCT FROM preparing->'request' + OR lifecycle->>'lifecycleEpoch' IS DISTINCT FROM NEW.result_lifecycle_epoch::TEXT + OR lifecycle->>'rowVersion' IS DISTINCT FROM NEW.result_row_version::TEXT + OR (lifecycle - 'lifecycleStatus' - 'lifecycleEpoch' - 'rowVersion') + IS DISTINCT FROM + (preparing - 'lifecycleStatus' - 'lifecycleEpoch' - 'rowVersion') THEN + RAISE EXCEPTION 'Canonical activation result does not retain its exact owner lifecycle snapshot' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO association_row FROM "${serviceSchema}".world_canonical_instance_association + WHERE canonical_game_instance_id = NEW.canonical_game_instance_id; + IF NOT FOUND OR association_row.world_instance_id IS DISTINCT FROM NEW.world_instance_id + OR lifecycle->'request'->>'canonicalGameInstanceId' IS DISTINCT FROM association_row.canonical_game_instance_id::TEXT THEN + RAISE EXCEPTION 'Canonical activation operation does not resolve through its exact World association' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO instance FROM "${serviceSchema}".world_instance WHERE id=association_row.world_instance_id FOR UPDATE; + IF NOT FOUND OR instance.canonical_game_instance_id IS DISTINCT FROM NEW.canonical_game_instance_id THEN + RAISE EXCEPTION 'Canonical activation operation lost its associated World row' + USING ERRCODE = '23514'; + END IF; + IF NOT EXISTS ( + SELECT 1 + FROM "${serviceSchema}".world_canonical_instance_association a + JOIN "${serviceSchema}".world_instance w + ON w.id=a.world_instance_id + JOIN "${serviceSchema}".world_complete_launch_binding b + ON b.binding_operation_id=a.canonical_launch_binding_operation_id + JOIN "${serviceSchema}".world_authored_source_intake s + ON s.operation_id=a.intake_operation_id + JOIN "${serviceSchema}".world_authored_version_identity v + ON v.operation_id=a.version_identity_operation_id + JOIN "${serviceSchema}".world_canonical_instance_preparation p + ON p.canonical_game_instance_id=a.canonical_game_instance_id + JOIN "${serviceSchema}".world_canonical_preparation_start_location start_row + ON start_row.canonical_game_instance_id=a.canonical_game_instance_id + JOIN "${serviceSchema}".world_canonical_instance_topology_identity m + ON m.world_instance_id=a.world_instance_id + AND m.canonical_game_instance_id=a.canonical_game_instance_id + AND m.family='ROOM' AND m.template_id=start_row.room_template_id + JOIN "${serviceSchema}".room_instance r + ON r.id=m.runtime_row_id AND r.room_instance_row_id=start_row.runtime_room_instance_id + JOIN "${serviceSchema}".region_instance runtime_region + ON runtime_region.id=r.region_instance_id AND runtime_region.world_instance_id=a.world_instance_id + WHERE a.canonical_game_instance_id=NEW.canonical_game_instance_id + AND a.world_instance_id=NEW.world_instance_id + AND a.schema_version=1 + AND a.playable_state_scope='SHARED' + AND a.public_production IS TRUE + AND a.playtest_lifecycle_id IS NULL + AND a.playtest_state_generation IS NULL + AND w.canonical_game_instance_id=a.canonical_game_instance_id + AND w.canonical_target_namespace=a.canonical_target_namespace + AND w.canonical_tenant_id=a.canonical_tenant_id + AND w.canonical_world_slug=a.canonical_world_slug + AND w.playable_state_namespace_id=a.playable_state_namespace_id + AND w.playable_state_scope=a.playable_state_scope + AND w.public_production=a.public_production + AND w.control_plane_request_id=a.control_plane_request_id + AND w.canonical_launch_binding_operation_id=a.canonical_launch_binding_operation_id + AND w.tenant_id=a.local_tenant_key + AND w.game_instance_id=a.private_game_instance_key + AND b.target_namespace=a.canonical_target_namespace + AND b.canonical_tenant_id=a.canonical_tenant_id + AND b.canonical_version_id=a.canonical_version_id + AND b.world_slug=a.canonical_world_slug + AND b.control_plane_request_id=a.control_plane_request_id + AND b.intake_operation_id=a.intake_operation_id + AND b.intake_request_id=a.intake_request_id + AND b.local_tenant_key=a.local_tenant_key + AND b.source_operation_id=a.source_operation_id + AND b.source_evidence_digest=a.source_evidence_digest + AND b.intake_receipt_digest=a.intake_receipt_digest + AND b.descriptor_request_digest=a.descriptor_request_digest + AND b.descriptor_result_digest=a.descriptor_result_digest + AND b.release_attestation_digest=a.release_attestation_digest + AND b.descriptor_json::JSONB->>'launchDescriptorId'=a.launch_descriptor_id + AND b.descriptor_json::JSONB->>'versionId'=a.version_id::TEXT + AND b.descriptor_json::JSONB->>'gameTemplateId'=a.game_template_id::TEXT + AND b.descriptor_json::JSONB->>'targetNamespace'=a.canonical_target_namespace + AND b.descriptor_json::JSONB->>'canonicalTenantId'=a.canonical_tenant_id::TEXT + AND b.descriptor_json::JSONB->>'worldSlug'=a.canonical_world_slug + AND b.descriptor_json::JSONB->>'controlPlaneRequestId'=a.control_plane_request_id + AND b.descriptor_json::JSONB->>'authoredWorldSourceOperationId'=a.source_operation_id::TEXT + AND b.descriptor_json::JSONB->>'authoredWorldSourceEvidenceDigest'=a.source_evidence_digest + AND b.descriptor_json::JSONB->>'requestDigest'=a.descriptor_request_digest + AND b.descriptor_json::JSONB->>'resultDigest'=a.descriptor_result_digest + AND (CASE WHEN b.descriptor_json::JSONB->>'scriptPatchVersionPresent'='true' + THEN b.descriptor_json::JSONB->>'scriptPatchVersion' ELSE NULL END) + IS NOT DISTINCT FROM a.script_patch_version + AND b.descriptor_json::JSONB->>'runtimeFlagsJson' IS NOT DISTINCT FROM a.runtime_flags_json + AND b.descriptor_json::JSONB->>'generationConfigRevision'=a.generation_config_revision + AND b.descriptor_json::JSONB->>'versionStateEpoch'=a.version_state_epoch::TEXT + AND b.descriptor_json::JSONB->>'releaseBundleId'=a.release_bundle_id::TEXT + AND b.descriptor_json::JSONB->>'publishedReleaseBundleRef'=a.published_release_bundle_ref + AND (CASE WHEN b.descriptor_json::JSONB->>'remapSetIdPresent'='true' + THEN b.descriptor_json::JSONB->>'remapSetId' ELSE NULL END) + IS NOT DISTINCT FROM a.remap_set_id + AND b.release_attestation_json::JSONB->>'targetNamespace'=a.canonical_target_namespace + AND b.release_attestation_json::JSONB->>'descriptorResultDigest'=a.descriptor_result_digest + AND b.release_attestation_json::JSONB->>'canonicalTenantId'=a.canonical_tenant_id::TEXT + AND b.release_attestation_json::JSONB->>'canonicalVersionId'=a.canonical_version_id::TEXT + AND b.release_attestation_json::JSONB->>'worldSlug'=a.canonical_world_slug + AND b.release_attestation_json::JSONB->>'authoredWorldSourceOperationId'=a.source_operation_id::TEXT + AND b.release_attestation_json::JSONB->>'authoredWorldSourceEvidenceDigest'=a.source_evidence_digest + AND b.release_attestation_json::JSONB->>'launchDescriptorId'=a.launch_descriptor_id + AND b.release_attestation_json::JSONB->>'publishedReleaseBundleRef'=a.published_release_bundle_ref + AND b.release_attestation_json::JSONB->>'versionStateEpoch'=a.version_state_epoch::TEXT + AND b.release_attestation_json::JSONB->>'generationConfigRevision'=a.generation_config_revision + AND b.release_attestation_json::JSONB->>'evidenceDigest'=a.release_attestation_digest + AND s.target_namespace=a.canonical_target_namespace + AND s.canonical_tenant_id=a.canonical_tenant_id + AND s.world_slug=a.canonical_world_slug + AND s.local_tenant_key=a.local_tenant_key + AND s.intake_request_id=a.intake_request_id + AND s.source_operation_id=a.source_operation_id + AND s.source_evidence_digest=a.source_evidence_digest + AND s.request_digest=a.intake_request_digest + AND s.receipt_digest=a.intake_receipt_digest + AND v.target_namespace=a.canonical_target_namespace + AND v.canonical_tenant_id=a.canonical_tenant_id + AND v.world_slug=a.canonical_world_slug + AND v.canonical_version_id=a.canonical_version_id + AND v.local_tenant_key=a.local_tenant_key + AND v.local_version_key=a.local_version_key + AND v.intake_operation_id=a.intake_operation_id + AND v.intake_request_id=a.intake_request_id + AND v.intake_request_digest=a.intake_request_digest + AND v.source_operation_id=a.source_operation_id + AND v.source_evidence_digest=a.source_evidence_digest + AND v.intake_receipt_digest=a.intake_receipt_digest + AND v.game_design_version_id=a.version_id + AND v.version_state_epoch=a.version_state_epoch + AND p.target_namespace=a.canonical_target_namespace + AND p.canonical_tenant_id=a.canonical_tenant_id + AND p.world_slug=a.canonical_world_slug + AND p.control_plane_request_id=a.control_plane_request_id + AND p.canonical_version_id=a.canonical_version_id + AND p.version_identity_operation_id=a.version_identity_operation_id + AND p.world_instance_id=a.world_instance_id + AND p.private_game_instance_key=a.private_game_instance_key + AND p.capture_id::TEXT=lifecycle->>'captureId' + AND p.graph_sha256=lifecycle->>'graphSha256' + AND p.graph_sha256=encode(sha256(p.graph_bytes),'hex') + AND p.input_digest=lifecycle->>'preparationInputDigest' + AND p.input_digest=('sha256:' || encode(sha256(convert_to(p.input_json,'UTF8')),'hex')) + AND p.input_json::JSONB->>'schemaVersion'='2' + AND p.input_json::JSONB->'identity'->>'canonicalGameInstanceId'=a.canonical_game_instance_id::TEXT + AND p.input_json::JSONB->'identity'->>'targetNamespace'=a.canonical_target_namespace + AND p.input_json::JSONB->'identity'->>'canonicalTenantId'=a.canonical_tenant_id::TEXT + AND p.input_json::JSONB->'identity'->>'worldSlug'=a.canonical_world_slug + AND p.input_json::JSONB->'identity'->>'playableStateNamespaceId'=a.playable_state_namespace_id::TEXT + AND p.input_json::JSONB->'identity'->>'playableStateScope'=a.playable_state_scope + AND p.input_json::JSONB->'identity'->'publicProduction'=to_jsonb(a.public_production) + AND p.input_json::JSONB->'identity'->>'controlPlaneRequestId'=a.control_plane_request_id + AND p.input_json::JSONB->'launchBinding'->>'operationId'=a.canonical_launch_binding_operation_id::TEXT + AND p.input_json::JSONB->'launchBinding'->>'targetNamespace'=b.target_namespace + AND p.input_json::JSONB->'launchBinding'->>'canonicalTenantId'=b.canonical_tenant_id::TEXT + AND p.input_json::JSONB->'launchBinding'->>'worldSlug'=b.world_slug + AND p.input_json::JSONB->'launchBinding'->>'controlPlaneRequestId'=b.control_plane_request_id + AND p.input_json::JSONB->'launchBinding'->>'canonicalVersionId'=b.canonical_version_id::TEXT + AND p.input_json::JSONB->'launchBinding'->>'descriptorRequestDigest'=b.descriptor_request_digest + AND p.input_json::JSONB->'launchBinding'->>'descriptorResultDigest'=b.descriptor_result_digest + AND p.input_json::JSONB->'launchBinding'->>'releaseAttestationDigest'=b.release_attestation_digest + AND p.input_json::JSONB->'launchBinding'->>'localTenantKey'=b.local_tenant_key::TEXT + AND p.input_json::JSONB->'launchBinding'->>'intakeOperationId'=b.intake_operation_id::TEXT + AND p.input_json::JSONB->'launchBinding'->>'intakeRequestId'=b.intake_request_id::TEXT + AND p.input_json::JSONB->'launchBinding'->>'sourceOperationId'=b.source_operation_id::TEXT + AND p.input_json::JSONB->'launchBinding'->>'sourceEvidenceDigest'=b.source_evidence_digest + AND p.input_json::JSONB->'launchBinding'->>'intakeRequestDigest'=s.request_digest + AND p.input_json::JSONB->'launchBinding'->>'intakeReceiptDigest'=s.receipt_digest + AND p.input_json::JSONB->'versionIdentity'->>'operationId'=v.operation_id::TEXT + AND p.input_json::JSONB->'versionIdentity'->>'canonicalVersionId'=v.canonical_version_id::TEXT + AND p.input_json::JSONB->'versionIdentity'->>'localVersionKey'=v.local_version_key::TEXT + AND p.input_json::JSONB->'versionIdentity'->>'gameDesignVersionId'=v.game_design_version_id::TEXT + AND p.input_json::JSONB->'versionIdentity'->>'versionState'=v.version_state_state + AND p.input_json::JSONB->'versionIdentity'->>'versionStateEpoch'=v.version_state_epoch::TEXT + AND p.input_json::JSONB->'versionIdentity'->>'evidenceDigest'=v.version_state_evidence_digest + AND p.input_json::JSONB->'sourceIntake'->>'schemaVersion'=s.schema_version::TEXT + AND p.input_json::JSONB->'sourceIntake'->>'targetNamespace'=s.target_namespace + AND p.input_json::JSONB->'sourceIntake'->>'intakeRequestId'=s.intake_request_id::TEXT + AND p.input_json::JSONB->'sourceIntake'->>'operationId'=s.operation_id::TEXT + AND p.input_json::JSONB->'sourceIntake'->>'canonicalTenantId'=s.canonical_tenant_id::TEXT + AND p.input_json::JSONB->'sourceIntake'->>'worldSlug'=s.world_slug + AND p.input_json::JSONB->'sourceIntake'->>'sourceOperationId'=s.source_operation_id::TEXT + AND p.input_json::JSONB->'sourceIntake'->>'sourceEvidenceDigest'=s.source_evidence_digest + AND p.input_json::JSONB->'sourceIntake'->>'requestDigest'=s.request_digest + AND p.input_json::JSONB->'sourceIntake'->>'receiptDigest'=s.receipt_digest + AND p.input_json::JSONB->'sourceIntake'->>'localTenantKey'=s.local_tenant_key::TEXT + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'schemaVersion'=s.source_schema_version::TEXT + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'registrationRequestId'=s.source_registration_request_id::TEXT + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'sourceOperationId'=s.source_operation_id::TEXT + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'requestDigest'=s.source_request_digest + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'canonicalTenantId'=s.canonical_tenant_id::TEXT + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'tenantSlug'=s.tenant_slug + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'worldSlug'=s.world_slug + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'worldDisplayName'=s.world_display_name + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'sourceGameRowId'=s.source_game_row_id::TEXT + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'sourceGameTenantKey'=s.source_game_tenant_key + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'provenanceKind'=s.source_provenance_kind + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'evidenceDigest'=s.source_evidence_digest + AND p.input_json::JSONB->'topology'->>'captureId'=p.capture_id::TEXT + AND p.input_json::JSONB->'topology'->>'targetNamespace'=a.canonical_target_namespace + AND p.input_json::JSONB->'topology'->>'canonicalTenantId'=a.canonical_tenant_id::TEXT + AND p.input_json::JSONB->'topology'->>'canonicalVersionId'=a.canonical_version_id::TEXT + AND p.input_json::JSONB->'topology'->>'versionIdentityOperationId'=a.version_identity_operation_id::TEXT + AND lifecycle->'request'->>'schemaVersion'='1' + AND lifecycle->'request'->>'targetNamespace'=a.canonical_target_namespace + AND lifecycle->'request'->>'canonicalTenantId'=a.canonical_tenant_id::TEXT + AND lifecycle->'request'->>'worldSlug'=a.canonical_world_slug + AND lifecycle->'request'->>'canonicalGameInstanceId'=a.canonical_game_instance_id::TEXT + AND lifecycle->'request'->>'playableStateNamespaceId'=a.playable_state_namespace_id::TEXT + AND lifecycle->'request'->>'playableStateScope'=a.playable_state_scope + AND lifecycle->'request'->'publicProduction'=to_jsonb(a.public_production) + AND lifecycle->'request'->>'controlPlaneRequestId'=a.control_plane_request_id + AND lifecycle->'request'->>'canonicalVersionId'=a.canonical_version_id::TEXT + AND lifecycle->'request'->>'expectedDescriptorRequestDigest'=a.descriptor_request_digest + AND lifecycle->'request'->>'expectedDescriptorResultDigest'=a.descriptor_result_digest + AND lifecycle->'request'->>'expectedReleaseAttestationDigest'=a.release_attestation_digest + AND decode(preparing->>'launchBindingBytesBase64','base64') IS NOT NULL + AND convert_from(decode(preparing->>'launchBindingBytesBase64','base64'),'UTF8')::JSONB + IS NOT DISTINCT FROM jsonb_build_object( + 'descriptor', b.descriptor_json::JSONB, + 'releaseAttestation', b.release_attestation_json::JSONB) + AND start_row.world_instance_id=a.world_instance_id + AND start_row.canonical_tenant_id=a.canonical_tenant_id + AND start_row.canonical_version_id=a.canonical_version_id + AND lifecycle->'startLocation'->>'tenantId'=start_row.canonical_tenant_id::TEXT + AND lifecycle->'startLocation'->>'versionId'=start_row.canonical_version_id::TEXT + AND lifecycle->'startLocation'->>'roomTemplateId'=start_row.room_template_id::TEXT + AND lifecycle->>'runtimeRoomInstanceId'=start_row.runtime_room_instance_id::TEXT + AND lifecycle->>'captureId'=p.capture_id::TEXT + AND lifecycle->>'graphSha256'=p.graph_sha256 + AND lifecycle->>'preparationInputDigest'=p.input_digest + AND start_row.graph_digest=('sha256:' || p.graph_sha256) + AND start_row.evidence_bytes=decode(p.input_json::JSONB->>'worldStartLocationEvidenceBase64','base64') + AND m.runtime_room_instance_id=start_row.runtime_room_instance_id + AND m.runtime_row_id=r.id + AND r.template_room_id=m.template_private_row_key + AND r.tenant_id=a.local_tenant_key + AND r.game_instance_id=a.private_game_instance_key + AND runtime_region.tenant_id=a.local_tenant_key + AND runtime_region.game_instance_id=a.private_game_instance_key + ) THEN + RAISE EXCEPTION 'Canonical activation proof differs from immutable World association, launch, preparation, or ROOM bindings' + USING ERRCODE = '23514'; + END IF; + IF NEW.outcome = 'COMMITTED' THEN + IF instance.status IS DISTINCT FROM 'PREPARING' + OR instance.lifecycle_epoch IS DISTINCT FROM NEW.expected_lifecycle_epoch + OR instance.row_version IS DISTINCT FROM NEW.expected_row_version + OR lifecycle->>'lifecycleStatus' IS DISTINCT FROM 'ACTIVE' THEN + RAISE EXCEPTION 'Committed canonical activation lacks the exact current PREPARING CAS' + USING ERRCODE = '23514'; + END IF; + ELSIF lifecycle->>'lifecycleStatus' IS DISTINCT FROM instance.status + OR lifecycle->>'lifecycleEpoch' IS DISTINCT FROM instance.lifecycle_epoch::TEXT + OR lifecycle->>'rowVersion' IS DISTINCT FROM instance.row_version::TEXT THEN + RAISE EXCEPTION 'Aborted canonical activation must retain the actual current lifecycle state' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION world_validate_canonical_activation_operation() FROM PUBLIC; +CREATE TRIGGER trg_world_canonical_activation_operation + BEFORE INSERT OR UPDATE OR DELETE ON world_canonical_instance_activation_operation + FOR EACH ROW EXECUTE FUNCTION world_validate_canonical_activation_operation(); + +CREATE FUNCTION world_reject_canonical_activation_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + RAISE EXCEPTION 'Canonical World activation operation evidence is immutable and retained' + USING ERRCODE = '55000'; + RETURN NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_reject_canonical_activation_truncate() FROM PUBLIC; +CREATE TRIGGER trg_world_canonical_activation_operation_no_truncate + BEFORE TRUNCATE ON world_canonical_instance_activation_operation + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_canonical_activation_truncate(); + +CREATE FUNCTION world_require_committed_activation_at_commit() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + instance "${serviceSchema}".world_instance%ROWTYPE; + result JSONB; +BEGIN + IF NEW.outcome <> 'COMMITTED' THEN RETURN NULL; END IF; + SELECT * INTO instance FROM "${serviceSchema}".world_instance + WHERE id=NEW.world_instance_id AND canonical_game_instance_id=NEW.canonical_game_instance_id; + result := convert_from(NEW.result_bytes, 'UTF8')::JSONB; + IF NOT FOUND + OR instance.status IS DISTINCT FROM 'ACTIVE' + OR instance.lifecycle_epoch IS DISTINCT FROM NEW.result_lifecycle_epoch + OR instance.row_version IS DISTINCT FROM NEW.result_row_version + OR result->>'outcome' IS DISTINCT FROM 'COMMITTED' + OR result->>'requestDigest' IS DISTINCT FROM NEW.request_digest + OR convert_from(decode(result->>'lifecycleEvidenceBytesBase64','base64'),'UTF8')::JSONB->>'lifecycleStatus' + IS DISTINCT FROM 'ACTIVE' THEN + RAISE EXCEPTION 'Committed canonical activation must include its exact ACTIVE lifecycle CAS before commit' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_require_committed_activation_at_commit() FROM PUBLIC; +CREATE CONSTRAINT TRIGGER trg_world_canonical_activation_commit_cas + AFTER INSERT ON world_canonical_instance_activation_operation + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION world_require_committed_activation_at_commit(); + +CREATE FUNCTION world_guard_canonical_activation_transition() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + IF OLD.canonical_game_instance_id IS NOT NULL AND NEW.status = 'ACTIVE' + AND (OLD.status IS DISTINCT FROM NEW.status + OR OLD.lifecycle_epoch IS DISTINCT FROM NEW.lifecycle_epoch + OR OLD.row_version IS DISTINCT FROM NEW.row_version) THEN + IF OLD.status IS DISTINCT FROM 'PREPARING' + OR NEW.lifecycle_epoch IS DISTINCT FROM OLD.lifecycle_epoch + 1 + OR NEW.row_version IS DISTINCT FROM OLD.row_version + 1 + OR NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_instance_activation_operation o + WHERE o.canonical_game_instance_id = OLD.canonical_game_instance_id + AND o.world_instance_id = OLD.id + AND o.outcome = 'COMMITTED' + AND o.expected_lifecycle_epoch = OLD.lifecycle_epoch + AND o.expected_row_version = OLD.row_version + AND o.result_lifecycle_epoch = NEW.lifecycle_epoch + AND o.result_row_version = NEW.row_version + AND convert_from(o.result_bytes, 'UTF8')::JSONB->>'outcome' = 'COMMITTED') THEN + RAISE EXCEPTION 'Canonical World PREPARING-to-ACTIVE transition requires its exact activation operation' + USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION world_guard_canonical_activation_transition() FROM PUBLIC; +CREATE TRIGGER trg_world_canonical_activation_transition + BEFORE UPDATE ON world_instance + FOR EACH ROW EXECUTE FUNCTION world_guard_canonical_activation_transition(); +-- [jooq ignore stop] 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..58c4967657 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 @@ -9,7 +9,10 @@ import io.grpc.Status; import io.grpc.stub.StreamObserver; import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.ArrayList; +import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -20,6 +23,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; @@ -406,6 +410,364 @@ void lifecycleReadFollowsCurrentWorldEpochAndReturnsExactCanonicalServiceEcho() assertOrigin(); } + @Test + void canonicalActivationCommitsOneOwnerCasAndReplaysItsImmutableResultAfterLaterLifecycleMove() + throws Exception { + PreparedLifecycleFixture fixture = materializedLifecycleFixture(); + byte[] preparationBefore = preparationRows(fixture.input().canonicalGameInstanceId()); + var rawCommitRequest = + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); + var rawPredictedActive = + new WorldCanonicalInstanceLifecycleEvidence( + fixture.preparing().request(), + fixture.preparing().launchBinding(), + fixture.preparing().startLocation(), + fixture.preparing().runtimeRoomInstanceId(), + "ACTIVE", + fixture.preparing().lifecycleEpoch() + 1L, + fixture.preparing().rowVersion() + 1L, + fixture.preparing().captureId(), + fixture.preparing().graphSha256(), + fixture.preparing().preparationInputDigest()); + var rawCommittedResult = + new WorldCanonicalInstanceActivation.Result( + rawCommitRequest, + WorldCanonicalInstanceActivation.Outcome.COMMITTED, + null, + rawPredictedActive); + byte[] rawRequestBytes = rawCommitRequest.canonicalRequestBytes(); + byte[] rawResultBytes = rawCommittedResult.canonicalBytes(); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + dsl.execute( + "INSERT INTO world_canonical_instance_activation_operation " + + "(activation_request_id,request_digest,request_bytes,preparing_evidence_bytes," + + "canonical_game_instance_id,world_instance_id,expected_lifecycle_epoch,expected_row_version," + + "outcome,terminal_code,result_lifecycle_epoch,result_row_version,result_bytes,result_digest) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + rawCommitRequest.activationRequestId(), + rawCommitRequest.requestDigest(), + rawRequestBytes, + rawCommitRequest.preparingEvidenceBytes(), + rawCommitRequest.canonicalGameInstanceId(), + fixture.materialized().association().worldInstanceId(), + rawCommitRequest.expectedLifecycleEpoch(), + rawCommitRequest.expectedRowVersion(), + "COMMITTED", + null, + rawCommittedResult.lifecycleEvidence().lifecycleEpoch(), + rawCommittedResult.lifecycleEvidence().rowVersion(), + rawResultBytes, + sha256Digest(rawResultBytes)); + return null; + })) + .hasMessageContaining("must include its exact ACTIVE lifecycle CAS before commit"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_instance_activation_operation WHERE activation_request_id=?", + rawCommitRequest.activationRequestId())) + .get(0, Long.class)) + .isZero(); + + var first = + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); + var second = + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); + CountDownLatch bothAuthoritiesChecked = new CountDownLatch(2); + AtomicInteger verifierCalls = new AtomicInteger(); + var service = + canonicalActivationService( + fixture, + request -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + verifierCalls.incrementAndGet(); + bothAuthoritiesChecked.countDown(); + await(bothAuthoritiesChecked); + return stipulatedActivationAuthority(); + }); + ExecutorService executor = Executors.newFixedThreadPool(2); + WorldCanonicalInstanceActivation.Result firstResult; + WorldCanonicalInstanceActivation.Result secondResult; + try { + Future firstFuture = + executor.submit(() -> service.activate(first)); + Future secondFuture = + executor.submit(() -> service.activate(second)); + firstResult = firstFuture.get(45, TimeUnit.SECONDS); + secondResult = secondFuture.get(45, TimeUnit.SECONDS); + } finally { + executor.shutdownNow(); + } + + assertThat(verifierCalls).hasValue(2); + assertThat(List.of(firstResult.outcome(), secondResult.outcome())) + .containsExactlyInAnyOrder( + WorldCanonicalInstanceActivation.Outcome.COMMITTED, + WorldCanonicalInstanceActivation.Outcome.ABORTED); + var committed = + firstResult.outcome() == WorldCanonicalInstanceActivation.Outcome.COMMITTED + ? firstResult + : secondResult; + var aborted = committed == firstResult ? secondResult : firstResult; + assertThat(committed.lifecycleEvidence().lifecycleStatus()).isEqualTo("ACTIVE"); + assertThat(committed.lifecycleEvidence().lifecycleEpoch()) + .isEqualTo(fixture.preparing().lifecycleEpoch() + 1L); + assertThat(committed.lifecycleEvidence().rowVersion()) + .isEqualTo(fixture.preparing().rowVersion() + 1L); + assertThat(aborted.terminalCode()).isEqualTo("PRECONDITION_FAILED"); + var active = fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow(); + assertThat(active.lifecycleStatus()).isEqualTo("ACTIVE"); + assertThat(active.lifecycleEpoch()).isEqualTo(committed.lifecycleEvidence().lifecycleEpoch()); + assertThat(active.rowVersion()).isEqualTo(committed.lifecycleEvidence().rowVersion()); + + var repository = + new WorldCanonicalInstanceActivationRepository(dsl, manager, fixture.lifecycleRepository()); + assertThat(repository.readResult(committed.request()).orElseThrow().canonicalBytes()) + .containsExactly(committed.canonicalBytes()); + int callsAfterFirstAttempt = verifierCalls.get(); + assertThat(service.activate(committed.request()).canonicalBytes()) + .containsExactly(committed.canonicalBytes()); + assertThat(verifierCalls).hasValue(callsAfterFirstAttempt); + var changedExpectedVersion = + new WorldCanonicalInstanceLifecycleEvidence( + fixture.preparing().request(), + fixture.preparing().launchBinding(), + fixture.preparing().startLocation(), + fixture.preparing().runtimeRoomInstanceId(), + "PREPARING", + fixture.preparing().lifecycleEpoch(), + fixture.preparing().rowVersion() + 1L, + fixture.preparing().captureId(), + fixture.preparing().graphSha256(), + fixture.preparing().preparationInputDigest()); + var changedRetry = + new WorldCanonicalInstanceActivation.Request( + committed.request().activationRequestId(), changedExpectedVersion); + assertThatThrownBy(() -> service.activate(changedRetry)) + .isInstanceOf(WorldCanonicalInstanceActivationRepository.ActivationConflictException.class) + .hasMessageContaining("reused with changed immutable bindings"); + assertThat(verifierCalls).hasValue(callsAfterFirstAttempt); + + // A raw ACTIVE write cannot manufacture the committed operation that guards this CAS. + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_instance SET status='ACTIVE',lifecycle_epoch=lifecycle_epoch+1," + + "row_version=row_version+1 WHERE id=?", + fixture.materialized().association().worldInstanceId())) + .hasMessageContaining("requires its exact activation operation"); + + var privateKeys = fixture.materialized().association().worldPrepareFields(); + lifecycleCommandService.terminateWorldInstance( + privateKeys.privateTenantKey(), + privateKeys.privateGameInstanceKey(), + active.lifecycleEpoch(), + "activation-replay-terminal-move", + "integration lifecycle movement"); + var terminalRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT status,lifecycle_epoch FROM world_instance WHERE id=?", + fixture.materialized().association().worldInstanceId())); + assertThat(terminalRow.get("status", String.class)).isEqualTo("TERMINATED"); + assertThat(service.activate(committed.request()).canonicalBytes()) + .containsExactly(committed.canonicalBytes()); + assertThat(verifierCalls).hasValue(callsAfterFirstAttempt); + assertThat(preparationRows(fixture.input().canonicalGameInstanceId())) + .containsExactly(preparationBefore); + assertOrigin(); + } + + @Test + void canonicalActivationStoresStaleFailedOutcomeAndFreshLifecycleReadRemainsCurrent() { + PreparedLifecycleFixture fixture = materializedLifecycleFixture(); + var staleRequest = + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); + var privateKeys = fixture.materialized().association().worldPrepareFields(); + lifecycleCommandService.failPreparedWorldInstance( + privateKeys.privateTenantKey(), + privateKeys.privateGameInstanceKey(), + fixture.preparing().lifecycleEpoch(), + "stale activation proof"); + var failed = fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow(); + assertThat(failed.lifecycleStatus()).isEqualTo("FAILED_PRE_ACTIVATION"); + var service = canonicalActivationService(fixture, ignored -> stipulatedActivationAuthority()); + + var aborted = service.activate(staleRequest); + + assertThat(aborted.outcome()).isEqualTo(WorldCanonicalInstanceActivation.Outcome.ABORTED); + assertThat(aborted.terminalCode()).isEqualTo("PRECONDITION_FAILED"); + assertThat(aborted.lifecycleEvidence().canonicalBytes()) + .containsExactly(failed.canonicalBytes()); + assertThat(fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow()) + .isEqualTo(failed); + assertThat(service.activate(staleRequest).canonicalBytes()) + .containsExactly(aborted.canonicalBytes()); + assertOrigin(); + } + + @Test + void canonicalActivationRejectsSelfConsistentForgedOwnerBindingsBeforeActiveCas() + throws Exception { + PreparedLifecycleFixture fixture = materializedLifecycleFixture(); + var activationRequest = + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); + + var forgedPreparing = + (tools.jackson.databind.node.ObjectNode) + mapper.readTree(fixture.preparing().canonicalBytes()); + ((tools.jackson.databind.node.ObjectNode) forgedPreparing.get("request")) + .put("targetNamespace", "forged-world-namespace"); + byte[] forgedPreparingBytes = + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + mapper.writeValueAsString(forgedPreparing)); + + var normalizedRequest = + (tools.jackson.databind.node.ObjectNode) + mapper.readTree(activationRequest.canonicalRequestBytes()); + var normalizedPreparing = + (tools.jackson.databind.node.ObjectNode) mapper.readTree(forgedPreparingBytes); + ((tools.jackson.databind.node.ObjectNode) normalizedPreparing.get("request")) + .remove("readRequestId"); + normalizedRequest.set("preparingEvidence", normalizedPreparing); + byte[] forgedRequestBytes = + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + mapper.writeValueAsString(normalizedRequest)); + String forgedRequestDigest = sha256Digest(forgedRequestBytes); + + var forgedActive = + (tools.jackson.databind.node.ObjectNode) mapper.readTree(forgedPreparingBytes); + forgedActive.put("lifecycleStatus", "ACTIVE"); + forgedActive.put("lifecycleEpoch", Long.toString(fixture.preparing().lifecycleEpoch() + 1L)); + forgedActive.put("rowVersion", Long.toString(fixture.preparing().rowVersion() + 1L)); + byte[] forgedActiveBytes = + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + mapper.writeValueAsString(forgedActive)); + + Map forgedResult = new LinkedHashMap<>(); + forgedResult.put("schema", "world-canonical-instance-activation-result/v1"); + forgedResult.put("activationRequestId", activationRequest.activationRequestId().toString()); + forgedResult.put("requestDigest", forgedRequestDigest); + forgedResult.put( + "requestBytesBase64", java.util.Base64.getEncoder().encodeToString(forgedRequestBytes)); + forgedResult.put( + "preparingEvidenceBytesBase64", + java.util.Base64.getEncoder().encodeToString(forgedPreparingBytes)); + forgedResult.put("outcome", "COMMITTED"); + forgedResult.put("terminalCode", null); + forgedResult.put( + "lifecycleEvidenceBytesBase64", + java.util.Base64.getEncoder().encodeToString(forgedActiveBytes)); + byte[] forgedResultBytes = + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + mapper.writeValueAsString(forgedResult)); + + ownerTransaction() + .execute( + status -> { + dsl.execute("SAVEPOINT forged_world_activation"); + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO world_canonical_instance_activation_operation " + + "(activation_request_id,request_digest,request_bytes,preparing_evidence_bytes," + + "canonical_game_instance_id,world_instance_id,expected_lifecycle_epoch,expected_row_version," + + "outcome,terminal_code,result_lifecycle_epoch,result_row_version,result_bytes,result_digest) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + activationRequest.activationRequestId(), + forgedRequestDigest, + forgedRequestBytes, + forgedPreparingBytes, + activationRequest.canonicalGameInstanceId(), + fixture.materialized().association().worldInstanceId(), + activationRequest.expectedLifecycleEpoch(), + activationRequest.expectedRowVersion(), + "COMMITTED", + null, + activationRequest.expectedLifecycleEpoch() + 1L, + activationRequest.expectedRowVersion() + 1L, + forgedResultBytes, + sha256Digest(forgedResultBytes))) + .hasMessageContaining("differs from immutable World association"); + dsl.execute("ROLLBACK TO SAVEPOINT forged_world_activation"); + dsl.execute("SAVEPOINT forged_active_cas"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_instance SET status='ACTIVE',lifecycle_epoch=lifecycle_epoch+1," + + "row_version=row_version+1 WHERE id=?", + fixture.materialized().association().worldInstanceId())) + .hasMessageContaining("requires its exact activation operation"); + dsl.execute("ROLLBACK TO SAVEPOINT forged_active_cas"); + return null; + }); + + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_instance_activation_operation WHERE activation_request_id=?", + activationRequest.activationRequestId())) + .get(0, Long.class)) + .isZero(); + var lifecycle = fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow(); + assertThat(lifecycle.lifecycleStatus()).isEqualTo("PREPARING"); + assertThat(lifecycle.lifecycleEpoch()).isEqualTo(activationRequest.expectedLifecycleEpoch()); + assertThat(lifecycle.rowVersion()).isEqualTo(activationRequest.expectedRowVersion()); + assertOrigin(); + } + + @Test + void lostHeldAuthorityAfterOperationInsertRollsBackActivationAndLedger() { + PreparedLifecycleFixture fixture = materializedLifecycleFixture(); + var request = + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); + AtomicInteger checks = new AtomicInteger(); + var service = + canonicalActivationService( + fixture, + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return new WorldCanonicalInstanceActivationService.HeldActivationAuthority() { + public void requireHeld() { + int count = checks.incrementAndGet(); + if (count == 4) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_instance_activation_operation WHERE activation_request_id=?", + request.activationRequestId())) + .get(0, Long.class)) + .isEqualTo(1L); + throw new IllegalStateException("stipulated activation authority loss"); + } + } + + public void close() {} + }; + }); + + assertThatThrownBy(() -> service.activate(request)) + .hasMessageContaining("stipulated activation authority loss"); + var current = fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow(); + assertThat(current.lifecycleStatus()).isEqualTo("PREPARING"); + assertThat(current.lifecycleEpoch()).isEqualTo(fixture.preparing().lifecycleEpoch()); + assertThat(current.rowVersion()).isEqualTo(fixture.preparing().rowVersion()); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_instance_activation_operation WHERE activation_request_id=?", + request.activationRequestId())) + .get(0, Long.class)) + .isZero(); + assertOrigin(); + } + @Test void releaseSelectorRejectsChangedFrozenRequestAndSqlSubstitutionWithoutRuntimeWrites() { Fixture f = fixture(); @@ -1051,6 +1413,72 @@ public void close() { }); } + private PreparedLifecycleFixture materializedLifecycleFixture() { + Fixture f = fixture(); + var original = application(generationFreePlan(f)); + var selectedRoom = + original.plan().graph().nodes().stream() + .filter( + node -> + node.mutation().getAggregateType() + == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .map(node -> node.templateId()) + .toList() + .getLast(); + var applied = withStartRoom(original, selectedRoom); + appliedComponent().apply(applied); + var frozen = capture(applied.plan()); + var selector = + publishedEvidence( + publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + var input = preparationInput(f, frozen, selector); + var materialized = preparationComponent(preparationRepository()).prepare(input); + var lifecycleRepository = + new WorldCanonicalInstanceLifecycleReadRepository(dsl, manager, associationRepository()); + var readRequest = lifecycleReadRequest(input); + var preparing = lifecycleRepository.read(readRequest).orElseThrow(); + assertThat(preparing.lifecycleStatus()).isEqualTo("PREPARING"); + assertThat(preparing.startLocation().roomTemplateId()).isEqualTo(selectedRoom); + assertThat(preparing.runtimeRoomInstanceId()).isEqualTo(materialized.runtimeRoomInstanceId()); + return new PreparedLifecycleFixture( + input, materialized, lifecycleRepository, readRequest, preparing); + } + + private WorldCanonicalInstanceActivationService canonicalActivationService( + PreparedLifecycleFixture fixture, + WorldCanonicalInstanceActivationService.ActivationAuthorityVerifier verifier) { + return new WorldCanonicalInstanceActivationService( + new WorldCanonicalInstanceActivationRepository(dsl, manager, fixture.lifecycleRepository()), + verifier); + } + + /** + * Synthetic fixture fence only; it does not authenticate live source, release, or Account state. + */ + private static WorldCanonicalInstanceActivationService.HeldActivationAuthority + stipulatedActivationAuthority() { + return new WorldCanonicalInstanceActivationService.HeldActivationAuthority() { + private boolean open = true; + + public void requireHeld() { + assertThat(open).isTrue(); + } + + public void close() { + open = false; + } + }; + } + + private static String sha256Digest(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw new AssertionError(unavailable); + } + } + private byte[] preparationRows(UUID instance) { return Objects.requireNonNull( Objects.requireNonNull( @@ -2870,4 +3298,11 @@ private record Fixture( WorldAuthoredSourceIntakeReceipt intake, WorldAuthoredVersionIdentityReceipt version, OwnerBinding owner) {} + + private record PreparedLifecycleFixture( + WorldCanonicalInstancePreparation.Input input, + WorldCanonicalInstancePreparation.Result materialized, + WorldCanonicalInstanceLifecycleReadRepository lifecycleRepository, + WorldCanonicalInstanceLifecycleEvidence.Request readRequest, + WorldCanonicalInstanceLifecycleEvidence preparing) {} } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java index 022554ac53..f2724e8f23 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java @@ -49,6 +49,7 @@ import net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository; import net.firedevops.firemud.worldmanagement.repository.ZoneInstanceRepository; import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; +import org.jooq.DSLContext; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -68,6 +69,7 @@ class WorldLifecycleCommandServiceImplTest { private WorldEventRepository worldEventRepository; private EntityManagementClient entityManagementClient; private GameDesignClient gameDesignClient; + private DSLContext dsl; private AtomicBoolean localTransactionActive; private AtomicBoolean worldInstanceReadInLocalTransaction; private WorldLifecycleCommandServiceImpl service; @@ -85,6 +87,7 @@ void setUp() { worldEventRepository = mock(WorldEventRepository.class); entityManagementClient = mock(EntityManagementClient.class); gameDesignClient = mock(GameDesignClient.class); + dsl = mock(DSLContext.class); localTransactionActive = new AtomicBoolean(); worldInstanceReadInLocalTransaction = new AtomicBoolean(); TransactionOperations transactionOperations = @@ -117,7 +120,8 @@ public T execute(TransactionCallback action) { gameDesignClient, entityManagementClient, new SimpleMeterRegistry(), - transactionOperations); + transactionOperations, + dsl); service.initMetrics(); when(gameDesignClient.getPublishedReleaseBundle(42L, 11L)) .thenReturn( @@ -478,6 +482,37 @@ void activatePreparedWorldInstancePromotesPreparingRow() { assertEquals(2L, snapshot.lifecycleEpoch()); } + @Test + void legacyNumericActivationDeniesCanonicalAssociationBeforeReleaseRpcOrMutation() { + WorldInstance instance = new WorldInstance(); + instance.setId(201L); + instance.setTenantId(42L); + instance.setGameInstanceId(101L); + instance.setLifecycleEpoch(1L); + instance.setStatus("PREPARING"); + when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) + .thenReturn(Optional.of(instance)); + org.jooq.Record associationRow = mock(org.jooq.Record.class); + when(dsl.fetchOne( + "SELECT canonical_game_instance_id FROM world_canonical_instance_association " + + "WHERE world_instance_id=?", + 201L)) + .thenReturn(associationRow); + when(associationRow.get(0, java.util.UUID.class)) + .thenReturn(java.util.UUID.fromString("11111111-1111-4111-8111-111111111111")); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> service.activatePreparedWorldInstance(42L, 101L, 1L)); + + assertTrue(error.getMessage().startsWith("CANONICAL_LIFECYCLE_OPERATION_REQUIRED:")); + assertEquals("PREPARING", instance.getStatus()); + assertEquals(1L, instance.getLifecycleEpoch()); + verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); + verifyNoInteractions(gameDesignClient); + } + @Test void failPreparedWorldInstanceMarksPreparingRowFailed() { WorldInstance instance = new WorldInstance(); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepositoryTest.java new file mode 100644 index 0000000000..6afb956d93 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepositoryTest.java @@ -0,0 +1,80 @@ +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 static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivation; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationService; +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 WorldCanonicalInstanceActivationRepositoryTest { + private final DSLContext dsl = mock(DSLContext.class); + private final PlatformTransactionManager manager = mock(PlatformTransactionManager.class); + private final WorldCanonicalInstanceLifecycleReadRepository lifecycle = + mock(WorldCanonicalInstanceLifecycleReadRepository.class); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Test + void immutableResultReadRejectsAmbientTransactionBeforeRepositoryOrDatabaseUse() { + var repository = new WorldCanonicalInstanceActivationRepository(dsl, manager, lifecycle); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> repository.readResult(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("must not join an ambient transaction"); + + verifyNoInteractions(dsl, manager, lifecycle); + } + + @Test + void activationRejectsAmbientTransactionBeforeOpeningItsOwnerCas() { + var repository = new WorldCanonicalInstanceActivationRepository(dsl, manager, lifecycle); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy( + () -> + repository.activate( + request(), + new WorldCanonicalInstanceActivationService.HeldActivationAuthority() { + public void requireHeld() {} + + public void close() {} + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("must not join an ambient transaction"); + + verifyNoInteractions(dsl, manager, lifecycle); + } + + private static WorldCanonicalInstanceActivation.Request request() { + var lifecycleRequest = mock(WorldCanonicalInstanceLifecycleEvidence.Request.class); + when(lifecycleRequest.canonicalGameInstanceId()) + .thenReturn(UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")); + var preparing = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(preparing.request()).thenReturn(lifecycleRequest); + when(preparing.lifecycleStatus()).thenReturn("PREPARING"); + when(preparing.lifecycleEpoch()).thenReturn(1L); + when(preparing.rowVersion()).thenReturn(0L); + when(preparing.canonicalBytes()) + .thenReturn( + ("{\"request\":{\"readRequestId\":\"11111111-1111-4111-8111-111111111111\"}}") + .getBytes(StandardCharsets.UTF_8)); + return new WorldCanonicalInstanceActivation.Request( + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), preparing); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationServiceTest.java new file mode 100644 index 0000000000..c965455c8e --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationServiceTest.java @@ -0,0 +1,102 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivation; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationService; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldCanonicalInstanceActivationServiceTest { + private static final UUID ACTIVATION_ID = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + + @Test + void defaultVerifierDeniesNewOperationAfterReadOnlyLedgerMiss() { + var repository = mock(WorldCanonicalInstanceActivationRepository.class); + var request = request(); + when(repository.readResult(request)).thenReturn(Optional.empty()); + var service = new WorldCanonicalInstanceActivationService(repository); + + assertThatThrownBy(() -> service.activate(request)) + .isInstanceOf(WorldCanonicalInstanceActivationService.ActivationDeniedException.class) + .hasMessageContaining("no authenticated current source/release"); + + verify(repository).readResult(request); + verify(repository, never()).activate(eq(request), any()); + } + + @Test + void exactPriorResultReplaysWithoutConsultingCurrentAuthority() { + var repository = mock(WorldCanonicalInstanceActivationRepository.class); + var request = request(); + var result = mock(WorldCanonicalInstanceActivation.Result.class); + when(repository.readResult(request)).thenReturn(Optional.of(result)); + var service = + new WorldCanonicalInstanceActivationService( + repository, + ignored -> { + throw new AssertionError("prior immutable result must bypass current authority"); + }); + + assertThat(service.activate(request)).isSameAs(result); + + verify(repository, never()).activate(eq(request), any()); + } + + @Test + void aNewOperationChecksAndHoldsAuthorityOutsideTheOwnerTransaction() { + var repository = mock(WorldCanonicalInstanceActivationRepository.class); + var request = request(); + var result = mock(WorldCanonicalInstanceActivation.Result.class); + var closed = new java.util.concurrent.atomic.AtomicBoolean(); + var service = + new WorldCanonicalInstanceActivationService( + repository, + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return new WorldCanonicalInstanceActivationService.HeldActivationAuthority() { + public void requireHeld() { + assertThat(closed.get()).isFalse(); + } + + public void close() { + closed.set(true); + } + }; + }); + when(repository.readResult(request)).thenReturn(Optional.empty()); + when(repository.activate(eq(request), any())).thenReturn(result); + + assertThat(service.activate(request)).isSameAs(result); + assertThat(closed.get()).isTrue(); + verify(repository).activate(eq(request), any()); + } + + private static WorldCanonicalInstanceActivation.Request request() { + var lifecycleRequest = mock(WorldCanonicalInstanceLifecycleEvidence.Request.class); + when(lifecycleRequest.canonicalGameInstanceId()) + .thenReturn(UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")); + var preparing = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(preparing.request()).thenReturn(lifecycleRequest); + when(preparing.lifecycleStatus()).thenReturn("PREPARING"); + when(preparing.lifecycleEpoch()).thenReturn(1L); + when(preparing.rowVersion()).thenReturn(0L); + when(preparing.canonicalBytes()) + .thenReturn( + ("{\"request\":{\"readRequestId\":\"11111111-1111-4111-8111-111111111111\"}}") + .getBytes(StandardCharsets.UTF_8)); + return new WorldCanonicalInstanceActivation.Request(ACTIVATION_ID, preparing); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationTest.java new file mode 100644 index 0000000000..99b2db4cc0 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationTest.java @@ -0,0 +1,69 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivation; +import org.junit.jupiter.api.Test; + +class WorldCanonicalInstanceActivationTest { + private static final UUID ACTIVATION_ID = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID CANONICAL_INSTANCE_ID = + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + + @Test + void stableOperationIdentityOmitsOnlyLifecycleReadCorrelationAndRetainsOriginalProof() { + var firstEvidence = evidence("11111111-1111-4111-8111-111111111111", "version-a"); + var retryEvidence = evidence("22222222-2222-4222-8222-222222222222", "version-a"); + var changedEvidence = evidence("33333333-3333-4333-8333-333333333333", "version-b"); + var first = new WorldCanonicalInstanceActivation.Request(ACTIVATION_ID, firstEvidence); + var retry = new WorldCanonicalInstanceActivation.Request(ACTIVATION_ID, retryEvidence); + var changed = new WorldCanonicalInstanceActivation.Request(ACTIVATION_ID, changedEvidence); + + assertThat(first.canonicalRequestBytes()).containsExactly(retry.canonicalRequestBytes()); + assertThat(first.requestDigest()).isEqualTo(retry.requestDigest()); + assertThat(first.preparingEvidenceBytes()).isNotEqualTo(retry.preparingEvidenceBytes()); + assertThat(changed.canonicalRequestBytes()).isNotEqualTo(first.canonicalRequestBytes()); + } + + @Test + void requestRejectsNilOperationIdentityAndNonPreparingEvidence() { + assertThatThrownBy( + () -> + new WorldCanonicalInstanceActivation.Request( + new UUID(0L, 0L), evidence("11111111-1111-4111-8111-111111111111", "v"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil"); + var active = evidence("11111111-1111-4111-8111-111111111111", "v"); + when(active.lifecycleStatus()).thenReturn("ACTIVE"); + assertThatThrownBy(() -> new WorldCanonicalInstanceActivation.Request(ACTIVATION_ID, active)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("PREPARING"); + } + + private static WorldCanonicalInstanceLifecycleEvidence evidence(String readId, String version) { + var lifecycleRequest = mock(WorldCanonicalInstanceLifecycleEvidence.Request.class); + when(lifecycleRequest.canonicalGameInstanceId()).thenReturn(CANONICAL_INSTANCE_ID); + var evidence = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(evidence.request()).thenReturn(lifecycleRequest); + when(evidence.lifecycleStatus()).thenReturn("PREPARING"); + when(evidence.lifecycleEpoch()).thenReturn(7L); + when(evidence.rowVersion()).thenReturn(11L); + when(evidence.canonicalBytes()) + .thenReturn( + ("{\"request\":{\"readRequestId\":\"" + + readId + + "\",\"canonicalVersionId\":\"" + + version + + "\",\"canonicalGameInstanceId\":\"" + + CANONICAL_INSTANCE_ID + + "\"}}") + .getBytes(StandardCharsets.UTF_8)); + return evidence; + } +} From 3aa085f3231785149189b4ff62ed0ea217467416 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 06:51:44 +1300 Subject: [PATCH 02/12] feat(publication): retain exact terminal release and World owner handoff --- .github/workflows/ci.yml | 21 +- .../game-design-service/version-control.md | 6 + .../world-management-service/api-contracts.md | 6 +- ...ame-authoring-publishing-and-activation.md | 4 + .../world-runtime-and-movement.md | 4 +- .../v1/publication_terminal_service.proto | 22 + .../GameDesignPublicationTerminalClient.java | 159 ++++ ...GameDesignPublicationTerminalEvidence.java | 517 +++++++++++++ ...DesignPublicationTerminalReadEvidence.java | 140 ++++ ...esignPublicationTerminalReadGrpcCodec.java | 57 ++ ...GameDesignPublicationOperationBinding.java | 67 ++ ...signPublicationTerminalClientMtlsTest.java | 491 ++++++++++++ ...nPublicationTerminalReadGrpcCodecTest.java | 222 ++++++ ...DesignPublicationTerminalEvidenceTest.java | 480 ++++++++++++ .../GameDesignPublicationOperation.java | 55 +- ...eDesignPublicationOperationRepository.java | 75 +- ...ignPublicationTerminalReadGrpcService.java | 110 +++ .../PublicationReleaseContent.java | 65 ++ ...publication_terminal_content_and_epoch.sql | 141 ++++ ...ationOperationPostgresIntegrationTest.java | 722 +++++++++++++++++- ...ublicationTerminalReadGrpcServiceTest.java | 208 +++++ ...DesignPublicationTerminalReadMtlsTest.java | 306 ++++++++ ...anonicalInstancePreparationRepository.java | 134 ++++ ...ldCanonicalInstancePreparationService.java | 25 +- .../tenant/WorldPublicationTerminal.java | 110 +++ ...orldPublicationTerminalClientVerifier.java | 60 ++ .../WorldPublicationTerminalRepository.java | 379 +++++++++ .../WorldPublicationTerminalService.java | 90 +++ ...44__world_publication_terminal_handoff.sql | 354 +++++++++ ...aphApplicationPostgresIntegrationTest.java | 386 +++++++++- ...WorldCanonicalInstancePreparationTest.java | 2 +- .../WorldPublicationTerminalServiceTest.java | 22 + 32 files changed, 5349 insertions(+), 91 deletions(-) create mode 100644 protos/game-design/v1/publication_terminal_service.proto create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBinding.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClientMtlsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadGrpcService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublicationReleaseContent.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V51__publication_terminal_content_and_epoch.sql create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadGrpcServiceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadMtlsTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminal.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalClientVerifier.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalService.java create mode 100644 services/world-management-service/src/main/resources/db/migration/V44__world_publication_terminal_handoff.sql create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalServiceTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0108f8dd02..cfd8e97357 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2248,6 +2248,9 @@ 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#publishedTerminalUsesExactOwnerEvidenceRetriesAndRejectsChangedReleaseContent()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#rawTerminalReceiptCannotCommitWithoutMatchingOwnerPhaseCas()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#onlyPositiveNoPublicationEvidenceCanSealWorldAsAbortedAndCannotPrepare()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#lifecycleReadFollowsCurrentWorldEpochAndReturnsExactCanonicalServiceEcho()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#canonicalActivationCommitsOneOwnerCasAndReplaysItsImmutableResultAfterLaterLifecycleMove()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#canonicalActivationStoresStaleFailedOutcomeAndFreshLifecycleReadRemainsCurrent()' \ @@ -2320,11 +2323,19 @@ 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#authenticatedTerminalReadDispatchesActualStoredPublishedAndNoPublicationEvidence()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#physicalMtlsTerminalReadRecoversActualPublishedAndNoPublicationOwnerSealsAndRejectsWrongPeers(Path)' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#authenticatedTerminalReadReturnsUnknownOnlyForAbsentOrPendingOperation()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#retainedV50TerminalReadFailsPreconditionWithoutBackfillingEvidenceOrEpoch()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#noPublicationReceiptReplaysAfterLostResponseAndExcludesDelayedFinalizerAndRawInsert()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#terminalEvidenceKeepsOriginalCommittedEpochAfterLaterVersionTransition()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#terminalExtensionRefusesRawEpochDigestBytesAndReleaseContentSubstitution()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#originalSealRejectsForgedCommittedEpochAndPreservesPendingOwnerRows()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationPostgresIntegrationTest#publicationSealEpochMustRemainTheActualVersionEpochThroughCommit()' \ + --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 diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 8c59373d3f..c528874d55 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -70,6 +70,12 @@ The complete publication operation is distinct from the [publication digest read 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. +The closed `game-design-publication-terminal/v1` evidence retains the original operation bytes, typed `PUBLISHED` or `NO_PUBLICATION` outcome and, only for `PUBLISHED`, complete immutable release content and the positive Version epoch captured after the actual publication transition in the same owner seal transaction. Historical readback compares the original captured content with the immutable release and preserves the committed publication epoch even after a legitimate later Version transition; it cannot reconstruct that epoch from mutable current Version state. `NO_PUBLICATION` has neither release content nor a publication epoch. Retained older results without the original captured extension remain non-authorizing for this handoff and are not backfilled. + +`publishedReleaseBundleDigest` is the SHA-256 content digest under `game-design-published-release-bundle/v1`, with lowercase `sha256:` representation and decimal byte-length framing. Its fixed field order is domain, canonical tenant UUID, canonical Version UUID, bundle reference, version number, bundle attestation schema `v2`, workflow, manifest hash/schema, artifacts, required asset keys, five ordered participant attestations, command definitions, generation revision, unchanged complete World start evidence, `scriptOnly=false`, and absent script-patch identity. Arrays encode an explicit canonical decimal count and preserve each entry's supplied order; artifacts and participants are individually framed entries, and nullable fields encode explicit boolean presence and a framed value, including absent versus present-empty error fields. Every artifact field and participant field, including optional base-Version, ability-schema digest, error code and error message, participates. Required owner, exact selected scope/commit/digest/schema, World checkpoint and complete manifest/object checks remain mandatory. Only private SQL row identity/tenant/version aliases and `publishedAt` metadata are excluded. Launch descriptor and release-attestation evidence digests are separate domains and cannot substitute for this content digest. Terminal evidence uses the original operation's four-byte length framing in order domain, operation, outcome, then complete content and canonical decimal committed epoch for `PUBLISHED`; outcome-inapplicable fields are forbidden. Neither canonical decoding nor code-only owner readback authenticates cross-service delivery. + +`GameDesignPublicationTerminalReadService.ReadGameDesignPublicationTerminal` is a separate read-only owner service for exact immutable operation recovery. It authenticates only the exact same-namespace Account or World Management SPIFFE workload before decoding or reading storage and rejects authenticated end-user context. Its closed schema-1 request carries the configured namespace, distinct non-nil read correlation UUID and complete unchanged original publication operation bytes; the response echoes that complete request. Only an absent operation or still-`PENDING` operation returns explicit `UNKNOWN` with no terminal payload. `PUBLISHED` and `NO_PUBLICATION` carry the unchanged stored terminal bytes and exact outcome/operation binding. Retained V50 terminal history without the captured extension returns `FAILED_PRECONDITION`, never inferred absence or manufactured evidence. Reads use an independent read-only `REPEATABLE_READ` owner boundary. A concrete file-backed, reloading mTLS client validates the exact Game Design peer before releasing request metadata/body and checks peer and complete echoed response afterward. This standalone adapter/client requires explicit composition and has no runtime registration; `UNKNOWN`, transport success or decoding alone cannot settle a publication fence or enable publication/activation. + **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/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index aad88182fb..2e7227e059 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -18,8 +18,8 @@ This API contract is target-state canonical; implementation coverage is partial - `ListRoomOccupants` – **target state:** returns the authoritative typed occupant list for actors in a room, scoped by `RoomInstanceRef`. The current LOOK path is fixture-backed and has no World-owned location/occupancy persistence or authoritative read/write surface; it must not be treated as gameplay occupancy truth. - `ApplyRoomAmbientStatePatch` – applies a typed ambient fact patch to the target runtime scope under expected epoch/version preconditions and an operation/aggregate/request-digest-bound guard derived from the root `EffectId`; matching replay returns the durable prior result and a conflicting identity or payload fails closed. - `GetDraftDesignDigest` – returns the publish-gating digest for Draft world templates using the typed scope request `GetDraftDesignDigestRequest { tenantId, scope: oneof { versionId, scriptPatchVersion } }`. World Management supports `versionId` scope only and must return `UNSUPPORTED_SCOPE` for `scriptPatchVersion`. -- `BeginVersionPublicationFreeze` – **Target state:** starts or exactly replays the durable WMS owner freeze for one `(tenantId, versionId)` publication request and returns the request/fence/epoch/digest checkpoint acknowledgement defined below. It is not present in the current proto or implementation. -- `CompleteVersionPublication` – **Target state:** exactly replays or terminalizes the same WMS freeze with a `PUBLISHED` or `ABORTED` outcome and matching bundle/digest evidence. It is not present in the current proto or implementation. +- `BeginVersionPublicationFreeze` – **Target state:** starts or exactly replays the durable WMS owner freeze for one `(tenantId, versionId)` publication request and returns the request/fence/epoch/digest checkpoint acknowledgement defined below. The internal V25 owner-lock persistence exists, but there is no public proto/RPC or authenticated freeze receiver. +- `CompleteVersionPublication` – **Target state:** exactly replays or terminalizes the same WMS freeze with a `PUBLISHED` or `ABORTED` outcome and matching bundle/digest evidence. V44 adds an unregistered internal owner operation and immutable terminal journal behind an explicit verifier; there is no public proto/RPC or production service composition, and the default verifier denies. - `ValidateWorldUpgradeMappings` – validates world-owned durable references and approved remap sets for replacement-instance cutover to a target `(tenantId, versionId)`. - `PrepareWorldInstance` – creates or reuses the canonical `PREPARING` world lifecycle row only after verifying and retaining the complete resolved launch binding (the source-bound descriptor and its separately authenticated full release attestation), and materializes first-cut instance topology rows without admitting gameplay yet. - `ActivatePreparedWorldInstance` – performs the fenced `PREPARING -> ACTIVE` lifecycle transition after Game Session has finished local start-up work for the same `gameInstanceId`. @@ -91,7 +91,7 @@ Account's [authorization-fence contract](../account-service/api-contracts.md#acc ### Publication freeze and terminal handoff (target state) -The publication-freeze operations remain unavailable target contract surfaces. The internal owner-lock persistence prerequisite is not an authenticated freeze producer or terminal handoff; the [World implementation tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status) records its current code and proof limits. No current caller may infer a freeze, publication, or terminal owner result from a digest, a remote `GetVersionState` read, or a Temporal run identity. +The publication-freeze operations remain unavailable target contract surfaces. V25 supplies internal owner-lock persistence, while V44 adds an unregistered, default-denied terminal receiver that accepts only the exact terminal result returned by its explicitly supplied Game Design verifier and records an immutable owner result. Neither is a public RPC or registered production composition; the Game Design terminal read and the World component fixtures do not establish live cross-service production. The [World implementation tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status) records current code and proof limits. No current caller may infer a freeze, publication, or terminal owner result from a digest, a remote `GetVersionState` read, or a Temporal run identity. `BeginVersionPublicationFreeze` accepts exactly: 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 7b6852fb34..e3687a69bf 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,10 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The unpublished terminal-read candidate adds a separate unregistered Game Design owner RPC and concrete reloading file-backed mTLS client for Account/World exact operation recovery. Closed request/response codecs preserve original operation and stored terminal bytes, explicit `UNKNOWN` is limited to absent/pending operations, and retained V50 terminal history without the captured extension fails precondition. Physical socket definitions exercise authenticated Game Design server pre-send denial and Account/World receiver identity; their owner source is an explicitly isolated double and they are transport-only proof. Additional PostgreSQL definitions dispatch the actual handler through the independent owner service to genuine stored `PUBLISHED`/`NO_PUBLICATION` results, absent/pending results and retained V50-to-V51 history without backfill; their upstream creator/source/World authority remains isolated. No validation has run for this candidate: formatting, proto generation, compilation, physical tests, jOOQ and PostgreSQL execution remain integration obligations. The standalone components do not register or enable public publication, authenticated normal World freeze/terminal orchestration, Account settlement or runtime activation. + +The forward V51 candidate extends the actual Game Design publication seal with closed terminal evidence, the complete release content digest and the original committed publication Version epoch. Existing V50 receipt bytes and retained results stay unchanged, with no historical epoch or evidence backfill. The shared operation adapter keeps the exact original authorization/freeze bytes. Readback checks the captured complete content against the immutable release while retaining the original epoch after later Version movement. Codec vectors and PostgreSQL definitions cover lossless content, typed no-publication, raw terminal substitution, rollback and later lifecycle movement. Local formatting, compilation, jOOQ generation, PostgreSQL migration execution and focused tests are deferred to integration and are not claimed as passed. Authenticated World delivery, Account currentness, complete live five-owner publication and runtime activation remain open under the [canonical publication handoff](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff-target-state). + 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. 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 9f3b726d6c..9575481c60 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,13 +6,15 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +The V44 World publication-terminal candidate adds an unregistered, default-denied owner operation with immutable exact-retry PUBLISHED/ABORTED readback. Its explicit verifier consumes the separate Game Design terminal read; the owner transaction checks and seals the original freeze, source, Account/APPLIED and selector evidence. Fresh V35 preparation now requires that exact retained PUBLISHED terminal and original frozen capture rather than FROZEN alone; it does not capture new source after terminalization. New PostgreSQL definitions exercise the owner transitions and preparation using explicitly isolated synthetic upstream evidence. They are not executed proof of the real Game Design producer, live mTLS/service composition, or production authorization, and validation for this unpublished batch remains pending. + The local World delivery correction behind #3029 adds an unregistered, default-denied V43 canonical activation operation and an immutable exact-retry result. The owner transaction independently reconstructs the same complete association/materialization evidence, locks the actual lifecycle row and commits its `PREPARING -> ACTIVE` CAS with the result; raw SQL cannot commit a success ledger without that CAS or activate the canonical row through the legacy numeric writer. New definitions cover stale outcomes, exact concurrent retry, lost held-authority rollback, self-consistent forged evidence rejected against independent owner rows, and historical recovery after later lifecycle movement. Validation and PostgreSQL execution for this unpublished batch remain pending; these definitions and an explicitly isolated verifier do not supply authenticated live activation, placement, region preparation or admission. The [World API contract](../../architecture/microservices/world-management-service/api-contracts.md#canonical-instance-activation-and-lifecycle-readback) owns the operation and historical-versus-current evidence distinction. Fresh Account lifecycle/serving authority remains a concrete missing producer, distinct from original Draft and publication authorization. Account's existing fresh-control bootstrap capture supplies committed exact-tenant `tenantAdmin` source evidence, but does not authenticate a lifecycle caller or produce fresh serving entitlement, billing/quota classification or capacity commitment. The gameplay-only numeric entitlement DTO and source-lock primitives cannot supply those missing facts. No `CommitTenantCapacityAdmission`, lifecycle participant hold, capacity usage/reservation ledger or complete canonical fresh-tenant billing source exists in this candidate; production activation therefore remains denied under [Versioning and Runtime](../../architecture/system-architecture-versioning-runtime.md#serving-entitlement-and-shutdown-gates). A clearly labeled isolated upstream authority composition can exercise real owner transitions for bounded fixture proof, but cannot count as any of those production producers or authorize player admission. 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. +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. V44 now requires fresh canonical materialization to consume the exact retained PUBLISHED terminal and original capture; tests for this continuation use isolated synthetic upstream evidence and remain pending validation. The live authenticated Game Design terminal producer/service composition, complete protected current authorization and 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. diff --git a/protos/game-design/v1/publication_terminal_service.proto b/protos/game-design/v1/publication_terminal_service.proto new file mode 100644 index 0000000000..c071aad909 --- /dev/null +++ b/protos/game-design/v1/publication_terminal_service.proto @@ -0,0 +1,22 @@ +syntax = "proto3"; + +package game_design.v1; + +option java_package = "net.firedevops.firemud.gamedesign.v1"; +option java_multiple_files = true; + +// Explicit composition only; no runtime publication or lifecycle authority is enabled. +service GameDesignPublicationTerminalReadService { + rpc ReadGameDesignPublicationTerminal(ReadGameDesignPublicationTerminalRequest) + returns (ReadGameDesignPublicationTerminalResponse); +} + +message ReadGameDesignPublicationTerminalRequest { + // Closed schema-1 namespace/read UUID/complete original operation carrier. + bytes canonical_request_bytes = 1; +} + +message ReadGameDesignPublicationTerminalResponse { + // Exact request echo plus UNKNOWN or the unchanged immutable terminal evidence. + bytes canonical_response_bytes = 1; +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java new file mode 100644 index 0000000000..a562ded108 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.common.gamedesign; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamedesign.v1.GameDesignPublicationTerminalReadServiceGrpc; + +/** Explicit mTLS client for the exact Game Design publication terminal read. */ +public final class GameDesignPublicationTerminalClient + extends AbstractReloadingBlockingGrpcClient< + GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GameDesignPublicationTerminalClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GameDesignPublicationTerminalClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when the owning Account or World service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Game Design publication terminal client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Game Design publication terminal client has no gRPC stub"); + } + initialized = true; + } + + /** + * Reads and validates Game Design-owned publication terminal evidence for this exact canonical + * request. + */ + public GameDesignPublicationTerminalReadEvidence.ReadResult read( + GameDesignPublicationTerminalReadEvidence.ReadRequest request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Game Design publication terminal request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readGameDesignPublicationTerminal( + GameDesignPublicationTerminalReadGrpcCodec.toRequest(request)); + try { + return GameDesignPublicationTerminalReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Design returned invalid publication terminal read evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + return GameDesignPublicationTerminalReadServiceGrpc.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 GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Game Design publication terminal client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Game Design publication terminal 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( + "Game Design publication terminal read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Game Design publication terminal read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Game Design publication terminal read " + label + " must be a readable file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Game Design publication terminal read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java new file mode 100644 index 0000000000..f83405fcb5 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java @@ -0,0 +1,517 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; + +/** Immutable original owner result. Decoding establishes integrity, never transport authority. */ +public final class GameDesignPublicationTerminalEvidence { + public static final String SCHEMA = "game-design-publication-terminal/v1"; + public static final String RELEASE_SCHEMA = "game-design-published-release-bundle/v1"; + + public enum Outcome { + PUBLISHED, + NO_PUBLICATION + } + + /** Lossless participant content, including the presence of nullable publication result fields. */ + public record Participant( + String participantKey, + String scopeValue, + Long baseVersionId, + String appliedCommitId, + String contentDigest, + int digestSchemaVersion, + String abilitySchemaDigest, + String errorCode, + String errorMessage) { + public Participant { + new AuthoredWorldReleaseAttestationEvidence.Participant( + participantKey, + scopeValue, + baseVersionId != null, + baseVersionId, + appliedCommitId, + contentDigest, + digestSchemaVersion, + abilitySchemaDigest != null, + abilitySchemaDigest); + if (errorCode != null && !errorCode.isEmpty()) { + throw new IllegalArgumentException("Published participant cannot carry an error"); + } + if (errorMessage != null) utf8(errorMessage); + } + } + + /** Complete full-Version content; private SQL aliases and publishedAt are excluded. */ + public record ReleaseContent( + UUID canonicalTenantId, + UUID canonicalVersionId, + String publishedReleaseBundleRef, + int versionNumber, + String attestationSchemaVersion, + String publishWorkflowId, + String manifestHash, + int manifestSchemaVersion, + List artifactDigests, + List requiredManifestAssetKeys, + List participantDigests, + List commandDefinitions, + String generationConfigRevision, + WorldPublishedStartLocationEvidence worldStartLocationEvidence) { + public ReleaseContent { + uuid(canonicalTenantId); + uuid(canonicalVersionId); + text(publishedReleaseBundleRef); + text(publishWorkflowId); + text(generationConfigRevision); + if (versionNumber <= 0 + || !"v2".equals(attestationSchemaVersion) + || manifestSchemaVersion != 1) { + throw new IllegalArgumentException("Complete full-Version bundle/v2 required"); + } + digest(manifestHash); + artifactDigests = List.copyOf(artifactDigests); + requiredManifestAssetKeys = List.copyOf(requiredManifestAssetKeys); + participantDigests = List.copyOf(participantDigests); + commandDefinitions = List.copyOf(commandDefinitions); + commandDefinitions.forEach(GameDesignPublicationTerminalEvidence::utf8); + worldStartLocationEvidence = + WorldPublishedStartLocationEvidence.fromStored( + Objects.requireNonNull(worldStartLocationEvidence).canonicalBytes()); + var selected = worldStartLocationEvidence.request(); + if (!canonicalTenantId.equals(selected.canonicalTenantId()) + || !canonicalVersionId.equals(selected.canonicalVersionId()) + || !publishWorkflowId.equals(selected.publishWorkflowId())) { + throw new IllegalArgumentException("Release identity differs from World checkpoint"); + } + var owners = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder(); + if (participantDigests.size() != owners.size()) { + throw new IllegalArgumentException("Exactly five participant owners required"); + } + for (int i = 0; i < owners.size(); i++) { + var p = participantDigests.get(i); + if (!owners.get(i).equals(p.participantKey()) + || p.digestSchemaVersion() + != AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + p.participantKey()) + || p.baseVersionId() != null + || !selected.appliedCommitId().equals(p.appliedCommitId()) + || !p.scopeValue().matches("[1-9][0-9]*") + || new BigInteger(p.scopeValue()).compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0 + || ((p.abilitySchemaDigest() != null) != "GAME_LOGIC".equals(p.participantKey()))) { + throw new IllegalArgumentException("Incomplete or changed required participant proof"); + } + } + var world = participantDigests.getFirst(); + if (!world.contentDigest().equals(selected.contentDigest()) + || world.digestSchemaVersion() != selected.digestSchemaVersion()) { + throw new IllegalArgumentException("World participant differs from frozen checkpoint"); + } + ordered(requiredManifestAssetKeys); + ordered( + artifactDigests.stream() + .map(AuthoredWorldReleaseAttestationEvidence.Artifact::usageKey) + .toList()); + if (!artifactDigests.stream() + .map(AuthoredWorldReleaseAttestationEvidence.Artifact::usageKey) + .toList() + .containsAll(requiredManifestAssetKeys)) { + throw new IllegalArgumentException( + "Every required asset must have actual-byte artifact proof"); + } + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + segment(out, RELEASE_SCHEMA); + segment(out, canonicalTenantId.toString()); + segment(out, canonicalVersionId.toString()); + segment(out, publishedReleaseBundleRef); + segment(out, Integer.toString(versionNumber)); + segment(out, attestationSchemaVersion); + segment(out, publishWorkflowId); + segment(out, manifestHash); + segment(out, Integer.toString(manifestSchemaVersion)); + segment(out, Integer.toString(artifactDigests.size())); + for (var a : artifactDigests) { + var entry = new ByteArrayOutputStream(); + segment(entry, a.usageKey()); + segment(entry, a.artifactKind()); + segment(entry, a.immutableObjectKey()); + segment(entry, a.contentDigest()); + segment(entry, a.contentType()); + segment(entry, Integer.toString(a.artifactSchemaVersion())); + segment(out, entry.toByteArray()); + } + strings(out, requiredManifestAssetKeys); + segment(out, Integer.toString(participantDigests.size())); + for (var p : participantDigests) { + var entry = new ByteArrayOutputStream(); + segment(entry, p.participantKey()); + segment(entry, p.scopeValue()); + optional(entry, p.baseVersionId() == null ? null : p.baseVersionId().toString()); + segment(entry, p.appliedCommitId()); + segment(entry, p.contentDigest()); + segment(entry, Integer.toString(p.digestSchemaVersion())); + optional(entry, p.abilitySchemaDigest()); + optional(entry, p.errorCode()); + optional(entry, p.errorMessage()); + segment(out, entry.toByteArray()); + } + strings(out, commandDefinitions); + segment(out, generationConfigRevision); + segment(out, worldStartLocationEvidence.canonicalBytes()); + // Full versions cannot carry a script patch; explicit presence is still part of content. + segment(out, "false"); + optional(out, null); + return out.toByteArray(); + } + + public String contentDigest() { + return sha256(canonicalBytes()); + } + + public static ReleaseContent fromStored(byte[] bytes) { + var r = new Reader(bytes); + r.expect(RELEASE_SCHEMA); + UUID tenant = UUID.fromString(r.text()); + UUID version = UUID.fromString(r.text()); + String ref = r.text(); + int number = r.positiveInt(); + String schema = r.text(); + String workflow = r.text(); + String manifest = r.text(); + int manifestSchema = r.positiveInt(); + var artifacts = new ArrayList(); + for (int remaining = r.count(); remaining > 0; remaining--) { + var a = new Reader(r.bytes()); + artifacts.add( + new AuthoredWorldReleaseAttestationEvidence.Artifact( + a.text(), a.text(), a.text(), a.text(), a.text(), a.positiveInt())); + a.end(); + } + List required = r.strings(); + var participants = new ArrayList(); + for (int remaining = r.count(); remaining > 0; remaining--) { + var p = new Reader(r.bytes()); + String owner = p.text(); + String scope = p.text(); + String base = p.optional(); + participants.add( + new Participant( + owner, + scope, + base == null ? null : positiveLong(base), + p.text(), + p.text(), + p.positiveInt(), + p.optional(), + p.optional(), + p.optional())); + p.end(); + } + List commands = r.strings(); + String generation = r.text(); + var world = WorldPublishedStartLocationEvidence.fromStored(r.bytes()); + r.expect("false"); + if (r.optional() != null) throw new IllegalArgumentException("Full version has script patch"); + r.end(); + var result = + new ReleaseContent( + tenant, + version, + ref, + number, + schema, + workflow, + manifest, + manifestSchema, + artifacts, + required, + participants, + commands, + generation, + world); + if (!Arrays.equals(bytes, result.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical release content"); + return result; + } + } + + private final GameDesignPublicationOperationBinding operation; + private final Outcome outcome; + private final ReleaseContent release; + private final Long epoch; + + public GameDesignPublicationTerminalEvidence( + byte[] operationBytes, + Outcome outcome, + ReleaseContent release, + Long publicationVersionStateEpoch) { + this.operation = GameDesignPublicationOperationBinding.fromStored(operationBytes); + this.outcome = Objects.requireNonNull(outcome); + if ((outcome == Outcome.PUBLISHED) != (release != null && publicationVersionStateEpoch != null) + || (outcome == Outcome.NO_PUBLICATION + && (release != null || publicationVersionStateEpoch != null))) { + throw new IllegalArgumentException("Outcome-inapplicable release or epoch"); + } + this.release = release == null ? null : ReleaseContent.fromStored(release.canonicalBytes()); + this.epoch = publicationVersionStateEpoch; + if (release != null) { + if (epoch <= 0 + || epoch != Math.addExact(operation.world().request().versionStateEpoch(), 1L) + || !Arrays.equals( + release.worldStartLocationEvidence().canonicalBytes(), + operation.world().canonicalBytes())) { + throw new IllegalArgumentException( + "Terminal release differs from original publication operation"); + } + String scope = + Long.toString(operation.account().input().selection().target().gameDesignVersionRowId()); + if (release.participantDigests().stream().anyMatch(p -> !scope.equals(p.scopeValue()))) { + throw new IllegalArgumentException("Participant scope differs from selected owner Version"); + } + } + } + + public Outcome outcome() { + return outcome; + } + + public byte[] operationBytes() { + return operation.canonicalBytes(); + } + + public WorldPublishedStartLocationEvidence worldEvidence() { + return operation.world(); + } + + public String publishedReleaseBundleRef() { + return requireRelease().publishedReleaseBundleRef(); + } + + public String publishedReleaseBundleDigest() { + return requireRelease().contentDigest(); + } + + public long publicationVersionStateEpoch() { + requireRelease(); + return epoch; + } + + public ReleaseContent releaseContent() { + return requireRelease(); + } + + private ReleaseContent requireRelease() { + if (release == null) + throw new IllegalStateException( + "NO_PUBLICATION has no release or committed publication epoch"); + return release; + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, operationBytes()); + DraftAuthorizationFenceBinding.frame(out, outcome.name()); + if (release != null) { + DraftAuthorizationFenceBinding.frame(out, release.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, Long.toString(epoch)); + } + return out.toByteArray(); + } + + public static GameDesignPublicationTerminalEvidence fromStored(byte[] bytes) { + var r = new DraftAuthorizationFenceBinding.FrameReader(bytes); + r.expect(SCHEMA); + byte[] operation = r.bytes(); + Outcome outcome = Outcome.valueOf(r.text()); + ReleaseContent release = + outcome == Outcome.PUBLISHED ? ReleaseContent.fromStored(r.bytes()) : null; + Long epoch = outcome == Outcome.PUBLISHED ? positiveLong(r.text()) : null; + r.requireEnd(); + var result = new GameDesignPublicationTerminalEvidence(operation, outcome, release, epoch); + if (!Arrays.equals(bytes, result.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical terminal evidence"); + return result; + } + + private static void uuid(UUID id) { + if (id == null || id.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException("Non-nil UUID required"); + } + + private static void text(String s) { + if (s == null || s.isBlank() || s.codePoints().anyMatch(Character::isISOControl)) + throw new IllegalArgumentException("Canonical nonblank text required"); + utf8(s); + } + + private static void digest(String s) { + if (s == null || !s.matches("sha256:[0-9a-f]{64}")) + throw new IllegalArgumentException("SHA256 digest required"); + } + + private static long positiveLong(String s) { + if (!s.matches("[1-9][0-9]*")) + throw new IllegalArgumentException("Canonical positive decimal required"); + try { + return Long.parseLong(s); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("Counter exceeds owner range", e); + } + } + + private static byte[] utf8(String s) { + try { + var b = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .encode(java.nio.CharBuffer.wrap(Objects.requireNonNull(s))); + var bytes = new byte[b.remaining()]; + b.get(bytes); + return bytes; + } catch (CharacterCodingException e) { + throw new IllegalArgumentException("Invalid UTF-8", e); + } + } + + private static void ordered(List values) { + String prior = null; + for (String value : values) { + text(value); + if (prior != null && Arrays.compareUnsigned(utf8(prior), utf8(value)) >= 0) + throw new IllegalArgumentException("Array must be unique and unsigned UTF-8 ordered"); + prior = value; + } + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + private static void segment(ByteArrayOutputStream out, String value) { + segment(out, utf8(value)); + } + + private static void segment(ByteArrayOutputStream out, byte[] bytes) { + out.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + out.write(':'); + out.writeBytes(bytes); + } + + private static void optional(ByteArrayOutputStream out, String value) { + segment(out, value == null ? "false" : "true"); + segment(out, value == null ? "" : value); + } + + private static void strings(ByteArrayOutputStream out, List values) { + segment(out, Integer.toString(values.size())); + values.forEach(v -> segment(out, v)); + } + + private static final class Reader { + private final byte[] bytes; + private int offset; + + Reader(byte[] bytes) { + this.bytes = Objects.requireNonNull(bytes).clone(); + } + + byte[] bytes() { + int start = offset; + while (offset < bytes.length && bytes[offset] >= '0' && bytes[offset] <= '9') offset++; + if (start == offset || offset == bytes.length || bytes[offset] != ':') + throw new IllegalArgumentException("Malformed byte-length frame"); + String decimal = new String(bytes, start, offset - start, StandardCharsets.US_ASCII); + if (!decimal.matches("0|[1-9][0-9]*")) + throw new IllegalArgumentException("Noncanonical frame length"); + int length; + try { + length = new BigInteger(decimal).intValueExact(); + } catch (ArithmeticException e) { + throw new IllegalArgumentException("Frame too large", e); + } + offset++; + if (length > bytes.length - offset) throw new IllegalArgumentException("Truncated frame"); + byte[] value = Arrays.copyOfRange(bytes, offset, offset + length); + offset += length; + return value; + } + + String text() { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes())) + .toString(); + } catch (CharacterCodingException e) { + throw new IllegalArgumentException("Invalid UTF-8", e); + } + } + + void expect(String value) { + if (!value.equals(text())) throw new IllegalArgumentException("Unexpected canonical field"); + } + + int positiveInt() { + return Math.toIntExact(positiveLong(text())); + } + + int count() { + String s = text(); + if (!s.matches("0|[1-9][0-9]*")) + throw new IllegalArgumentException("Noncanonical array count"); + int n; + try { + n = new BigInteger(s).intValueExact(); + } catch (ArithmeticException e) { + throw new IllegalArgumentException("Array too large", e); + } + if (n > (bytes.length - offset) / 2) throw new IllegalArgumentException("Incomplete array"); + return n; + } + + String optional() { + String present = text(); + String value = text(); + if ("true".equals(present)) return value; + if (!"false".equals(present) || !value.isEmpty()) + throw new IllegalArgumentException("Malformed optional field"); + return null; + } + + List strings() { + var result = new ArrayList(); + for (int n = count(); n > 0; n--) result.add(text()); + return result; + } + + void end() { + if (offset != bytes.length) throw new IllegalArgumentException("Trailing fields"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadEvidence.java new file mode 100644 index 0000000000..d88b0fdb69 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadEvidence.java @@ -0,0 +1,140 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; + +/** + * Closed immutable read correlation. Integrity alone grants no settlement or workload authority. + */ +public final class GameDesignPublicationTerminalReadEvidence { + private GameDesignPublicationTerminalReadEvidence() {} + + public enum Status { + UNKNOWN, + PUBLISHED, + NO_PUBLICATION + } + + public record ReadRequest( + int schemaVersion, String targetNamespace, UUID readRequestId, byte[] operationBytes) { + public static final int SCHEMA_VERSION = 1; + public static final String SCHEMA = "game-design-publication-terminal-read-request/v1"; + + public ReadRequest { + if (schemaVersion != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || readRequestId == null + || readRequestId.equals(new UUID(0, 0))) { + throw new IllegalArgumentException( + "Closed schema-1 namespace and non-nil read UUID required"); + } + operationBytes = + GameDesignPublicationOperationBinding.fromStored(operationBytes).canonicalBytes(); + var operation = GameDesignPublicationOperationBinding.fromStored(operationBytes); + if (!targetNamespace.equals(operation.world().request().targetNamespace())) { + throw new IllegalArgumentException("Read namespace differs from original World operation"); + } + if (readRequestId.equals(operation.account().operationId()) + || readRequestId.equals(operation.account().fenceId()) + || readRequestId.equals(operation.world().request().intakeRequestId()) + || readRequestId.equals(operation.world().request().publicationFence()) + || readRequestId.toString().equals(operation.world().request().publicationRequestId()) + || readRequestId.equals( + operation.account().input().selection().intent().selectedCommitRequestId()) + || readRequestId.equals( + operation.account().input().selection().intent().selectedCommitId())) { + throw new IllegalArgumentException( + "Terminal read UUID must be distinct from original operation identity"); + } + } + + public static ReadRequest create(String namespace, byte[] operationBytes) { + return new ReadRequest(SCHEMA_VERSION, namespace, UUID.randomUUID(), operationBytes); + } + + @Override + public byte[] operationBytes() { + return operationBytes.clone(); + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, Integer.toString(schemaVersion)); + DraftAuthorizationFenceBinding.frame(out, targetNamespace); + DraftAuthorizationFenceBinding.frame(out, readRequestId.toString()); + DraftAuthorizationFenceBinding.frame(out, operationBytes); + return out.toByteArray(); + } + + public static ReadRequest fromStored(byte[] bytes) { + var r = new DraftAuthorizationFenceBinding.FrameReader(bytes); + r.expect(SCHEMA); + r.expect("1"); + var result = new ReadRequest(1, r.text(), UUID.fromString(r.text()), r.bytes()); + r.requireEnd(); + if (!Arrays.equals(bytes, result.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical terminal read request"); + return result; + } + } + + public record ReadResult( + ReadRequest request, + Status status, + Optional terminalEvidence) { + public static final String SCHEMA = "game-design-publication-terminal-read-response/v1"; + + public ReadResult { + request = ReadRequest.fromStored(Objects.requireNonNull(request).canonicalBytes()); + Objects.requireNonNull(status); + Objects.requireNonNull(terminalEvidence); + if ((status == Status.UNKNOWN) != terminalEvidence.isEmpty()) { + throw new IllegalArgumentException("UNKNOWN alone omits terminal evidence"); + } + if (terminalEvidence.isPresent()) { + var terminal = + GameDesignPublicationTerminalEvidence.fromStored( + terminalEvidence.orElseThrow().canonicalBytes()); + if (!terminal.outcome().name().equals(status.name()) + || !Arrays.equals(request.operationBytes(), terminal.operationBytes())) { + throw new IllegalArgumentException( + "Terminal result differs from exact original read operation or outcome"); + } + terminalEvidence = Optional.of(terminal); + } + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, request.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, status.name()); + terminalEvidence.ifPresent( + t -> DraftAuthorizationFenceBinding.frame(out, t.canonicalBytes())); + return out.toByteArray(); + } + + public static ReadResult fromStored(byte[] bytes) { + var r = new DraftAuthorizationFenceBinding.FrameReader(bytes); + r.expect(SCHEMA); + var request = ReadRequest.fromStored(r.bytes()); + var status = Status.valueOf(r.text()); + var terminal = + status == Status.UNKNOWN + ? Optional.empty() + : Optional.of(GameDesignPublicationTerminalEvidence.fromStored(r.bytes())); + r.requireEnd(); + var result = new ReadResult(request, status, terminal); + if (!Arrays.equals(bytes, result.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical terminal read response"); + return result; + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadGrpcCodec.java new file mode 100644 index 0000000000..4cb2c9abbc --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadGrpcCodec.java @@ -0,0 +1,57 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.google.protobuf.ByteString; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadResult; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalRequest; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalResponse; + +/** Closed wire mapping; receiver authentication must precede decoding. */ +public final class GameDesignPublicationTerminalReadGrpcCodec { + private GameDesignPublicationTerminalReadGrpcCodec() {} + + public static ReadGameDesignPublicationTerminalRequest toRequest(ReadRequest request) { + return ReadGameDesignPublicationTerminalRequest.newBuilder() + .setCanonicalRequestBytes( + ByteString.copyFrom(Objects.requireNonNull(request).canonicalBytes())) + .build(); + } + + public static ReadRequest fromRequest(ReadGameDesignPublicationTerminalRequest request) { + if (!Objects.requireNonNull(request).getUnknownFields().asMap().isEmpty() + || request.getCanonicalRequestBytes().isEmpty()) { + throw new IllegalArgumentException("Closed complete terminal read request required"); + } + return ReadRequest.fromStored(request.getCanonicalRequestBytes().toByteArray()); + } + + public static ReadGameDesignPublicationTerminalResponse toResponse( + ReadRequest request, ReadResult result) { + exact(request, result); + return ReadGameDesignPublicationTerminalResponse.newBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(result.canonicalBytes())) + .build(); + } + + public static ReadResult fromResponse( + ReadRequest request, ReadGameDesignPublicationTerminalResponse response) { + if (!Objects.requireNonNull(response).getUnknownFields().asMap().isEmpty() + || response.getCanonicalResponseBytes().isEmpty()) { + throw new IllegalArgumentException("Closed complete terminal read response required"); + } + var result = ReadResult.fromStored(response.getCanonicalResponseBytes().toByteArray()); + exact(request, result); + return result; + } + + private static void exact(ReadRequest request, ReadResult result) { + if (!Arrays.equals( + Objects.requireNonNull(request).canonicalBytes(), + Objects.requireNonNull(result).request().canonicalBytes())) { + throw new IllegalArgumentException( + "Terminal read response changed the complete request echo"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBinding.java new file mode 100644 index 0000000000..0d664c9a04 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBinding.java @@ -0,0 +1,67 @@ +package net.firedevops.firemud.common.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.world.WorldPublishedStartLocationEvidence; + +/** Original closed publication input; byte integrity never authenticates its producer. */ +public record GameDesignPublicationOperationBinding( + AccountPublicationAuthorizationBinding account, WorldPublishedStartLocationEvidence world) { + public static final String SCHEMA = "game-design-publication-operation/v1"; + + public GameDesignPublicationOperationBinding { + account = + AccountPublicationAuthorizationBinding.fromStored( + Objects.requireNonNull(account).canonicalBytes()); + world = + WorldPublishedStartLocationEvidence.fromStored( + Objects.requireNonNull(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"); + } + if (!PublicationDigestRequestBinding.full( + account.tenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + intent.publishRequestId()) + .derivedWorkflowIdentity() + .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 GameDesignPublicationOperationBinding fromStored(byte[] bytes) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(bytes); + reader.expect(SCHEMA); + var operation = + new GameDesignPublicationOperationBinding( + AccountPublicationAuthorizationBinding.fromStored(reader.bytes()), + WorldPublishedStartLocationEvidence.fromStored(reader.bytes())); + reader.requireEnd(); + if (!Arrays.equals(bytes, operation.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical publication operation"); + } + return operation; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClientMtlsTest.java new file mode 100644 index 0000000000..2ff9dfcbb6 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClientMtlsTest.java @@ -0,0 +1,491 @@ +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.Optional; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadResult; +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.gamedesign.v1.GameDesignPublicationTerminalReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalRequest; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalResponse; +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 client proof against a labeled transport-only owner source double. */ +class GameDesignPublicationTerminalClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String OTHER_GAME_DESIGN_URI = + "spiffe://firemud/ns/other-test/sa/game-design-service"; + private static final String WRONG_WORKLOAD_URI = + "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + @TempDir static Path tempDirectory; + private static TestPki pki; + private Server server; + private GameDesignPublicationTerminalClient client; + private AtomicInteger headers; + private AtomicInteger bodies; + + @BeforeAll + static void createTrustedCertificates() 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 exactGameDesignServerReturnsExplicitUnknownAndUnchangedTerminalEvidence() throws Exception { + var request = GameDesignPublicationTerminalReadGrpcCodecTest.request(); + for (Mode mode : List.of(Mode.UNKNOWN, Mode.EXACT)) { + startServer(pki.gameDesignServer(), mode); + client = newClient(server); + client.init(); + var actual = client.read(request); + assertThat(actual.status()) + .isEqualTo( + mode == Mode.UNKNOWN + ? GameDesignPublicationTerminalReadEvidence.Status.UNKNOWN + : GameDesignPublicationTerminalReadEvidence.Status.NO_PUBLICATION); + if (mode == Mode.EXACT) + assertThat(actual.terminalEvidence().orElseThrow().canonicalBytes()) + .isEqualTo( + GameDesignPublicationTerminalReadGrpcCodecTest.noPublication(request) + .terminalEvidence() + .orElseThrow() + .canonicalBytes()); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + stopTransport(); + } + } + + @Test + void trustedWrongGameDesignWorkloadAndNamespaceReleaseNoMetadataOrBody() throws Exception { + var request = GameDesignPublicationTerminalReadGrpcCodecTest.request(); + for (TestIdentity identity : List.of(pki.wrongWorkloadServer(), pki.otherNamespaceServer())) { + startServer(identity, Mode.EXACT); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + e -> + assertThat(Status.fromThrowable(e).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + stopTransport(); + } + } + + @Test + void authenticatedResponseCannotSubstituteReadIdentityOrMalformedTerminalBytes() + throws Exception { + var request = GameDesignPublicationTerminalReadGrpcCodecTest.request(); + for (Mode mode : List.of(Mode.WRONG_REQUEST, Mode.MALFORMED)) { + startServer(pki.gameDesignServer(), mode); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid publication terminal read evidence"); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + stopTransport(); + } + } + + @Test + void refusesPlaintextClasspathUnreadableFilesAndUninitializedOrClosedCalls() throws Exception { + var plain = pki.clientProperties(tempDirectory); + plain.setPlaintext(true); + assertThatThrownBy( + () -> + new GameDesignPublicationTerminalClient( + new ServiceEndpointsProperties(), plain, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + var classpath = pki.clientProperties(tempDirectory); + classpath.setCaCert("classpath:ca.crt"); + assertThatThrownBy( + () -> + new GameDesignPublicationTerminalClient( + new ServiceEndpointsProperties(), + classpath, + new GrpcChannelFactory(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + var missing = pki.clientProperties(tempDirectory); + missing.setCaCert(tempDirectory.resolve("absent-ca.crt").toString()); + assertThatThrownBy( + () -> + new GameDesignPublicationTerminalClient( + new ServiceEndpointsProperties(), missing, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + startServer(pki.gameDesignServer(), Mode.EXACT); + client = newClient(server); + var request = GameDesignPublicationTerminalReadGrpcCodecTest.request(); + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + client.init(); + client.close(); + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(client::init).isInstanceOf(IllegalStateException.class); + assertThat(headers).hasValue(0); + } + + private enum Mode { + EXACT, + UNKNOWN, + WRONG_REQUEST, + MALFORMED + } + + private void startServer(TestIdentity identity, Mode mode) throws Exception { + headers = new AtomicInteger(); + bodies = new AtomicInteger(); + var service = + new GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceImplBase() { + @Override + public void readGameDesignPublicationTerminal( + ReadGameDesignPublicationTerminalRequest wire, + StreamObserver observer) { + bodies.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(ACCOUNT_URI); + var request = GameDesignPublicationTerminalReadGrpcCodec.fromRequest(wire); + ReadGameDesignPublicationTerminalResponse response; + if (mode == Mode.MALFORMED) + response = + ReadGameDesignPublicationTerminalResponse.newBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(new byte[] {(byte) 0xff})) + .build(); + else { + if (mode == Mode.WRONG_REQUEST) + request = + new ReadRequest( + 1, + NAMESPACE, + UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"), + request.operationBytes()); + var result = + mode == Mode.UNKNOWN + ? new ReadResult( + request, + GameDesignPublicationTerminalReadEvidence.Status.UNKNOWN, + Optional.empty()) + : GameDesignPublicationTerminalReadGrpcCodecTest.noPublication(request); + response = GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, result); + } + observer.onNext(response); + observer.onCompleted(); + } + }; + ServerInterceptor countHeaders = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + headers.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, countHeaders, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GameDesignPublicationTerminalClient newClient(Server target) + throws IOException, CertificateEncodingException { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + target.getPort()); + return new GameDesignPublicationTerminalClient( + endpoints, pki.clientProperties(tempDirectory), new GrpcChannelFactory(), NAMESPACE); + } + + private record TestIdentity(String alias, PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity gameDesignServer, + TestIdentity wrongWorkloadServer, + TestIdentity otherNamespaceServer, + TestIdentity accountClient) { + 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, "game-design-server", GAME_DESIGN_URI, true), + issueIdentity( + directory, caStore, caFile, "wrong-workload-server", WRONG_WORKLOAD_URI, true), + issueIdentity( + directory, caStore, caFile, "wrong-namespace-server", OTHER_GAME_DESIGN_URI, true), + issueIdentity(directory, caStore, caFile, "account-client", ACCOUNT_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory) + throws IOException, CertificateEncodingException { + Path clientCertificate = + writePem( + directory.resolve("account-client.crt"), + "CERTIFICATE", + accountClient.certificate().getEncoded()); + Path clientPrivateKey = + writePem( + directory.resolve("account-client.key"), + "PRIVATE KEY", + accountClient.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/gamedesign/GameDesignPublicationTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadGrpcCodecTest.java new file mode 100644 index 0000000000..c3ef5952bb --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalReadGrpcCodecTest.java @@ -0,0 +1,222 @@ +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 com.google.protobuf.UnknownFieldSet; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadResult; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.Status; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalRequest; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalResponse; +import org.junit.jupiter.api.Test; + +class GameDesignPublicationTerminalReadGrpcCodecTest { + @Test + void exactRequestAndTypedUnknownAndTerminalRoundTripWithoutInventingPublication() + throws Exception { + var request = request(); + assertThat( + GameDesignPublicationTerminalReadGrpcCodec.fromRequest( + GameDesignPublicationTerminalReadGrpcCodec.toRequest(request)) + .canonicalBytes()) + .isEqualTo(request.canonicalBytes()); + for (ReadResult result : + List.of( + new ReadResult(request, Status.UNKNOWN, Optional.empty()), noPublication(request))) { + var restored = + GameDesignPublicationTerminalReadGrpcCodec.fromResponse( + request, GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, result)); + assertThat(restored.canonicalBytes()).isEqualTo(result.canonicalBytes()); + assertThat(restored.terminalEvidence().isEmpty()) + .isEqualTo(result.status() == Status.UNKNOWN); + } + } + + @Test + void rejectsUnknownTrailingMalformedNoncanonicalMixedOutcomeAndRequestSubstitution() + throws Exception { + var request = request(); + var terminal = noPublication(request); + var unsupported = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + assertThatThrownBy( + () -> + GameDesignPublicationTerminalReadGrpcCodec.fromRequest( + GameDesignPublicationTerminalReadGrpcCodec.toRequest(request).toBuilder() + .setUnknownFields(unsupported) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameDesignPublicationTerminalReadGrpcCodec.fromResponse( + request, + GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, terminal) + .toBuilder() + .setUnknownFields(unsupported) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + ReadRequest.fromStored( + Arrays.copyOf(request.canonicalBytes(), request.canonicalBytes().length + 1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + ReadResult.fromStored( + Arrays.copyOf(terminal.canonicalBytes(), terminal.canonicalBytes().length + 1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new ReadRequest(2, "test", UUID.randomUUID(), request.operationBytes())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new ReadRequest(1, "test", new UUID(0, 0), request.operationBytes())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new ReadRequest(1, "other", UUID.randomUUID(), request.operationBytes())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameDesignPublicationTerminalReadGrpcCodec.fromRequest( + ReadGameDesignPublicationTerminalRequest.newBuilder() + .setCanonicalRequestBytes(ByteString.copyFrom(new byte[] {1})) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new ReadResult(request, Status.UNKNOWN, terminal.terminalEvidence())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new ReadResult(request, Status.PUBLISHED, terminal.terminalEvidence())) + .isInstanceOf(IllegalArgumentException.class); + var changed = + new ReadRequest(1, request.targetNamespace(), UUID.randomUUID(), request.operationBytes()); + assertThatThrownBy( + () -> + GameDesignPublicationTerminalReadGrpcCodec.fromResponse( + request, + GameDesignPublicationTerminalReadGrpcCodec.toResponse( + changed, noPublication(changed)))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameDesignPublicationTerminalReadGrpcCodec.fromResponse( + request, ReadGameDesignPublicationTerminalResponse.getDefaultInstance())) + .isInstanceOf(IllegalArgumentException.class); + byte[] noncanonical = request.canonicalBytes(); + noncanonical[0] = (byte) 0xff; + assertThatThrownBy(() -> ReadRequest.fromStored(noncanonical)) + .isInstanceOf(IllegalArgumentException.class); + var op = GameDesignPublicationOperationBinding.fromStored(request.operationBytes()); + var a = op.account(); + var changedOp = + new GameDesignPublicationOperationBinding( + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), a.fenceId(), a.input(), a.sources()), + op.world()); + var changedRequest = new ReadRequest(1, "test", UUID.randomUUID(), changedOp.canonicalBytes()); + assertThatThrownBy( + () -> + new ReadResult(changedRequest, Status.NO_PUBLICATION, terminal.terminalEvidence())) + .isInstanceOf(IllegalArgumentException.class); + } + + static ReadRequest request() throws Exception { + var seed = AuthoredWorldReleaseAttestationSelectorTest.selectorEvidence(); + var original = DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); + var draft = + DraftCommitBinding.fromStored( + new String(original.gameDesignBinding(), StandardCharsets.UTF_8), + original.inputDigest()); + var target = draft.target(); + String request = "publication-terminal-test"; + var selected = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + request, + "5", + "fixed-notes", + draft.requestId(), + draft.commitId(), + draft.digest()), + target, + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + draft.requestId(), + draft.commitId(), + draft.digest(), + "[]", + OffsetDateTime.parse("2026-10-07T00:00:00Z"))); + var account = + new AccountPublicationAuthorizationBinding( + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + new AccountPublicationAuthorizationBinding.PreallocationInput( + original.actorAccountId(), selected), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + original.actorAccountId().toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + var r = seed.request(); + var world = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + r.targetNamespace(), + r.canonicalTenantId(), + r.canonicalVersionId(), + r.intakeRequestId(), + r.publicationFence(), + request, + selected.digest().substring(7), + 5, + PublicationDigestRequestBinding.full( + target.canonicalTenantId().toString(), + Long.toString(target.gameDesignVersionRowId()), + request) + .derivedWorkflowIdentity(), + r.appliedCommitId(), + r.contentDigest(), + r.digestSchemaVersion(), + r.worldAffectedTuples()), + seed.selectorReceiptBytes(), + seed.originalAccountBindingBytes(), + seed.appliedResultBytes()); + return new ReadRequest( + 1, + "test", + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + new GameDesignPublicationOperationBinding(account, world).canonicalBytes()); + } + + static ReadResult noPublication(ReadRequest request) { + return new ReadResult( + request, + Status.NO_PUBLICATION, + Optional.of( + new GameDesignPublicationTerminalEvidence( + request.operationBytes(), + GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION, + null, + null))); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceTest.java new file mode 100644 index 0000000000..37b867816b --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceTest.java @@ -0,0 +1,480 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Participant; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.ReleaseContent; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import org.junit.jupiter.api.Test; + +/** Fixed isolated inputs prove codec integrity, never upstream creator or owner authentication. */ +class GameDesignPublicationTerminalEvidenceTest { + private static final String DIGEST = "sha256:" + "a".repeat(64); + + @Test + void goldenContentFramesAndDigestBindCompleteBundleWithoutLaunchMetadata() throws Exception { + var operation = operation(9007199254740993L); + var content = content(operation, List.of("LOOK", "é"), "generation-1"); + // Independent reference vector: every field and optional presence is explicit in owner order. + String expected = + frame("game-design-published-release-bundle/v1") + + frame(content.canonicalTenantId().toString()) + + frame(content.canonicalVersionId().toString()) + + frame("bundle-fixed") + + frame("1") + + frame("v2") + + frame(content.publishWorkflowId()) + + frame(DIGEST) + + frame("1") + + frame("1") + + frame( + frame("asset-é") + + frame("FILE") + + frame("artifacts/sha256/" + "a".repeat(64)) + + frame(DIGEST) + + frame("text/plain") + + frame("1")) + + frame("1") + + frame("asset-é") + + frame("5"); + var expectedBytes = new StringBuilder(expected); + for (var p : content.participantDigests()) { + expectedBytes.append( + frame( + frame(p.participantKey()) + + frame(p.scopeValue()) + + frame("false") + + frame("") + + frame(p.appliedCommitId()) + + frame(p.contentDigest()) + + frame(Integer.toString(p.digestSchemaVersion())) + + frame(p.abilitySchemaDigest() == null ? "false" : "true") + + frame(p.abilitySchemaDigest() == null ? "" : p.abilitySchemaDigest()) + + frame("false") + + frame("") + + frame("false") + + frame(""))); + } + expectedBytes.append( + frame("2") + + frame("LOOK") + + frame("é") + + frame("generation-1") + + frame(new String(operation.world().canonicalBytes(), StandardCharsets.UTF_8)) + + frame("false") + + frame("false") + + frame("")); + byte[] golden = expectedBytes.toString().getBytes(StandardCharsets.UTF_8); + assertThat(content.canonicalBytes()).isEqualTo(golden); + assertThat(content.contentDigest()) + .isEqualTo( + "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(golden))); + var terminal = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), Outcome.PUBLISHED, content, 9007199254740994L); + var expectedTerminal = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(expectedTerminal, "game-design-publication-terminal/v1"); + DraftAuthorizationFenceBinding.frame(expectedTerminal, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(expectedTerminal, "PUBLISHED"); + DraftAuthorizationFenceBinding.frame(expectedTerminal, golden); + DraftAuthorizationFenceBinding.frame(expectedTerminal, "9007199254740994"); + assertThat(terminal.canonicalBytes()).isEqualTo(expectedTerminal.toByteArray()); + var decoded = GameDesignPublicationTerminalEvidence.fromStored(terminal.canonicalBytes()); + assertThat(decoded.canonicalBytes()).isEqualTo(terminal.canonicalBytes()); + assertThat(decoded.operationBytes()).isEqualTo(operation.canonicalBytes()); + assertThat(decoded.publicationVersionStateEpoch()).isEqualTo(9007199254740994L); + } + + @Test + void changedContentAndOptionalPresenceChangeDistinctContentDigest() throws Exception { + var operation = operation(5); + var original = content(operation, List.of("LOOK"), "generation-1"); + assertThat(content(operation, List.of("LOOK", "PLAY"), "generation-1").contentDigest()) + .isNotEqualTo(original.contentDigest()); + assertThat(content(operation, List.of("LOOK"), "generation-2").contentDigest()) + .isNotEqualTo(original.contentDigest()); + var changedManifest = + new ReleaseContent( + original.canonicalTenantId(), + original.canonicalVersionId(), + "changed-ref", + 2, + original.attestationSchemaVersion(), + original.publishWorkflowId(), + "sha256:" + "d".repeat(64), + original.manifestSchemaVersion(), + original.artifactDigests(), + original.requiredManifestAssetKeys(), + original.participantDigests(), + original.commandDefinitions(), + original.generationConfigRevision(), + original.worldStartLocationEvidence()); + assertThat(changedManifest.contentDigest()).isNotEqualTo(original.contentDigest()); + var changedArtifact = + List.of( + new AuthoredWorldReleaseAttestationEvidence.Artifact( + "asset-é", + "TEXT", + "artifacts/sha256/" + "d".repeat(64), + "sha256:" + "d".repeat(64), + "text/other", + 1)); + assertThat( + copy( + original, + original.publishWorkflowId(), + original.participantDigests(), + changedArtifact) + .contentDigest()) + .isNotEqualTo(original.contentDigest()); + var participants = new ArrayList<>(original.participantDigests()); + var p = participants.getFirst(); + participants.set( + 0, + new Participant( + p.participantKey(), + p.scopeValue(), + null, + p.appliedCommitId(), + p.contentDigest(), + p.digestSchemaVersion(), + null, + "", + "")); + assertThat( + copy(original, original.publishWorkflowId(), participants, original.artifactDigests()) + .contentDigest()) + .isNotEqualTo(original.contentDigest()); + var terminal = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), Outcome.PUBLISHED, original, 6L); + byte[] bytes = terminal.canonicalBytes(); + bytes[0] = 99; + assertThat(terminal.canonicalBytes()).isNotEqualTo(bytes); + } + + @Test + void rejectsWrongOperationWorkflowFreezeCommitRequiredParticipantAndArtifact() throws Exception { + var operation = operation(5); + var content = content(operation, List.of(), "generation-1"); + assertThatThrownBy( + () -> + copy( + content, + "changed-workflow", + content.participantDigests(), + content.artifactDigests())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + copy( + content, + content.publishWorkflowId(), + content.participantDigests().subList(0, 4), + content.artifactDigests())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + copy(content, content.publishWorkflowId(), content.participantDigests(), List.of())) + .isInstanceOf(IllegalArgumentException.class); + var changed = new ArrayList<>(content.participantDigests()); + var p = changed.getFirst(); + changed.set( + 0, + new Participant( + p.participantKey(), + p.scopeValue(), + null, + "changed-commit", + p.contentDigest(), + p.digestSchemaVersion(), + null, + null, + null)); + assertThatThrownBy( + () -> copy(content, content.publishWorkflowId(), changed, content.artifactDigests())) + .isInstanceOf(IllegalArgumentException.class); + var missingAbility = new ArrayList<>(content.participantDigests()); + var logic = missingAbility.get(2); + missingAbility.set( + 2, + new Participant( + logic.participantKey(), + logic.scopeValue(), + null, + logic.appliedCommitId(), + logic.contentDigest(), + logic.digestSchemaVersion(), + null, + null, + null)); + assertThatThrownBy( + () -> + copy( + content, + content.publishWorkflowId(), + missingAbility, + content.artifactDigests())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AuthoredWorldReleaseAttestationEvidence.Artifact( + "asset-é", "FILE", "wrong-object", DIGEST, "text/plain", 1)) + .isInstanceOf(IllegalArgumentException.class); + var reordered = new ArrayList<>(content.participantDigests()); + java.util.Collections.swap(reordered, 0, 1); + assertThatThrownBy( + () -> copy(content, content.publishWorkflowId(), reordered, content.artifactDigests())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), Outcome.PUBLISHED, content, 7L)) + .isInstanceOf(IllegalArgumentException.class); + var account = operation.account(); + var allocatedDifferently = + new GameDesignPublicationOperationBinding( + new AccountPublicationAuthorizationBinding( + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + account.fenceId(), + account.input(), + account.sources()), + operation.world()); + var first = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), Outcome.PUBLISHED, content, 6L); + var second = + new GameDesignPublicationTerminalEvidence( + allocatedDifferently.canonicalBytes(), Outcome.PUBLISHED, content, 6L); + assertThat(second.canonicalBytes()).isNotEqualTo(first.canonicalBytes()); + var world = operation.world(); + var r = world.request(); + var changedFreeze = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + r.targetNamespace(), + r.canonicalTenantId(), + r.canonicalVersionId(), + r.intakeRequestId(), + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + r.publicationRequestId(), + r.requestDigest(), + r.versionStateEpoch(), + r.publishWorkflowId(), + r.appliedCommitId(), + r.contentDigest(), + r.digestSchemaVersion(), + r.worldAffectedTuples()), + world.selectorReceiptBytes(), + world.originalAccountBindingBytes(), + world.appliedResultBytes()); + var changedOperation = new GameDesignPublicationOperationBinding(account, changedFreeze); + assertThatThrownBy( + () -> + new GameDesignPublicationTerminalEvidence( + changedOperation.canonicalBytes(), Outcome.PUBLISHED, content, 6L)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void noPublicationHasNoReleaseAndRejectsMalformedTrailingAndNoncanonicalFrames() + throws Exception { + var operation = operation(5); + var no = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), Outcome.NO_PUBLICATION, null, null); + assertThat(GameDesignPublicationTerminalEvidence.fromStored(no.canonicalBytes()).outcome()) + .isEqualTo(Outcome.NO_PUBLICATION); + assertThatThrownBy(no::publishedReleaseBundleDigest).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(no::publishedReleaseBundleRef).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(no::publicationVersionStateEpoch).isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + Outcome.NO_PUBLICATION, + content(operation, List.of(), "g"), + null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameDesignPublicationTerminalEvidence.fromStored( + Arrays.copyOf(no.canonicalBytes(), no.canonicalBytes().length + 1))) + .isInstanceOf(IllegalArgumentException.class); + var content = content(operation, List.of(), "g"); + var canonical = content.canonicalBytes(); + var noncanonical = + ("0" + new String(canonical, StandardCharsets.UTF_8)).getBytes(StandardCharsets.UTF_8); + assertThatThrownBy(() -> ReleaseContent.fromStored(noncanonical)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> ReleaseContent.fromStored(Arrays.copyOf(canonical, canonical.length - 1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> ReleaseContent.fromStored(Arrays.copyOf(canonical, canonical.length + 1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> GameDesignPublicationTerminalEvidence.fromStored(operation.canonicalBytes())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static ReleaseContent content( + GameDesignPublicationOperationBinding operation, List commands, String generation) { + var r = operation.world().request(); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new Participant( + owner, + Long.toString( + operation + .account() + .input() + .selection() + .target() + .gameDesignVersionRowId()), + null, + r.appliedCommitId(), + owner.equals("WORLD_MANAGEMENT") ? r.contentDigest() : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + owner.equals("GAME_LOGIC") ? DIGEST : null, + null, + null)) + .toList(); + return new ReleaseContent( + r.canonicalTenantId(), + r.canonicalVersionId(), + "bundle-fixed", + 1, + "v2", + r.publishWorkflowId(), + DIGEST, + 1, + List.of( + new AuthoredWorldReleaseAttestationEvidence.Artifact( + "asset-é", "FILE", "artifacts/sha256/" + "a".repeat(64), DIGEST, "text/plain", 1)), + List.of("asset-é"), + participants, + commands, + generation, + operation.world()); + } + + private static ReleaseContent copy( + ReleaseContent c, + String workflow, + List participants, + List artifacts) { + return new ReleaseContent( + c.canonicalTenantId(), + c.canonicalVersionId(), + c.publishedReleaseBundleRef(), + c.versionNumber(), + c.attestationSchemaVersion(), + workflow, + c.manifestHash(), + c.manifestSchemaVersion(), + artifacts, + c.requiredManifestAssetKeys(), + participants, + c.commandDefinitions(), + c.generationConfigRevision(), + c.worldStartLocationEvidence()); + } + + private static GameDesignPublicationOperationBinding operation(long epoch) throws Exception { + var seed = WorldPublishedStartLocationGrpcCodecTest.evidence(); + var original = DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); + var draft = + DraftCommitBinding.fromStored( + new String(original.gameDesignBinding(), StandardCharsets.UTF_8), + original.inputDigest()); + var target = draft.target(); + String request = "publication-request"; + var selected = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + request, + Long.toString(epoch), + "fixed-notes", + draft.requestId(), + draft.commitId(), + draft.digest()), + target, + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + draft.requestId(), + draft.commitId(), + draft.digest(), + "[]", + OffsetDateTime.parse("2026-10-07T00:00:00Z"))); + var account = + new AccountPublicationAuthorizationBinding( + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + new AccountPublicationAuthorizationBinding.PreallocationInput( + original.actorAccountId(), selected), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + original.actorAccountId().toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + var r = seed.request(); + var world = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + r.targetNamespace(), + r.canonicalTenantId(), + r.canonicalVersionId(), + r.intakeRequestId(), + r.publicationFence(), + request, + selected.digest().substring(7), + epoch, + PublicationDigestRequestBinding.full( + target.canonicalTenantId().toString(), + Long.toString(target.gameDesignVersionRowId()), + request) + .derivedWorkflowIdentity(), + r.appliedCommitId(), + r.contentDigest(), + r.digestSchemaVersion(), + r.worldAffectedTuples()), + seed.selectorReceiptBytes(), + seed.originalAccountBindingBytes(), + seed.appliedResultBytes()); + return new GameDesignPublicationOperationBinding(account, world); + } + + private static String frame(String s) { + return s.getBytes(StandardCharsets.UTF_8).length + ":" + s; + } +} 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 4832a86662..45d095299a 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 @@ -1,66 +1,27 @@ 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.temporal.FiremudWorkflowIds; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; /** 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 static final String SCHEMA = GameDesignPublicationOperationBinding.SCHEMA; 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"); - } + var binding = new GameDesignPublicationOperationBinding(account, world); + account = binding.account(); + world = binding.world(); } public byte[] canonicalBytes() { - var out = new ByteArrayOutputStream(); - DraftAuthorizationFenceBinding.frame(out, SCHEMA); - DraftAuthorizationFenceBinding.frame(out, account.canonicalBytes()); - DraftAuthorizationFenceBinding.frame(out, world.canonicalBytes()); - return out.toByteArray(); + return new GameDesignPublicationOperationBinding(account, world).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())); - reader.requireEnd(); - if (!Arrays.equals(bytes, operation.canonicalBytes())) { - throw new IllegalArgumentException("Noncanonical publication operation"); - } - return operation; + var binding = GameDesignPublicationOperationBinding.fromStored(bytes); + return new GameDesignPublicationOperation(binding.account(), binding.world()); } public String workflowId() { 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..534c408c4e 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 @@ -6,6 +6,7 @@ import java.util.Objects; import java.util.Optional; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -60,7 +61,7 @@ public void seal(String tenant, String workflow, long version, String digest, bo 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 = ?", + "SELECT r.*, 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); @@ -68,12 +69,35 @@ public void seal(String tenant, String workflow, long version, String digest, bo throw new IllegalStateException("PUBLICATION_READBACK_UNRESOLVED"); String outcome = published ? "PUBLISHED" : "NO_PUBLICATION"; byte[] result = receipt(operation, outcome, evidence); + Long publicationEpoch = null; + if (published) { + Record committedVersion = + dsl.fetchOne( + "SELECT version_state, version_state_epoch FROM version WHERE tenant_id = ? AND id = ? FOR UPDATE", + tenant, + version); + if (committedVersion == null + || !"PUBLISHED".equals(committedVersion.get("version_state", String.class))) { + throw new IllegalStateException("PUBLICATION_VERSION_NOT_COMMITTED"); + } + publicationEpoch = committedVersion.get("version_state_epoch", Long.class); + } + var terminal = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + GameDesignPublicationTerminalEvidence.Outcome.valueOf(outcome), + published ? PublicationReleaseContent.fromRow(release) : null, + publicationEpoch); 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", + "UPDATE game_design_publication_operation SET outcome = ?, result_bytes = ?, release_row_json = ?, terminal_evidence_bytes = ?, publication_version_state_epoch = ?, release_content_bytes = ?, published_release_bundle_digest = ?, revision = revision + 1 WHERE publish_workflow_id = ? AND outcome = 'PENDING' AND revision = 1", outcome, result, evidence, + terminal.canonicalBytes(), + publicationEpoch, + published ? terminal.releaseContent().canonicalBytes() : null, + published ? terminal.publishedReleaseBundleDigest() : null, workflow); if (changed != 1) throw new IllegalStateException("PUBLICATION_OPERATION_CAS_CONFLICT"); } @@ -89,6 +113,7 @@ public Optional read(String workflow) { String outcome = row.get("outcome", String.class); byte[] bytes = row.get("result_bytes", byte[].class); String evidence = row.get("release_row_json", String.class); + byte[] terminalBytes = row.get("terminal_evidence_bytes", byte[].class); if (!operation.workflowId().equals(workflow) || !operation.tenantKey().equals(row.get("tenant_id", String.class)) || operation.versionId() != row.get("version_id", Long.class) @@ -107,6 +132,35 @@ public Optional read(String workflow) { if (!Objects.equals(actual, evidence) || ("PUBLISHED".equals(outcome) != (actual != null))) { throw new IllegalStateException("PUBLICATION_RECEIPT_BACKING_CONFLICT"); } + // V50 history remains readable but never acquires unverifiable forward evidence. + if (terminalBytes != null) { + var terminal = GameDesignPublicationTerminalEvidence.fromStored(terminalBytes); + if (!Arrays.equals(terminal.operationBytes(), operation.canonicalBytes()) + || !terminal.outcome().name().equals(outcome)) { + throw new IllegalStateException("PUBLICATION_TERMINAL_IDENTITY_CONFLICT"); + } + if (terminal.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED) { + Record immutableRelease = + dsl.fetchOne( + "SELECT * FROM published_release_bundle WHERE tenant_id = ? AND version_id = ?", + operation.tenantKey(), + operation.versionId()); + if (!Arrays.equals( + terminal.releaseContent().canonicalBytes(), + PublicationReleaseContent.fromRow(immutableRelease).canonicalBytes()) + || !Arrays.equals( + terminal.releaseContent().canonicalBytes(), + row.get("release_content_bytes", byte[].class)) + || !Objects.equals( + terminal.publicationVersionStateEpoch(), + row.get("publication_version_state_epoch", Long.class)) + || !terminal + .publishedReleaseBundleDigest() + .equals(row.get("published_release_bundle_digest", String.class))) { + throw new IllegalStateException("PUBLICATION_TERMINAL_BACKING_CONFLICT"); + } + } + } Record attempt = dsl.fetchOne( "SELECT status FROM publish_attempt WHERE publish_workflow_id = ?", workflow); @@ -118,7 +172,7 @@ public Optional read(String workflow) { throw new IllegalStateException("PUBLICATION_RECEIPT_ATTEMPT_CONFLICT"); } } - return Optional.of(new Readback(operation, outcome, bytes)); + return Optional.of(new Readback(operation, outcome, bytes, terminalBytes)); } private void lock(String tenant, String workflow, long version) { @@ -158,9 +212,22 @@ private static void requireTransaction() { } public record Readback( - GameDesignPublicationOperation operation, String outcome, byte[] receiptBytes) { + GameDesignPublicationOperation operation, + String outcome, + byte[] receiptBytes, + byte[] terminalEvidenceBytes) { public Readback { receiptBytes = receiptBytes == null ? null : receiptBytes.clone(); + terminalEvidenceBytes = terminalEvidenceBytes == null ? null : terminalEvidenceBytes.clone(); + } + + public Readback(GameDesignPublicationOperation operation, String outcome, byte[] receiptBytes) { + this(operation, outcome, receiptBytes, null); + } + + @Override + public byte[] terminalEvidenceBytes() { + return terminalEvidenceBytes == null ? null : terminalEvidenceBytes.clone(); } @Override diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadGrpcService.java new file mode 100644 index 0000000000..fa1b8ba391 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadGrpcService.java @@ -0,0 +1,110 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadResult; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.v1.GameDesignPublicationTerminalReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalRequest; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalResponse; + +/** Standalone authenticated read adapter. Deliberately has no runtime registration. */ +public final class GameDesignPublicationTerminalReadGrpcService + extends GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceImplBase { + private final GameDesignPublicationOperationService owner; + private final String namespace; + + public GameDesignPublicationTerminalReadGrpcService( + GameDesignPublicationOperationService owner, String namespace) { + this.owner = Objects.requireNonNull(owner); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical workload namespace required"); + this.namespace = namespace; + } + + @Override + public void readGameDesignPublicationTerminal( + ReadGameDesignPublicationTerminalRequest wire, + StreamObserver observer) { + var peer = GrpcPeerIdentity.current(); + String prefix = "spiffe://firemud/ns/" + namespace + "/sa/"; + if (peer == null + || !(peer.uri().equals(prefix + "account-service") + || peer.uri().equals(prefix + "world-management-service")) + || SessionContext.hasAuthenticatedCallerContext()) { + fail( + observer, + Status.PERMISSION_DENIED, + "Verified same-namespace Account or World workload without end-user context required"); + return; + } + final ReadRequest request; + try { + request = GameDesignPublicationTerminalReadGrpcCodec.fromRequest(wire); + } catch (RuntimeException malformed) { + fail( + observer, + Status.INVALID_ARGUMENT, + "Complete canonical publication terminal read request required"); + return; + } + if (!namespace.equals(request.targetNamespace())) { + fail( + observer, + Status.PERMISSION_DENIED, + "Terminal read namespace differs from authenticated peer"); + return; + } + final ReadResult result; + try { + var operation = GameDesignPublicationOperation.fromStored(request.operationBytes()); + // readExact owns the independent read-only REPEATABLE_READ transaction and exact binding. + var stored = owner.readExact(operation); + if (stored.isEmpty() || stored.orElseThrow().outcome().equals("PENDING")) { + result = + new ReadResult( + request, + GameDesignPublicationTerminalReadEvidence.Status.UNKNOWN, + Optional.empty()); + } else { + byte[] bytes = stored.orElseThrow().terminalEvidenceBytes(); + if (bytes == null) + throw new IllegalStateException("Historical terminal result has no captured evidence"); + var terminal = GameDesignPublicationTerminalEvidence.fromStored(bytes); + result = + new ReadResult( + request, + GameDesignPublicationTerminalReadEvidence.Status.valueOf( + stored.orElseThrow().outcome()), + Optional.of(terminal)); + } + } catch (org.springframework.dao.DataAccessException + | org.jooq.exception.DataAccessException unavailable) { + fail(observer, Status.UNAVAILABLE, "Publication terminal owner storage unavailable"); + return; + } catch (IllegalArgumentException | IllegalStateException conflict) { + fail( + observer, + Status.FAILED_PRECONDITION, + "Retained publication terminal evidence unavailable or inconsistent"); + return; + } catch (RuntimeException unexpected) { + fail(observer, Status.INTERNAL, "Publication terminal owner read failed"); + return; + } + observer.onNext(GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, result)); + observer.onCompleted(); + } + + private static void fail(StreamObserver observer, Status status, String message) { + observer.onError(status.withDescription(message).asRuntimeException()); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublicationReleaseContent.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublicationReleaseContent.java new file mode 100644 index 0000000000..e330e02684 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublicationReleaseContent.java @@ -0,0 +1,65 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import org.jooq.Record; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.ObjectMapper; + +/** Maps the actual immutable release row, never a launch descriptor or a mutable Version read. */ +final class PublicationReleaseContent { + private PublicationReleaseContent() {} + + static GameDesignPublicationTerminalEvidence.ReleaseContent fromRow(Record row) { + if (row == null + || !Boolean.FALSE.equals(row.get("script_only", Boolean.class)) + || row.get("script_patch_version", String.class) != null) { + throw new IllegalStateException("PUBLICATION_RELEASE_NOT_FULL_VERSION"); + } + var mapper = new ObjectMapper(); + List participants = + mapper.readValue( + row.get("participant_digests_json", String.class), new TypeReference<>() {}); + return new GameDesignPublicationTerminalEvidence.ReleaseContent( + row.get("canonical_tenant_id", UUID.class), + row.get("canonical_version_id", UUID.class), + row.get("published_release_bundle_ref", String.class), + row.get("version_number", Integer.class), + row.get("attestation_schema_version", String.class), + row.get("publish_workflow_id", String.class), + row.get("manifest_hash", String.class), + row.get("manifest_schema_version", Integer.class), + mapper.readValue( + row.get("artifact_digests_json", String.class), + new TypeReference>() {}), + mapper.readValue( + row.get("required_manifest_asset_keys_json", String.class), + new TypeReference>() {}), + participants.stream() + .map( + p -> + new GameDesignPublicationTerminalEvidence.Participant( + p.participantKey(), + p.scopeValue(), + p.baseVersionId(), + p.appliedCommitId(), + p.contentDigest(), + p.digestSchemaVersion(), + p.abilitySchemaDigest(), + p.errorCode(), + p.errorMessage())) + .toList(), + mapper.readValue( + row.get("command_definitions_json", String.class), + new TypeReference>() {}), + row.get("generation_config_revision", String.class), + WorldPublishedStartLocationEvidence.fromStored( + row.get("world_published_start_location_evidence_json", String.class) + .getBytes(StandardCharsets.UTF_8))); + } +} diff --git a/services/game-design-service/src/main/resources/db/migration/V51__publication_terminal_content_and_epoch.sql b/services/game-design-service/src/main/resources/db/migration/V51__publication_terminal_content_and_epoch.sql new file mode 100644 index 0000000000..a40cd4fd14 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V51__publication_terminal_content_and_epoch.sql @@ -0,0 +1,141 @@ +-- Retained V50 terminal rows keep their original bytes and gain no unverifiable epoch. +ALTER TABLE game_design_publication_operation ADD COLUMN terminal_evidence_bytes BYTEA; +ALTER TABLE game_design_publication_operation ADD COLUMN publication_version_state_epoch BIGINT; +ALTER TABLE game_design_publication_operation ADD COLUMN release_content_bytes BYTEA; +ALTER TABLE game_design_publication_operation ADD COLUMN published_release_bundle_digest VARCHAR(71); +ALTER TABLE game_design_publication_operation ADD CONSTRAINT publication_terminal_extension_shape CHECK ( + (terminal_evidence_bytes IS NULL AND publication_version_state_epoch IS NULL + AND release_content_bytes IS NULL AND published_release_bundle_digest IS NULL) + OR (terminal_evidence_bytes IS NOT NULL AND octet_length(terminal_evidence_bytes) > 0 AND + ((outcome = 'NO_PUBLICATION' AND publication_version_state_epoch IS NULL + AND release_content_bytes IS NULL AND published_release_bundle_digest IS NULL) + OR (outcome = 'PUBLISHED' AND publication_version_state_epoch IS NOT NULL AND publication_version_state_epoch > 0 + AND release_content_bytes IS NOT NULL AND octet_length(release_content_bytes) > 0 + AND published_release_bundle_digest IS NOT NULL AND published_release_bundle_digest ~ '^sha256:[0-9a-f]{64}$')))); + +-- [jooq ignore start] +-- ADR byte-length framing for complete immutable release content, distinct from launch evidence. +CREATE FUNCTION publication_content_frame(value BYTEA) RETURNS BYTEA AS $$ + SELECT convert_to(octet_length(value)::TEXT || ':', 'UTF8') || value; +$$ LANGUAGE SQL IMMUTABLE STRICT; +CREATE FUNCTION publication_content_text(value TEXT) RETURNS BYTEA AS $$ + SELECT publication_content_frame(convert_to(value, 'UTF8')); +$$ LANGUAGE SQL IMMUTABLE STRICT; +CREATE FUNCTION publication_content_optional(value TEXT) RETURNS BYTEA AS $$ + SELECT publication_content_text(CASE WHEN value IS NULL THEN 'false' ELSE 'true' END) + || publication_content_text(COALESCE(value, '')); +$$ LANGUAGE SQL IMMUTABLE; +CREATE FUNCTION publication_content_strings(values_json JSONB) RETURNS BYTEA AS $$ +DECLARE result BYTEA; value JSONB; +BEGIN + result := publication_content_text(jsonb_array_length(values_json)::TEXT); + FOR value IN SELECT * FROM jsonb_array_elements(values_json) LOOP + result := result || publication_content_text(value #>> '{}'); + END LOOP; + RETURN result; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; + +CREATE FUNCTION publication_release_content(release published_release_bundle) RETURNS BYTEA AS $$ +DECLARE result BYTEA; entry BYTEA; item JSONB; +BEGIN + IF release.script_only OR release.script_patch_version IS NOT NULL + OR release.attestation_schema_version <> 'v2' THEN + RAISE EXCEPTION 'terminal publication requires complete full-version v2 content' USING ERRCODE = 'check_violation'; + END IF; + result := publication_content_text('game-design-published-release-bundle/v1') + || publication_content_text(release.canonical_tenant_id::TEXT) + || publication_content_text(release.canonical_version_id::TEXT) + || publication_content_text(release.published_release_bundle_ref) + || publication_content_text(release.version_number::TEXT) + || publication_content_text(release.attestation_schema_version) + || publication_content_text(release.publish_workflow_id) + || publication_content_text(release.manifest_hash) + || publication_content_text(release.manifest_schema_version::TEXT) + || publication_content_text(jsonb_array_length(release.artifact_digests_json::JSONB)::TEXT); + FOR item IN SELECT * FROM jsonb_array_elements(release.artifact_digests_json::JSONB) LOOP + entry := publication_content_text(item->>'usageKey') || publication_content_text(item->>'artifactKind') + || publication_content_text(item->>'immutableObjectKey') || publication_content_text(item->>'contentDigest') + || publication_content_text(item->>'contentType') || publication_content_text(item->>'artifactSchemaVersion'); + result := result || publication_content_frame(entry); + END LOOP; + result := result || publication_content_strings(release.required_manifest_asset_keys_json::JSONB) + || publication_content_text(jsonb_array_length(release.participant_digests_json::JSONB)::TEXT); + FOR item IN SELECT * FROM jsonb_array_elements(release.participant_digests_json::JSONB) LOOP + entry := publication_content_text(item->>'participantKey') || publication_content_text(item->>'scopeValue') + || publication_content_optional(item->>'baseVersionId') || publication_content_text(item->>'appliedCommitId') + || publication_content_text(item->>'contentDigest') || publication_content_text(item->>'digestSchemaVersion') + || publication_content_optional(item->>'abilitySchemaDigest') || publication_content_optional(item->>'errorCode') + || publication_content_optional(item->>'errorMessage'); + result := result || publication_content_frame(entry); + END LOOP; + RETURN result || publication_content_strings(release.command_definitions_json::JSONB) + || publication_content_text(release.generation_config_revision) + || publication_content_text(release.world_published_start_location_evidence_json) + || publication_content_text('false') || publication_content_optional(NULL); +END; +$$ LANGUAGE plpgsql STABLE STRICT; + +CREATE FUNCTION guard_publication_terminal_extension() RETURNS trigger AS $$ +DECLARE release published_release_bundle%ROWTYPE; owner_version version%ROWTYPE; + expected BYTEA; content BYTEA; freeze_epoch BIGINT; +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.terminal_evidence_bytes IS NOT NULL THEN + RAISE EXCEPTION 'new publication operation must remain pending' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + -- This extension is captured only at the original seal, never backfilled onto V50 history. + IF OLD.outcome <> 'PENDING' OR OLD.terminal_evidence_bytes IS NOT NULL + OR NEW.outcome = 'PENDING' OR NEW.terminal_evidence_bytes IS NULL THEN + RAISE EXCEPTION 'publication terminal extension is immutable and cannot be backfilled' USING ERRCODE = 'check_violation'; + END IF; + expected := int4send(octet_length(convert_to('game-design-publication-terminal/v1', 'UTF8'))) + || convert_to('game-design-publication-terminal/v1', 'UTF8') + || int4send(octet_length(NEW.request_bytes)) || NEW.request_bytes + || int4send(octet_length(convert_to(NEW.outcome, 'UTF8'))) || convert_to(NEW.outcome, 'UTF8'); + IF NEW.outcome = 'PUBLISHED' THEN + SELECT * INTO STRICT release FROM published_release_bundle + WHERE tenant_id = NEW.tenant_id AND version_id = NEW.version_id; + SELECT * INTO STRICT owner_version FROM version + WHERE tenant_id = NEW.tenant_id AND id = NEW.version_id FOR UPDATE; + freeze_epoch := ((convert_from(published_world_selector_frame(NEW.request_bytes, 2), 'UTF8')::JSONB) + ->'request'->>'versionStateEpoch')::BIGINT; + content := publication_release_content(release); + IF owner_version.version_state <> 'PUBLISHED' + OR owner_version.version_state_epoch <> freeze_epoch + 1 + OR NEW.publication_version_state_epoch IS DISTINCT FROM owner_version.version_state_epoch + OR NEW.release_content_bytes IS DISTINCT FROM content + OR NEW.published_release_bundle_digest IS DISTINCT FROM 'sha256:' || encode(sha256(content), 'hex') + OR release.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR to_jsonb(release)::TEXT IS DISTINCT FROM NEW.release_row_json THEN + RAISE EXCEPTION 'publication terminal content or committed epoch differs from owner seal' USING ERRCODE = 'check_violation'; + END IF; + expected := expected || int4send(octet_length(content)) || content + || int4send(octet_length(convert_to(NEW.publication_version_state_epoch::TEXT, 'UTF8'))) + || convert_to(NEW.publication_version_state_epoch::TEXT, 'UTF8'); + END IF; + IF NEW.terminal_evidence_bytes IS DISTINCT FROM expected THEN + RAISE EXCEPTION 'publication terminal bytes differ from original owner result' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER publication_terminal_extension_guard BEFORE INSERT OR UPDATE + ON game_design_publication_operation FOR EACH ROW EXECUTE FUNCTION guard_publication_terminal_extension(); + +CREATE FUNCTION verify_publication_terminal_epoch_commit() RETURNS trigger AS $$ +BEGIN + IF NEW.outcome = 'PUBLISHED' AND NEW.terminal_evidence_bytes IS NOT NULL + AND NOT EXISTS (SELECT 1 FROM version WHERE tenant_id = NEW.tenant_id AND id = NEW.version_id + AND version_state = 'PUBLISHED' AND version_state_epoch = NEW.publication_version_state_epoch) THEN + RAISE EXCEPTION 'publication terminal epoch lacks its exact atomic Version commit' USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; +CREATE CONSTRAINT TRIGGER publication_terminal_epoch_commit_guard AFTER UPDATE + ON game_design_publication_operation DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION verify_publication_terminal_epoch_commit(); +-- [jooq ignore stop] 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..0f196d3c7a 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 @@ -3,13 +3,54 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import io.grpc.Context; +import io.grpc.ForwardingServerCall; +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.ByteArrayOutputStream; +import java.math.BigInteger; +import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; +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.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.config.PostgresProperties; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadGrpcCodec; +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.gamedesign.draft.IsolatedPublicationOwnerSetup; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; @@ -21,17 +62,34 @@ 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.publication.GameDesignPublicationTerminalReadGrpcService; +import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; 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 net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalResponse; +import net.firedevops.firemud.test.TlsTestSupport; +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.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -49,6 +107,467 @@ class GameDesignPublicationOperationPostgresIntegrationTest { static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); private static final String MANIFEST = "sha256:" + "a".repeat(64); + private static final AtomicLong TEST_CERTIFICATE_SERIAL = new AtomicLong(1); + + /** + * Genuine GD SQL result and physical workload identity; upstream creator/export/freeze remain + * ISOLATED. + */ + @Test + void + physicalMtlsTerminalReadRecoversActualPublishedAndNoPublicationOwnerSealsAndRejectsWrongPeers( + @TempDir Path directory) throws Exception { + var pki = publicationReadPki(); + int ownerIndex = 0; + for (boolean published : java.util.List.of(true, false)) { + var fixture = fixture(); + if (published) publish(fixture); + else noPublication(fixture); + var original = fixture.service().readExact(fixture.operation()).orElseThrow(); + byte[] retained = original.terminalEvidenceBytes(); + var request = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + "test", fixture.operation().canonicalBytes()); + var headers = new AtomicInteger(); + var loseResponse = new AtomicBoolean(true); + var server = publicationReadServer(fixture, pki.server(), pki.ca(), headers, loseResponse); + try { + try (var client = + publicationReadClient( + server, + pki.account(), + pki.ca(), + directory.resolve("owner-" + ownerIndex + "-account"))) { + client.init(); + // The real handler and owner read finish; the first outbound result is deliberately lost. + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + e -> + assertThat(Status.fromThrowable(e).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + var recovered = client.read(request).terminalEvidence().orElseThrow(); + assertThat(recovered.canonicalBytes()).isEqualTo(retained); + assertThat(recovered.operationBytes()).isEqualTo(fixture.operation().canonicalBytes()); + assertThat(recovered.outcome().name()) + .isEqualTo(published ? "PUBLISHED" : "NO_PUBLICATION"); + if (published) { + assertThat(recovered.publicationVersionStateEpoch()) + .isEqualTo(fixture.operation().world().request().versionStateEpoch() + 1); + assertThat(recovered.publishedReleaseBundleDigest()) + .isEqualTo(recovered.releaseContent().contentDigest()); + } else + assertThatThrownBy(recovered::publicationVersionStateEpoch) + .isInstanceOf(IllegalStateException.class); + assertThat(client.read(request).terminalEvidence().orElseThrow().canonicalBytes()) + .isEqualTo(retained); + } + for (var identity : + java.util.List.of(pki.wrongCallerService(), pki.wrongCallerNamespace())) { + try (var client = + publicationReadClient( + server, + identity, + pki.ca(), + directory.resolve("owner-" + ownerIndex + "-" + identity.label()))) { + client.init(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + e -> { + assertThat(Status.fromThrowable(e).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(TlsTestSupport.isTlsHandshakeRejection(e)).isFalse(); + }); + } + } + assertThat(headers).hasValue(5); + } finally { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + for (var wrongServer : + java.util.List.of(pki.wrongServerService(), pki.wrongServerNamespace())) { + var deniedHeaders = new AtomicInteger(); + var deniedServer = + publicationReadServer( + fixture, wrongServer, pki.ca(), deniedHeaders, new AtomicBoolean(false)); + try (var client = + publicationReadClient( + deniedServer, + pki.account(), + pki.ca(), + directory.resolve("owner-" + ownerIndex + "-" + wrongServer.label()))) { + client.init(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + e -> { + assertThat(Status.fromThrowable(e).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(TlsTestSupport.isTlsHandshakeRejection(e)).isFalse(); + }); + assertThat(deniedHeaders).hasValue(0); + } finally { + deniedServer.shutdownNow(); + assertThat(deniedServer.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + assertThat( + fixture + .service() + .readExact(fixture.operation()) + .orElseThrow() + .terminalEvidenceBytes()) + .isEqualTo(retained); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().receiptBytes()) + .isEqualTo(original.receiptBytes()); + ownerIndex++; + } + } + + private Server publicationReadServer( + Fixture fixture, + TestCertificate identity, + X509Certificate ca, + AtomicInteger headers, + AtomicBoolean loseResponse) + throws Exception { + ServerInterceptor responseLoss = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + headers.incrementAndGet(); + return next.startCall( + new ForwardingServerCall.SimpleForwardingServerCall<>(call) { + private boolean dropped; + + @Override + public void sendMessage(RespT message) { + if (loseResponse.compareAndSet(true, false)) dropped = true; + else super.sendMessage(message); + } + + @Override + public void close(Status status, Metadata trailers) { + super.close( + dropped + ? Status.UNAVAILABLE.withDescription( + "ISOLATED lost terminal read response") + : status, + trailers); + } + }, + metadata); + } + }; + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(ca) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + new GameDesignPublicationTerminalReadGrpcService(fixture.service(), "test"), + responseLoss, + new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GameDesignPublicationTerminalClient publicationReadClient( + Server server, TestCertificate identity, X509Certificate ca, Path directory) + throws Exception { + Files.createDirectories(directory); + var tls = new CommonGrpcClientProperties(); + tls.setCertChain( + publicationReadPem( + directory.resolve("client.crt"), "CERTIFICATE", identity.certificate().getEncoded()) + .toString()); + tls.setPrivateKey( + publicationReadPem( + directory.resolve("client.key"), "PRIVATE KEY", identity.privateKey().getEncoded()) + .toString()); + tls.setCaCert( + publicationReadPem(directory.resolve("ca.crt"), "CERTIFICATE", ca.getEncoded()).toString()); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + server.getPort()); + return new GameDesignPublicationTerminalClient( + endpoints, tls, new GrpcChannelFactory(), "test"); + } + + private static Path publicationReadPem(Path path, String type, byte[] bytes) throws Exception { + Files.writeString( + path, + "-----BEGIN " + + type + + "-----\n" + + Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes) + + "\n-----END " + + type + + "-----\n"); + return path; + } + + private static TestPki publicationReadPki() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) + Security.addProvider(new BouncyCastleProvider()); + var keys = publicationReadKeyPair(); + var name = new X500Name("CN=Game Design PostgreSQL Terminal Test CA, O=FireMUD Test"); + var ca = + publicationReadCertificate(name, keys.getPublic(), name, keys.getPrivate(), true, null); + return new TestPki( + ca, + publicationReadLeaf( + name, keys.getPrivate(), "server", "spiffe://firemud/ns/test/sa/game-design-service"), + publicationReadLeaf( + name, keys.getPrivate(), "account", "spiffe://firemud/ns/test/sa/account-service"), + publicationReadLeaf( + name, + keys.getPrivate(), + "wrong-caller-service", + "spiffe://firemud/ns/test/sa/game-session-service"), + publicationReadLeaf( + name, + keys.getPrivate(), + "wrong-caller-namespace", + "spiffe://firemud/ns/other/sa/account-service"), + publicationReadLeaf( + name, + keys.getPrivate(), + "wrong-server-service", + "spiffe://firemud/ns/test/sa/world-management-service"), + publicationReadLeaf( + name, + keys.getPrivate(), + "wrong-server-namespace", + "spiffe://firemud/ns/other/sa/game-design-service")); + } + + private static TestCertificate publicationReadLeaf( + X500Name ca, PrivateKey issuerKey, String label, String uri) throws Exception { + var keys = publicationReadKeyPair(); + var names = + new GeneralNames( + new GeneralName[] { + new GeneralName(GeneralName.uniformResourceIdentifier, uri), + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + }); + return new TestCertificate( + label, + keys.getPrivate(), + publicationReadCertificate( + new X500Name("CN=" + label + ", O=FireMUD Test"), + keys.getPublic(), + ca, + issuerKey, + false, + names)); + } + + private static X509Certificate publicationReadCertificate( + X500Name subject, + java.security.PublicKey key, + X500Name issuer, + PrivateKey issuerKey, + boolean ca, + GeneralNames names) + throws Exception { + var start = Instant.now().minusSeconds(60); + var builder = + new JcaX509v3CertificateBuilder( + issuer, + BigInteger.valueOf(TEST_CERTIFICATE_SERIAL.getAndIncrement()), + Date.from(start), + Date.from(start.plusSeconds(60L * 60L * 24L * 14L)), + subject, + key); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca)); + builder.addExtension( + Extension.keyUsage, + true, + new KeyUsage( + ca + ? KeyUsage.keyCertSign | KeyUsage.cRLSign + : KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + if (!ca) { + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + new KeyPurposeId[] {KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth})); + builder.addExtension(Extension.subjectAlternativeName, false, names); + } + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuerKey))); + } + + private static KeyPair publicationReadKeyPair() throws Exception { + var generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private record TestCertificate( + String label, PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate ca, + TestCertificate server, + TestCertificate account, + TestCertificate wrongCallerService, + TestCertificate wrongCallerNamespace, + TestCertificate wrongServerService, + TestCertificate wrongServerNamespace) {} + + @Test + void authenticatedTerminalReadDispatchesActualStoredPublishedAndNoPublicationEvidence() + throws Exception { + for (boolean published : java.util.List.of(true, false)) { + var fixture = fixture(); + if (published) publish(fixture); + else noPublication(fixture); + var expected = + fixture.service().readExact(fixture.operation()).orElseThrow().terminalEvidenceBytes(); + var request = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + "test", fixture.operation().canonicalBytes()); + for (String peer : java.util.List.of("account-service", "world-management-service")) { + var result = readThroughHandler(fixture, request, peer); + assertThat(result.error).isNull(); + var evidence = + GameDesignPublicationTerminalReadGrpcCodec.fromResponse(request, result.response); + assertThat(evidence.terminalEvidence().orElseThrow().canonicalBytes()).isEqualTo(expected); + assertThat(evidence.status().name()).isEqualTo(published ? "PUBLISHED" : "NO_PUBLICATION"); + } + } + } + + @Test + void authenticatedTerminalReadReturnsUnknownOnlyForAbsentOrPendingOperation() throws Exception { + var fixture = fixture(); + var pending = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + "test", fixture.operation().canonicalBytes()); + var result = readThroughHandler(fixture, pending, "world-management-service"); + var evidence = + GameDesignPublicationTerminalReadGrpcCodec.fromResponse(pending, result.response); + assertThat(evidence.status()) + .isEqualTo(GameDesignPublicationTerminalReadEvidence.Status.UNKNOWN); + assertThat(evidence.terminalEvidence()).isEmpty(); + var absentOperation = + IsolatedPublicationOperationFixtures.fresh( + fixture.operation().account().input().selection().target()); + var absent = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + "test", absentOperation.canonicalBytes()); + var absentResult = readThroughHandler(fixture, absent, "account-service"); + assertThat( + GameDesignPublicationTerminalReadGrpcCodec.fromResponse(absent, absentResult.response) + .status()) + .isEqualTo(GameDesignPublicationTerminalReadEvidence.Status.UNKNOWN); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().outcome()) + .isEqualTo("PENDING"); + } + + @Test + void retainedV50TerminalReadFailsPreconditionWithoutBackfillingEvidenceOrEpoch() + throws Exception { + var fixture = fixture("50"); + var op = fixture.operation(); + var old = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(old, "game-design-publication-owner-readback/v1"); + DraftAuthorizationFenceBinding.frame(old, op.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(old, "NO_PUBLICATION"); + DraftAuthorizationFenceBinding.frame(old, ""); + fixture + .write() + .executeWithoutResult( + status -> { + var attempt = + fixture + .attempts() + .findByPublishWorkflowIdForUpdate(op.workflowId()) + .orElseThrow(); + attempt.setStatus(PublishAttemptStatus.FAILED); + fixture.attempts().save(attempt); + fixture + .dsl() + .execute( + "UPDATE game_design_publication_operation SET outcome = 'NO_PUBLICATION', revision = revision + 1, result_bytes = ? WHERE publish_workflow_id = ?", + old.toByteArray(), + op.workflowId()); + }); + fixture.completeMigration().run(); + var request = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create("test", op.canonicalBytes()); + var result = readThroughHandler(fixture, request, "account-service"); + assertThat(result.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(result.response).isNull(); + var retained = fixture.service().readExact(op).orElseThrow(); + assertThat(retained.receiptBytes()).isEqualTo(old.toByteArray()); + assertThat(retained.terminalEvidenceBytes()).isNull(); + assertThat( + java.util.Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT publication_version_state_epoch FROM game_design_publication_operation WHERE publish_workflow_id = ?", + op.workflowId())) + .get(0)) + .isNull(); + } + + private ReadCollector readThroughHandler( + Fixture fixture, + GameDesignPublicationTerminalReadEvidence.ReadRequest request, + String service) { + var handler = new GameDesignPublicationTerminalReadGrpcService(fixture.service(), "test"); + var collector = new ReadCollector(); + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity("spiffe://firemud/ns/test/sa/" + service, "test", service)); + var previous = context.attach(); + try { + handler.readGameDesignPublicationTerminal( + GameDesignPublicationTerminalReadGrpcCodec.toRequest(request), collector); + } finally { + context.detach(previous); + } + return collector; + } + + private static final class ReadCollector + implements StreamObserver { + private ReadGameDesignPublicationTerminalResponse response; + private Status.Code error; + + @Override + public void onNext(ReadGameDesignPublicationTerminalResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() {} + } @Test void noPublicationReceiptReplaysAfterLostResponseAndExcludesDelayedFinalizerAndRawInsert() @@ -57,6 +576,12 @@ void noPublicationReceiptReplaysAfterLostResponseAndExcludesDelayedFinalizerAndR noPublication(fixture); var original = fixture.service().readExact(fixture.operation()).orElseThrow(); assertThat(original.outcome()).isEqualTo("NO_PUBLICATION"); + var noPublication = + GameDesignPublicationTerminalEvidence.fromStored(original.terminalEvidenceBytes()); + assertThat(noPublication.outcome()) + .isEqualTo(GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); + assertThatThrownBy(noPublication::publicationVersionStateEpoch) + .isInstanceOf(IllegalStateException.class); assertThat(fixture.service().retainVerifiedOperation(fixture.operation()).receiptBytes()) .isEqualTo(original.receiptBytes()); assertThatThrownBy( @@ -87,6 +612,132 @@ void noPublicationReceiptReplaysAfterLostResponseAndExcludesDelayedFinalizerAndR .isEqualTo(original.receiptBytes()); } + @Test + void terminalEvidenceKeepsOriginalCommittedEpochAfterLaterVersionTransition() throws Exception { + var fixture = fixture(); + publish(fixture); + var original = fixture.service().readExact(fixture.operation()).orElseThrow(); + var terminal = + GameDesignPublicationTerminalEvidence.fromStored(original.terminalEvidenceBytes()); + long captured = terminal.publicationVersionStateEpoch(); + assertThat(captured).isEqualTo(fixture.operation().world().request().versionStateEpoch() + 1); + assertThat(terminal.operationBytes()).isEqualTo(fixture.operation().canonicalBytes()); + fixture + .write() + .executeWithoutResult( + status -> { + var version = + fixture + .versions() + .findByTenantIdAndIdForUpdate( + fixture.operation().tenantKey(), fixture.operation().versionId()) + .orElseThrow(); + version.setVersionState(VersionLifecycleState.RETIRED); + version.setVersionStateEpoch(captured + 1); + fixture.versions().save(version); + }); + var replay = fixture.service().readExact(fixture.operation()).orElseThrow(); + assertThat(replay.terminalEvidenceBytes()).isEqualTo(original.terminalEvidenceBytes()); + assertThat( + GameDesignPublicationTerminalEvidence.fromStored(replay.terminalEvidenceBytes()) + .publicationVersionStateEpoch()) + .isEqualTo(captured); + } + + @Test + void terminalExtensionRefusesRawEpochDigestBytesAndReleaseContentSubstitution() throws Exception { + var fixture = fixture(); + publish(fixture); + var original = fixture.service().readExact(fixture.operation()).orElseThrow(); + for (String assignment : + java.util.List.of( + "publication_version_state_epoch = publication_version_state_epoch + 1", + "published_release_bundle_digest = 'sha256:' || repeat('f', 64)", + "terminal_evidence_bytes = terminal_evidence_bytes || decode('00', 'hex')", + "release_content_bytes = release_content_bytes || decode('00', 'hex')")) { + assertThatThrownBy( + () -> + fixture + .write() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "UPDATE game_design_publication_operation SET " + + assignment + + " WHERE publish_workflow_id = ?", + fixture.operation().workflowId()))) + .isInstanceOf(RuntimeException.class); + } + assertThatThrownBy( + () -> + fixture + .write() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "UPDATE published_release_bundle SET generation_config_revision = 'changed' WHERE tenant_id = ? AND version_id = ?", + fixture.operation().tenantKey(), + fixture.operation().versionId()))) + .isInstanceOf(RuntimeException.class); + assertThat( + fixture.service().readExact(fixture.operation()).orElseThrow().terminalEvidenceBytes()) + .isEqualTo(original.terminalEvidenceBytes()); + } + + @Test + void originalSealRejectsForgedCommittedEpochAndPreservesPendingOwnerRows() throws Exception { + for (String forgedField : java.util.List.of("epoch", "digest", "content", "terminal")) { + var fixture = fixture(); + assertThatThrownBy( + () -> + fixture + .write() + .executeWithoutResult( + status -> { + publishInTransaction(fixture, false); + rawTerminalSeal(fixture, forgedField); + })) + .isInstanceOf(RuntimeException.class); + var pending = fixture.service().readExact(fixture.operation()).orElseThrow(); + assertThat(pending.outcome()).isEqualTo("PENDING"); + assertThat(pending.terminalEvidenceBytes()).isNull(); + publish(fixture); + assertThat( + fixture + .service() + .readExact(fixture.operation()) + .orElseThrow() + .terminalEvidenceBytes()) + .isNotNull(); + } + } + + @Test + void publicationSealEpochMustRemainTheActualVersionEpochThroughCommit() throws Exception { + var fixture = fixture(); + assertThatThrownBy( + () -> + fixture + .write() + .executeWithoutResult( + status -> { + publishInTransaction(fixture); + fixture + .dsl() + .execute( + "UPDATE version SET version_state_epoch = version_state_epoch + 1 WHERE tenant_id = ? AND id = ?", + fixture.operation().tenantKey(), + fixture.operation().versionId()); + })) + .isInstanceOf(RuntimeException.class); + assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().outcome()) + .isEqualTo("PENDING"); + } + @Test void publishedReceiptCannotBeDemotedByStaleFailureAndRetainsOriginalFreezeEpoch() throws Exception { @@ -220,6 +871,10 @@ private void publish(Fixture fixture) { } private void publishInTransaction(Fixture fixture) { + publishInTransaction(fixture, true); + } + + private void publishInTransaction(Fixture fixture, boolean seal) { var op = fixture.operation(); fixture .operations() @@ -249,9 +904,52 @@ private void publishInTransaction(Fixture fixture) { fixture.attempts().findByPublishWorkflowIdForUpdate(op.workflowId()).orElseThrow(); attempt.setStatus(PublishAttemptStatus.SUCCEEDED); fixture.attempts().save(attempt); + if (seal) + fixture + .operations() + .seal(op.tenantKey(), op.workflowId(), op.versionId(), op.selectionDigest(), true); + } + + /** + * Attempts a raw first seal, so failures prove content/epoch binding rather than only + * immutability. + */ + private void rawTerminalSeal(Fixture fixture, String forgedField) { + var op = fixture.operation(); + var row = + java.util.Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT to_jsonb(r)::TEXT AS evidence, publication_release_content(r) AS content, 'sha256:' || encode(sha256(publication_release_content(r)), 'hex') AS digest FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", + op.tenantKey(), + op.versionId())); + String evidence = row.get("evidence", String.class); + byte[] content = row.get("content", byte[].class); + String digest = row.get("digest", String.class); + long epoch = op.world().request().versionStateEpoch() + 1; + var old = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(old, "game-design-publication-owner-readback/v1"); + DraftAuthorizationFenceBinding.frame(old, op.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(old, "PUBLISHED"); + DraftAuthorizationFenceBinding.frame(old, evidence); + var terminal = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(terminal, "game-design-publication-terminal/v1"); + DraftAuthorizationFenceBinding.frame(terminal, op.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(terminal, "PUBLISHED"); + DraftAuthorizationFenceBinding.frame(terminal, content); + DraftAuthorizationFenceBinding.frame(terminal, Long.toString(epoch)); fixture - .operations() - .seal(op.tenantKey(), op.workflowId(), op.versionId(), op.selectionDigest(), true); + .dsl() + .execute( + "UPDATE game_design_publication_operation SET outcome = 'PUBLISHED', revision = revision + 1, result_bytes = ?, release_row_json = ?, terminal_evidence_bytes = ?, publication_version_state_epoch = ?, release_content_bytes = ?, published_release_bundle_digest = ? WHERE publish_workflow_id = ?", + old.toByteArray(), + evidence, + forgedField.equals("terminal") ? new byte[] {1} : terminal.toByteArray(), + forgedField.equals("epoch") ? epoch + 1 : epoch, + forgedField.equals("content") ? new byte[] {1} : content, + forgedField.equals("digest") ? "sha256:" + "f".repeat(64) : digest, + op.workflowId()); } private PublishedReleaseBundle bundle(Fixture fixture) { @@ -301,6 +999,10 @@ private void rawReleaseInsert(Fixture fixture) { } private Fixture fixture() throws Exception { + return fixture("51"); + } + + private Fixture fixture(String migrationTarget) throws Exception { String schema = "gd_pub_op_" + UUID.randomUUID().toString().replace("-", ""); var source = new DriverManagerDataSource( @@ -313,6 +1015,7 @@ private Fixture fixture() throws Exception { .placeholders(java.util.Map.of("serviceSchema", schema)) .locations("classpath:db/migration") .table("flyway_schema_history_game_design_service") + .target(migrationTarget) .load() .migrate(); var transactions = new DataSourceTransactionManager(source); @@ -375,7 +1078,17 @@ private Fixture fixture() throws Exception { new VersionAssetArtifactRepository(dsl), operations, new GameDesignPublicationOperationService(operations, transactions), - operation); + operation, + () -> + 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()); } private static void await(CountDownLatch latch) { @@ -397,5 +1110,6 @@ private record Fixture( VersionAssetArtifactRepository artifacts, GameDesignPublicationOperationRepository operations, GameDesignPublicationOperationService service, - GameDesignPublicationOperation operation) {} + GameDesignPublicationOperation operation, + Runnable completeMigration) {} } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadGrpcServiceTest.java new file mode 100644 index 0000000000..b3726a332d --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadGrpcServiceTest.java @@ -0,0 +1,208 @@ +package unit.net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +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.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +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.publication.GameDesignPublicationTerminalReadGrpcService; +import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalRequest; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalResponse; +import org.junit.jupiter.api.Test; + +/** Adapter proof only: owner source and peer identity are labeled isolated doubles. */ +class GameDesignPublicationTerminalReadGrpcServiceTest { + @Test + void rejectsMissingWrongServiceNamespaceAndEndUserBeforeDecodeOrOwnerRead() { + var owner = mock(GameDesignPublicationOperationService.class); + var handler = new GameDesignPublicationTerminalReadGrpcService(owner, "test"); + var malformed = + ReadGameDesignPublicationTerminalRequest.newBuilder() + .setCanonicalRequestBytes(ByteString.copyFromUtf8("malformed")) + .build(); + assertThat(call(handler, malformed, null).error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(call(handler, malformed, peer("game-session-service", "test")).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(call(handler, malformed, peer("account-service", "other")).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.setContext("11111111-1111-4111-8111-111111111111", List.of(), Map.of()); + try { + assertThat(call(handler, malformed, peer("account-service", "test")).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + verifyNoInteractions(owner); + } + + @Test + void malformedAuthenticatedInputCannotReadOwnerStorage() { + var owner = mock(GameDesignPublicationOperationService.class); + var handler = new GameDesignPublicationTerminalReadGrpcService(owner, "test"); + assertThat( + call( + handler, + ReadGameDesignPublicationTerminalRequest.getDefaultInstance(), + peer("world-management-service", "test")) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner); + } + + @Test + void exactAllowedPeersReceiveOnlyUnknownPendingOrUnchangedStoredNoPublication() throws Exception { + var operation = operation(); + var request = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + "test", operation.canonicalBytes()); + var terminal = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION, + null, + null); + for (Optional stored : + List.of( + Optional.empty(), + Optional.of( + new GameDesignPublicationOperationRepository.Readback(operation, "PENDING", null)), + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + operation, "NO_PUBLICATION", new byte[] {1}, terminal.canonicalBytes())))) { + var owner = mock(GameDesignPublicationOperationService.class); + when(owner.readExact(any())).thenReturn(stored); + var handler = new GameDesignPublicationTerminalReadGrpcService(owner, "test"); + for (String service : List.of("account-service", "world-management-service")) { + var response = + call( + handler, + GameDesignPublicationTerminalReadGrpcCodec.toRequest(request), + peer(service, "test")); + assertThat(response.error).isNull(); + var result = + GameDesignPublicationTerminalReadGrpcCodec.fromResponse(request, response.response); + if (stored.isEmpty() || stored.orElseThrow().outcome().equals("PENDING")) { + assertThat(result.status()) + .isEqualTo(GameDesignPublicationTerminalReadEvidence.Status.UNKNOWN); + assertThat(result.terminalEvidence()).isEmpty(); + } else + assertThat(result.terminalEvidence().orElseThrow().canonicalBytes()) + .isEqualTo(terminal.canonicalBytes()); + } + } + } + + @Test + void unavailableCorruptAndHistoricalOwnerReadCannotInventUnknownOrTerminalEvidence() + throws Exception { + var operation = operation(); + var request = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + "test", operation.canonicalBytes()); + var owner = mock(GameDesignPublicationOperationService.class); + var handler = new GameDesignPublicationTerminalReadGrpcService(owner, "test"); + when(owner.readExact(any())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + operation, "NO_PUBLICATION", new byte[] {1}))); + var historical = + call( + handler, + GameDesignPublicationTerminalReadGrpcCodec.toRequest(request), + peer("account-service", "test")); + assertThat(historical.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(historical.response).isNull(); + doThrow(new org.jooq.exception.DataAccessException("ISOLATED unavailable")) + .when(owner) + .readExact(any()); + assertThat( + call( + handler, + GameDesignPublicationTerminalReadGrpcCodec.toRequest(request), + peer("account-service", "test")) + .error) + .isEqualTo(Status.Code.UNAVAILABLE); + doThrow(new IllegalStateException("ISOLATED conflicting evidence")) + .when(owner) + .readExact(any()); + assertThat( + call( + handler, + GameDesignPublicationTerminalReadGrpcCodec.toRequest(request), + peer("account-service", "test")) + .error) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } + + static GameDesignPublicationOperation operation() throws Exception { + return IsolatedPublicationOperationFixtures.fresh( + 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 GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static Collector call( + GameDesignPublicationTerminalReadGrpcService handler, + ReadGameDesignPublicationTerminalRequest request, + GrpcPeerIdentity peer) { + var collector = new Collector(); + var context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + var previous = context.attach(); + try { + handler.readGameDesignPublicationTerminal(request, collector); + } finally { + context.detach(previous); + } + return collector; + } + + private static final class Collector + implements StreamObserver { + private ReadGameDesignPublicationTerminalResponse response; + private Status.Code error; + + @Override + public void onNext(ReadGameDesignPublicationTerminalResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() {} + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadMtlsTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadMtlsTest.java new file mode 100644 index 0000000000..ee25e16912 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadMtlsTest.java @@ -0,0 +1,306 @@ +package unit.net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import java.math.BigInteger; +import java.net.InetSocketAddress; +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.Date; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationService; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationTerminalReadGrpcService; +import net.firedevops.firemud.gamedesign.v1.GameDesignPublicationTerminalReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalRequest; +import net.firedevops.firemud.test.TlsTestSupport; +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; + +/** + * Physical authenticated handler proof only: original authority and owner service are isolated + * doubles. + */ +class GameDesignPublicationTerminalReadMtlsTest { + private static final String NAMESPACE = "test"; + private static final String SERVER_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1); + private static TestPki pki; + + @BeforeAll + static void generateEphemeralPki() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) + Security.addProvider(new BouncyCastleProvider()); + var pair = newRsaKeyPair(); + var name = new X500Name("CN=Publication Terminal Test CA, O=FireMUD Test"); + var ca = issueCertificate(name, pair.getPublic(), name, pair.getPrivate(), true); + pki = + new TestPki( + ca, + issueLeaf(name, pair.getPrivate(), "game-design-server", SERVER_URI), + issueLeaf( + name, + pair.getPrivate(), + "account-client", + "spiffe://firemud/ns/test/sa/account-service"), + issueLeaf( + name, + pair.getPrivate(), + "world-client", + "spiffe://firemud/ns/test/sa/world-management-service"), + issueLeaf( + name, + pair.getPrivate(), + "wrong-service", + "spiffe://firemud/ns/test/sa/game-session-service"), + issueLeaf( + name, + pair.getPrivate(), + "wrong-namespace", + "spiffe://firemud/ns/other/sa/account-service")); + } + + @Test + void trustedWrongCallerServiceAndNamespaceAreRejectedBeforeMalformedDecodeOrOwnerRead() + throws Exception { + var owner = mock(GameDesignPublicationOperationService.class); + var server = server(owner); + try { + for (var identity : List.of(pki.wrongService(), pki.wrongNamespace())) { + var channel = channel(server, identity); + try { + var malformed = + ReadGameDesignPublicationTerminalRequest.newBuilder() + .setCanonicalRequestBytes(ByteString.copyFromUtf8("malformed")) + .build(); + assertThatThrownBy(() -> stub(channel).readGameDesignPublicationTerminal(malformed)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + e -> { + assertThat(Status.fromThrowable(e).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(TlsTestSupport.isTlsHandshakeRejection(e)).isFalse(); + }); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + verifyNoInteractions(owner); + } finally { + stopServer(server); + } + } + + @Test + void exactAccountAndWorldPhysicalPeersReceiveUnchangedTerminalFromIsolatedOwnerSource() + throws Exception { + var op = GameDesignPublicationTerminalReadGrpcServiceTest.operation(); + var request = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + NAMESPACE, op.canonicalBytes()); + var terminal = + new GameDesignPublicationTerminalEvidence( + op.canonicalBytes(), + GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION, + null, + null); + var owner = mock(GameDesignPublicationOperationService.class); + when(owner.readExact(any())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + op, "NO_PUBLICATION", new byte[] {1}, terminal.canonicalBytes()))); + var server = server(owner); + try { + for (var identity : List.of(pki.account(), pki.world())) { + var channel = channel(server, identity); + try { + var response = + stub(channel) + .readGameDesignPublicationTerminal( + GameDesignPublicationTerminalReadGrpcCodec.toRequest(request)); + assertThat( + GameDesignPublicationTerminalReadGrpcCodec.fromResponse(request, response) + .terminalEvidence() + .orElseThrow() + .canonicalBytes()) + .isEqualTo(terminal.canonicalBytes()); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + } finally { + stopServer(server); + } + } + + private static Server server(GameDesignPublicationOperationService owner) throws Exception { + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.server().privateKey(), pki.server().certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + new GameDesignPublicationTerminalReadGrpcService(owner, NAMESPACE), + new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private static ManagedChannel channel(Server server, TestCertificate identity) throws Exception { + return NettyChannelBuilder.forAddress("localhost", server.getPort()) + .sslContext( + GrpcSslContexts.forClient() + .trustManager(pki.caCertificate()) + .keyManager(identity.privateKey(), identity.certificate()) + .build()) + .build(); + } + + private static GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceBlockingStub + stub(ManagedChannel channel) { + return GameDesignPublicationTerminalReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(SERVER_URI)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(SERVER_URI)) + .withDeadlineAfter(5, TimeUnit.SECONDS); + } + + 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 record TestCertificate(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestCertificate server, + TestCertificate account, + TestCertificate world, + TestCertificate wrongService, + TestCertificate wrongNamespace) {} +} 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 9d480111e0..5b557cca27 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 @@ -13,6 +13,9 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.world.RoomTemplateRef; import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopology.Request; @@ -435,6 +438,137 @@ private void requireExactOriginalBindings(Input input) { throw new InvalidPreparationEvidenceException( "Canonical preparation V27 Version/source evidence differs from its original immutable row"); } + requireExactPublishedTerminal(input); + } + + /** A fresh preparation consumes only the exact retained PUBLISHED terminal release. */ + private void requireExactPublishedTerminal(Input input) { + var source = input.topologyPlan().sourceBinding(); + var release = input.completeLaunchBinding().evidence().releaseAttestation(); + var selector = release.worldStartLocationEvidence(); + if (selector == null) { + throw new InvalidPreparationEvidenceException( + "Fresh canonical preparation requires the complete published World selector terminal"); + } + Record row = + dsl.fetchOne( + "SELECT * " + "FROM world_design_publication_terminal WHERE publication_fence=?", + source.freeze().publicationFence()); + if (row == null || !"PUBLISHED".equals(required(row, "outcome", String.class))) { + throw new InvalidPreparationEvidenceException( + "Fresh canonical preparation requires an exact PUBLISHED World owner terminal"); + } + byte[] terminalBytes = required(row, "terminal_evidence_bytes", byte[].class); + String terminalDigest = required(row, "terminal_evidence_digest", String.class); + if (!digest(terminalBytes).substring("sha256:".length()).equals(terminalDigest)) { + throw new InvalidPreparationEvidenceException( + "Retained Game Design terminal evidence digest differs from its immutable bytes"); + } + final GameDesignPublicationTerminalEvidence terminal; + try { + terminal = GameDesignPublicationTerminalEvidence.fromStored(terminalBytes); + } catch (IllegalArgumentException invalid) { + throw new InvalidPreparationEvidenceException( + "Retained Game Design terminal evidence is not canonical", invalid); + } + var terminalRequest = new WorldPublicationTerminal.Request(terminal); + var worldRequest = selector.request(); + if (terminal.outcome() != GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + || !worldRequest.publicationFence().equals(required(row, "publication_fence", UUID.class)) + || !worldRequest.targetNamespace().equals(required(row, "target_namespace", String.class)) + || !worldRequest + .canonicalTenantId() + .equals(required(row, "canonical_tenant_id", UUID.class)) + || !worldRequest + .canonicalVersionId() + .equals(required(row, "canonical_version_id", UUID.class)) + || !worldRequest + .publicationRequestId() + .equals(required(row, "publication_request_id", String.class)) + || !worldRequest.requestDigest().equals(required(row, "request_digest", String.class)) + || !worldRequest + .publishWorkflowId() + .equals(required(row, "publish_workflow_id", String.class)) + || worldRequest.versionStateEpoch() + != required(row, "freeze_version_state_epoch", Long.class) + || !worldRequest.appliedCommitId().equals(required(row, "applied_commit_id", String.class)) + || !worldRequest.contentDigest().equals(required(row, "content_digest", String.class)) + || worldRequest.digestSchemaVersion() + != required(row, "digest_schema_version", Integer.class) + || !terminalRequest + .releaseBundleRef() + .equals(required(row, "published_release_bundle_ref", String.class)) + || !terminalRequest + .releaseBundleDigest() + .equals(required(row, "published_release_bundle_digest", String.class)) + || !Objects.equals( + terminalRequest.publicationVersionStateEpoch(), + required(row, "publication_version_state_epoch", Long.class)) + || !Arrays.equals( + terminalRequest.operationBytes(), required(row, "operation_bytes", byte[].class)) + || !Arrays.equals( + terminalRequest.worldEvidenceBytes(), + required(row, "world_evidence_bytes", byte[].class)) + || !Arrays.equals( + terminalRequest.releaseContentBytes(), + required(row, "release_content_bytes", byte[].class)) + || !Arrays.equals(terminal.worldEvidence().canonicalBytes(), selector.canonicalBytes())) { + throw new InvalidPreparationEvidenceException( + "Retained terminal differs from the complete original World selector evidence"); + } + requireExactPublishedRelease(terminal, release); + } + + private static void requireExactPublishedRelease( + GameDesignPublicationTerminalEvidence terminal, + AuthoredWorldReleaseAttestationEvidence release) { + var bundle = terminal.releaseContent(); + if (release.schemaVersion() != AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION + || !bundle.canonicalTenantId().equals(release.canonicalTenantId()) + || !bundle.canonicalVersionId().equals(release.canonicalVersionId()) + || !bundle.publishedReleaseBundleRef().equals(release.publishedReleaseBundleRef()) + || terminal.publicationVersionStateEpoch() != release.versionStateEpoch() + || !bundle.publishWorkflowId().equals(release.publishWorkflowId()) + || !bundle + .publishWorkflowId() + .equals(terminal.worldEvidence().request().publishWorkflowId()) + || !terminal.worldEvidence().request().appliedCommitId().equals(release.commitId()) + || !bundle.manifestHash().equals(release.manifestHash()) + || bundle.manifestSchemaVersion() != release.manifestSchemaVersion() + || !bundle.requiredManifestAssetKeys().equals(release.requiredManifestAssetKeys()) + || !bundle.artifactDigests().equals(release.artifactDigests()) + || !bundle.commandDefinitions().equals(release.commandDefinitions()) + || !bundle.generationConfigRevision().equals(release.generationConfigRevision()) + || !matchesPublishedParticipants( + bundle.participantDigests(), release.participantDigests())) { + throw new InvalidPreparationEvidenceException( + "Retained terminal ReleaseContent differs from the exact immutable launch release binding"); + } + } + + private static boolean matchesPublishedParticipants( + java.util.List terminal, + java.util.List release) { + if (terminal.size() != AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().size() + || release.size() != terminal.size()) return false; + for (int index = 0; index < terminal.size(); index++) { + var actual = terminal.get(index); + var expected = release.get(index); + if (!actual.participantKey().equals(expected.participantKey()) + || !actual.scopeValue().equals(expected.scopeValue()) + || !Objects.equals( + actual.baseVersionId(), + expected.baseVersionIdPresent() ? expected.baseVersionId() : null) + || !actual.appliedCommitId().equals(expected.appliedCommitId()) + || !actual.contentDigest().equals(expected.contentDigest()) + || actual.digestSchemaVersion() != expected.digestSchemaVersion() + || !Objects.equals( + actual.abilitySchemaDigest(), + expected.abilitySchemaDigestPresent() ? expected.abilitySchemaDigest() : null) + || actual.errorCode() != null && !actual.errorCode().isEmpty() + || actual.errorMessage() != null) return false; + } + return true; } static String inputJson(Input input) { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java index a5a50bb112..d9437201b9 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java @@ -9,10 +9,11 @@ * Unregistered, default-denied owner operation for a canonical generation-free world instance. * *

No production verifier is supplied in this slice. A future authenticated integration must - * verify the same-namespace Game Session producer, current Game Design release and source, applied - * participant state, and Account commit authority before the World transaction begins. Its held - * authority must stay valid until the transaction manager has committed. This class is deliberately - * not a Spring component and adds no RPC or public activation path. + * verify the same-namespace Game Session producer and exact current Game Design release/terminal + * source before the World transaction begins. The original Account-authorized APPLIED result is + * immutable input evidence; preparation must not reauthorize the creator or reuse Draft/publication + * permission. Its held producer evidence must remain valid through commit. This class is + * deliberately not a Spring component and adds no RPC or public activation path. */ public final class WorldCanonicalInstancePreparationService { private final WorldCanonicalInstancePreparationRepository repository; @@ -55,22 +56,22 @@ public Result prepare(Input input) { private static HeldCommitAuthority denyByDefault(Input input) { throw new PreparationDeniedException( - "Canonical World preparation has no authenticated source/release and Account commit verifier"); + "Canonical World preparation has no authenticated source/release terminal verifier"); } - /** Performs remote/current-state checks before returning a continuously held local fence. */ + /** Performs authenticated producer checks before returning a continuously held local fence. */ @FunctionalInterface public interface CommitAuthorityVerifier { HeldCommitAuthority verifyAndHold(Input input); } /** - * A verifier-owned, continuously held authority/fence handle. It stays open throughout the World - * transaction and its commit; implementations must fail closed from {@link #requireHeld()} if - * current authority has been lost or is no longer effective. Remote/current-state checks happen - * before the World transaction; {@code requireHeld()} is a local fence/effective-state assertion - * and must never perform RPC while World holds database locks. It is not a time lease and cannot - * extend authority beyond its effective period. + * A verifier-owned, continuously held producer-evidence handle. It stays open throughout the + * World transaction and its commit; implementations must fail closed from {@link #requireHeld()} + * if the evidence they verified is no longer effective. Remote/current-state checks happen before + * the World transaction; {@code requireHeld()} is a local fence/effective-state assertion and + * must never perform RPC while World holds database locks. It is not a new Account creator + * permission. */ public interface HeldCommitAuthority extends AutoCloseable { void requireHeld(); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminal.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminal.java new file mode 100644 index 0000000000..343ea45c12 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminal.java @@ -0,0 +1,110 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import tools.jackson.core.JacksonException; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** Closed, immutable World handoff to the exact Game Design publication terminal result. */ +public final class WorldPublicationTerminal { + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private WorldPublicationTerminal() {} + + /** + * Reconstructs the only accepted terminal carrier; decoding does not authenticate Game Design. + */ + public static Request request(byte[] terminalBytes) { + return new Request(GameDesignPublicationTerminalEvidence.fromStored(terminalBytes)); + } + + public record Request(GameDesignPublicationTerminalEvidence evidence) { + public Request { + Objects.requireNonNull(evidence, "evidence"); + evidence = GameDesignPublicationTerminalEvidence.fromStored(evidence.canonicalBytes()); + } + + public WorldPublishedStartLocationEvidence worldEvidence() { + return evidence.worldEvidence(); + } + + public byte[] terminalBytes() { + return evidence.canonicalBytes(); + } + + public byte[] operationBytes() { + return evidence.operationBytes(); + } + + public byte[] worldEvidenceBytes() { + return evidence.worldEvidence().canonicalBytes(); + } + + public String worldRequestJson() { + try { + JsonNode root = JSON.readTree(worldEvidenceBytes()); + JsonNode request = root == null ? null : root.get("request"); + if (request == null || !request.isObject()) { + throw new IllegalArgumentException("Terminal evidence has no exact World request"); + } + return request.toString(); + } catch (JacksonException invalid) { + throw new IllegalArgumentException( + "Terminal evidence has an invalid World request", invalid); + } + } + + public byte[] originalAccountBindingBytes() { + return worldEvidence().originalAccountBindingBytes(); + } + + public byte[] selectorReceiptBytes() { + return worldEvidence().selectorReceiptBytes(); + } + + public byte[] appliedResultBytes() { + return worldEvidence().appliedResultBytes(); + } + + public byte[] releaseContentBytes() { + return evidence.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? evidence.releaseContent().canonicalBytes() + : new byte[0]; + } + + public String ownerPhase() { + return evidence.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? "PUBLISHED" + : "ABORTED"; + } + + public String releaseBundleRef() { + return evidence.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? evidence.publishedReleaseBundleRef() + : null; + } + + public String releaseBundleDigest() { + return evidence.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? evidence.publishedReleaseBundleDigest() + : null; + } + + public Long publicationVersionStateEpoch() { + return evidence.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? evidence.publicationVersionStateEpoch() + : null; + } + + public static Request fromStored(byte[] bytes) { + return request(bytes); + } + + public boolean exactBytes(byte[] bytes) { + return Arrays.equals(terminalBytes(), bytes); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalClientVerifier.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalClientVerifier.java new file mode 100644 index 0000000000..728488bc7b --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalClientVerifier.java @@ -0,0 +1,60 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.Status; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** + * Explicit, unregistered verifier for authenticated Game Design terminal readback. Construction + * does not initialize or register the transport; the owning composition must deliberately do so. + */ +public final class WorldPublicationTerminalClientVerifier + implements WorldPublicationTerminalService.TerminalAuthorityVerifier { + private final GameDesignPublicationTerminalClient client; + private final String workloadNamespace; + + public WorldPublicationTerminalClientVerifier( + GameDesignPublicationTerminalClient client, String workloadNamespace) { + this.client = Objects.requireNonNull(client, "client"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("World terminal verifier namespace must be canonical"); + } + this.workloadNamespace = workloadNamespace; + } + + @Override + public WorldPublicationTerminalService.VerifiedTerminal authenticateAndVerifyAndHold( + byte[] operationBytes, byte[] terminalBytes) { + Objects.requireNonNull(operationBytes, "operationBytes"); + Objects.requireNonNull(terminalBytes, "terminalBytes"); + ReadRequest request = ReadRequest.create(workloadNamespace, operationBytes); + var response = client.read(request); + if (!Arrays.equals(request.canonicalBytes(), response.request().canonicalBytes()) + || response.status() == Status.UNKNOWN) { + throw new WorldPublicationTerminalService.TerminalDeniedException( + "Game Design has no exact sealed terminal result for this World publication operation"); + } + var evidence = response.terminalEvidence().orElseThrow(); + if (!Arrays.equals(operationBytes, evidence.operationBytes()) + || !Arrays.equals(terminalBytes, evidence.canonicalBytes())) { + throw new WorldPublicationTerminalService.TerminalDeniedException( + "Authenticated Game Design terminal readback differs from the submitted exact evidence"); + } + WorldPublicationTerminal.Request worldRequest = + WorldPublicationTerminal.Request.fromStored(evidence.canonicalBytes()); + return new WorldPublicationTerminalService.VerifiedTerminal( + worldRequest, + new WorldPublicationTerminalService.HeldTerminalAuthority() { + // Game Design terminal evidence is immutable and the remote client authenticated its + // exact operation/result. No RPC or time-limited permission is held under World locks. + @Override + public void requireHeld() {} + + @Override + public void close() {} + }); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalRepository.java new file mode 100644 index 0000000000..500c85b9ee --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalRepository.java @@ -0,0 +1,379 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +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 net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Owner-local immutable terminal receipt and exact FROZEN-to-terminal phase transition. */ +public final class WorldPublicationTerminalRepository { + private static final String TERMINAL_WITH_OWNER_READ = + "SELECT t.*, o.owner_freeze_phase AS joined_owner_phase, " + + "o.current_publication_fence AS joined_owner_current_fence, " + + "a.owner_binding_schema_version AS joined_owner_binding_schema_version, " + + "a.target_namespace AS joined_attempt_target_namespace, " + + "a.canonical_tenant_id AS joined_attempt_canonical_tenant_id, " + + "a.canonical_version_id AS joined_attempt_canonical_version_id, " + + "a.local_tenant_key AS joined_attempt_local_tenant_key, " + + "a.version_id AS joined_attempt_local_version_id, " + + "a.intake_request_id AS joined_attempt_intake_request_id, " + + "a.publication_request_id AS joined_attempt_publication_request_id, " + + "a.request_digest AS joined_attempt_request_digest, " + + "a.version_state_epoch AS joined_attempt_version_state_epoch, " + + "a.publish_workflow_id AS joined_attempt_publish_workflow_id, " + + "a.applied_commit_id AS joined_attempt_applied_commit_id, " + + "a.content_digest AS joined_attempt_content_digest, " + + "a.digest_schema_version AS joined_attempt_digest_schema_version " + + "FROM world_design_publication_terminal t " + + "LEFT JOIN world_design_publication_fence_attempt a " + + "ON a.publication_fence=t.publication_fence " + + "LEFT JOIN world_design_publication_fence_owner o " + + "ON o.target_namespace=a.target_namespace " + + "AND o.canonical_tenant_id=a.canonical_tenant_id " + + "AND o.local_tenant_key=a.local_tenant_key AND o.version_id=a.version_id " + + "WHERE t.publication_fence=?"; + + private final DSLContext dsl; + private final TransactionTemplate ownerTransaction; + + public WorldPublicationTerminalRepository( + DSLContext dsl, PlatformTransactionManager transactionManager) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + /** + * Persists one exact terminal result under the original V25 owner lock. The supplied authority + * was acquired before this call and remains held until the real owner transaction commits. + */ + public GameDesignPublicationTerminalEvidence complete( + WorldPublicationTerminal.Request request, + WorldPublicationTerminalService.HeldTerminalAuthority authority) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(authority, "authority"); + requireNoAmbientTransaction("World publication terminal"); + GameDesignPublicationTerminalEvidence committed = + Objects.requireNonNull( + ownerTransaction.execute( + status -> { + requireWritableReadCommittedTransaction(); + authority.requireHeld(); + Record owner = lockOriginalOwner(request); + Optional prior = + readInOwnerTransaction(request); + if (prior.isPresent()) return prior.orElseThrow(); + if (!"FROZEN".equals(required(owner, "owner_freeze_phase", String.class))) { + throw new PublicationTerminalConflictException( + "World publication fence is no longer open for its first terminal result"); + } + + insertTerminal(request); + String phase = request.ownerPhase(); + int updated = + dsl.execute( + "UPDATE world_design_publication_fence_owner SET owner_freeze_phase=? " + + "WHERE target_namespace=? AND canonical_tenant_id=? " + + "AND local_tenant_key=? AND version_id=? " + + "AND owner_freeze_phase='FROZEN' AND current_publication_fence=?", + phase, + request.worldEvidence().request().targetNamespace(), + request.worldEvidence().request().canonicalTenantId(), + required(owner, "local_tenant_key", Long.class), + required(owner, "version_id", Long.class), + request.worldEvidence().request().publicationFence()); + if (updated != 1) { + throw new PublicationTerminalConflictException( + "World publication terminal lost the exact locked FROZEN owner row"); + } + authority.requireHeld(); + GameDesignPublicationTerminalEvidence readback = + readInOwnerTransaction(request) + .orElseThrow( + () -> + new PublicationTerminalConflictException( + "World publication terminal has no exact immutable readback")); + if (!Arrays.equals(readback.canonicalBytes(), request.terminalBytes())) { + throw new PublicationTerminalConflictException( + "World publication terminal differs from exact inserted evidence"); + } + return readback; + }), + "World publication terminal transaction did not commit"); + + // Confirm committed immutable readback after TransactionTemplate returns from commit. + GameDesignPublicationTerminalEvidence readback = + readCommitted(request) + .orElseThrow( + () -> + new PublicationTerminalConflictException( + "Committed World publication terminal has no independent readback")); + if (!Arrays.equals(committed.canonicalBytes(), readback.canonicalBytes())) { + throw new PublicationTerminalConflictException( + "Committed World publication terminal differs from its owner transaction readback"); + } + return readback; + } + + /** Independent immutable read. Unknown is not interpreted as publication or abort. */ + public Optional readCommitted( + WorldPublicationTerminal.Request request) { + Objects.requireNonNull(request, "request"); + requireNoAmbientTransaction("World publication terminal readback"); + Record row = readTerminalWithOwner(request, false); + if (row == null) return Optional.empty(); + return Optional.of(exactReadback(request, row)); + } + + private Record lockOriginalOwner(WorldPublicationTerminal.Request request) { + var world = request.worldEvidence().request(); + Record row = + dsl.fetchOne( + "SELECT a.*,o.owner_freeze_phase,o.current_publication_fence " + + "FROM world_design_publication_fence_attempt a " + + "JOIN world_design_publication_fence_owner o " + + "ON o.target_namespace=a.target_namespace " + + "AND o.canonical_tenant_id=a.canonical_tenant_id " + + "AND o.local_tenant_key=a.local_tenant_key AND o.version_id=a.version_id " + + "WHERE a.publication_fence=? AND a.target_namespace=? " + + "AND a.canonical_tenant_id=? AND a.canonical_version_id=? " + + "AND o.current_publication_fence=a.publication_fence FOR UPDATE OF o", + world.publicationFence(), + world.targetNamespace(), + world.canonicalTenantId(), + world.canonicalVersionId()); + if (row == null) { + throw new PublicationTerminalConflictException( + "World terminal request has no exact retained V25 attempt and current owner association"); + } + if (!Short.valueOf((short) 1).equals(required(row, "owner_binding_schema_version", Short.class)) + || !world.intakeRequestId().equals(required(row, "intake_request_id", java.util.UUID.class)) + || !world + .publicationFence() + .equals(required(row, "publication_fence", java.util.UUID.class)) + || !world + .publicationRequestId() + .equals(required(row, "publication_request_id", String.class)) + || !world.requestDigest().equals(required(row, "request_digest", String.class)) + || world.versionStateEpoch() != required(row, "version_state_epoch", Long.class) + || !world.publishWorkflowId().equals(required(row, "publish_workflow_id", String.class)) + || !world.appliedCommitId().equals(required(row, "applied_commit_id", String.class)) + || !world.contentDigest().equals(required(row, "content_digest", String.class)) + || world.digestSchemaVersion() != required(row, "digest_schema_version", Integer.class)) { + throw new PublicationTerminalConflictException( + "World terminal evidence differs from its exact immutable V25 publication checkpoint"); + } + return row; + } + + private void insertTerminal(WorldPublicationTerminal.Request request) { + var world = request.worldEvidence().request(); + GameDesignPublicationTerminalEvidence evidence = request.evidence(); + dsl.execute( + "INSERT INTO world_design_publication_terminal (publication_fence,target_namespace," + + "canonical_tenant_id,canonical_version_id,publication_request_id,request_digest," + + "publish_workflow_id,freeze_version_state_epoch,applied_commit_id,content_digest," + + "digest_schema_version,outcome,publication_version_state_epoch," + + "published_release_bundle_ref,published_release_bundle_digest,operation_bytes," + + "terminal_evidence_bytes,terminal_evidence_digest,world_evidence_bytes,world_request_json," + + "selector_receipt_bytes,original_account_binding_bytes,applied_result_bytes,release_content_bytes) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + world.publicationFence(), + world.targetNamespace(), + world.canonicalTenantId(), + world.canonicalVersionId(), + world.publicationRequestId(), + world.requestDigest(), + world.publishWorkflowId(), + world.versionStateEpoch(), + world.appliedCommitId(), + world.contentDigest(), + world.digestSchemaVersion(), + evidence.outcome().name(), + request.publicationVersionStateEpoch(), + request.releaseBundleRef(), + request.releaseBundleDigest(), + request.operationBytes(), + request.terminalBytes(), + digest(request.terminalBytes()), + request.worldEvidenceBytes(), + request.worldRequestJson(), + request.selectorReceiptBytes(), + request.originalAccountBindingBytes(), + request.appliedResultBytes(), + request.releaseContentBytes()); + } + + private Optional readInOwnerTransaction( + WorldPublicationTerminal.Request request) { + Record row = readTerminalWithOwner(request, true); + if (row == null) return Optional.empty(); + return Optional.of(exactReadback(request, row)); + } + + private Record readTerminalWithOwner(WorldPublicationTerminal.Request request, boolean lock) { + return dsl.fetchOne( + TERMINAL_WITH_OWNER_READ + (lock ? " FOR UPDATE OF t" : ""), + request.worldEvidence().request().publicationFence()); + } + + private GameDesignPublicationTerminalEvidence exactReadback( + WorldPublicationTerminal.Request request, Record row) { + byte[] stored = required(row, "terminal_evidence_bytes", byte[].class); + if (!request.exactBytes(stored)) { + throw new PublicationTerminalConflictException( + "World publication fence was reused with changed complete terminal evidence"); + } + var world = request.worldEvidence().request(); + if (!request.ownerPhase().equals(required(row, "joined_owner_phase", String.class)) + || !world + .publicationFence() + .equals(required(row, "joined_owner_current_fence", java.util.UUID.class)) + || !Short.valueOf((short) 1) + .equals(required(row, "joined_owner_binding_schema_version", Short.class)) + || !world + .targetNamespace() + .equals(required(row, "joined_attempt_target_namespace", String.class)) + || !world + .canonicalTenantId() + .equals(required(row, "joined_attempt_canonical_tenant_id", java.util.UUID.class)) + || !world + .canonicalVersionId() + .equals(required(row, "joined_attempt_canonical_version_id", java.util.UUID.class)) + || required(row, "joined_attempt_local_tenant_key", Long.class) <= 0L + || required(row, "joined_attempt_local_version_id", Long.class) <= 0L + || !world + .intakeRequestId() + .equals(required(row, "joined_attempt_intake_request_id", java.util.UUID.class)) + || !world + .publicationRequestId() + .equals(required(row, "joined_attempt_publication_request_id", String.class)) + || !world + .requestDigest() + .equals(required(row, "joined_attempt_request_digest", String.class)) + || world.versionStateEpoch() + != required(row, "joined_attempt_version_state_epoch", Long.class) + || !world + .publishWorkflowId() + .equals(required(row, "joined_attempt_publish_workflow_id", String.class)) + || !world + .appliedCommitId() + .equals(required(row, "joined_attempt_applied_commit_id", String.class)) + || !world + .contentDigest() + .equals(required(row, "joined_attempt_content_digest", String.class)) + || world.digestSchemaVersion() + != required(row, "joined_attempt_digest_schema_version", Integer.class) + || !digest(stored).equals(required(row, "terminal_evidence_digest", String.class)) + || !world + .publicationFence() + .equals(required(row, "publication_fence", java.util.UUID.class)) + || !world.targetNamespace().equals(required(row, "target_namespace", String.class)) + || !world + .canonicalTenantId() + .equals(required(row, "canonical_tenant_id", java.util.UUID.class)) + || !world + .canonicalVersionId() + .equals(required(row, "canonical_version_id", java.util.UUID.class)) + || !world + .publicationRequestId() + .equals(required(row, "publication_request_id", String.class)) + || !world.requestDigest().equals(required(row, "request_digest", String.class)) + || !world.publishWorkflowId().equals(required(row, "publish_workflow_id", String.class)) + || world.versionStateEpoch() != required(row, "freeze_version_state_epoch", Long.class) + || !world.appliedCommitId().equals(required(row, "applied_commit_id", String.class)) + || !world.contentDigest().equals(required(row, "content_digest", String.class)) + || world.digestSchemaVersion() != required(row, "digest_schema_version", Integer.class) + || !request.evidence().outcome().name().equals(required(row, "outcome", String.class)) + || !Objects.equals( + request.publicationVersionStateEpoch(), + row.get("publication_version_state_epoch", Long.class)) + || !Objects.equals( + request.releaseBundleRef(), row.get("published_release_bundle_ref", String.class)) + || !Objects.equals( + request.releaseBundleDigest(), row.get("published_release_bundle_digest", String.class)) + || !Arrays.equals(request.operationBytes(), required(row, "operation_bytes", byte[].class)) + || !Arrays.equals( + request.worldEvidenceBytes(), required(row, "world_evidence_bytes", byte[].class)) + || !request.worldRequestJson().equals(required(row, "world_request_json", String.class)) + || !Arrays.equals( + request.selectorReceiptBytes(), required(row, "selector_receipt_bytes", byte[].class)) + || !Arrays.equals( + request.originalAccountBindingBytes(), + required(row, "original_account_binding_bytes", byte[].class)) + || !Arrays.equals( + request.appliedResultBytes(), required(row, "applied_result_bytes", byte[].class)) + || !Arrays.equals( + request.releaseContentBytes(), required(row, "release_content_bytes", byte[].class))) { + throw new InvalidPublicationTerminalEvidenceException( + "Retained World publication terminal columns differ from their canonical producer evidence"); + } + return GameDesignPublicationTerminalEvidence.fromStored(stored); + } + + private static String digest(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private static T required(Record record, String field, Class type) { + T value = record.get(field, type); + if (value == null) throw new InvalidPublicationTerminalEvidenceException("Missing " + field); + return value; + } + + private static void requireNoAmbientTransaction(String operation) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException(operation + " requires no caller transaction"); + } + } + + private void requireWritableReadCommittedTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "World publication terminal requires a writable owner transaction"); + } + Integer isolation = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (isolation != null && isolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("World publication terminal requires READ COMMITTED"); + } + Record settings = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"); + if (settings == null + || !"read committed".equalsIgnoreCase(required(settings, "isolation", String.class)) + || !"off".equalsIgnoreCase(required(settings, "read_only", String.class))) { + throw new IllegalStateException( + "World publication terminal requires writable READ COMMITTED"); + } + } + + public static class PublicationTerminalConflictException extends IllegalStateException { + public PublicationTerminalConflictException(String message) { + super(message); + } + } + + public static final class InvalidPublicationTerminalEvidenceException + extends PublicationTerminalConflictException { + public InvalidPublicationTerminalEvidenceException(String message) { + super(message); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalService.java new file mode 100644 index 0000000000..faa87bc113 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalService.java @@ -0,0 +1,90 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone, default-denied receiver for one authenticated Game Design terminal publication. */ +public final class WorldPublicationTerminalService { + private final WorldPublicationTerminalRepository repository; + private final TerminalAuthorityVerifier verifier; + + /** + * Production-safe default until an authenticated same-namespace Game Design verifier is wired. + */ + public WorldPublicationTerminalService(WorldPublicationTerminalRepository repository) { + this(repository, WorldPublicationTerminalService::denyByDefault); + } + + /** Explicit verifier seam for a future authenticated producer and isolated component fixtures. */ + public WorldPublicationTerminalService( + WorldPublicationTerminalRepository repository, TerminalAuthorityVerifier verifier) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.verifier = Objects.requireNonNull(verifier, "verifier"); + } + + /** + * Authenticates and reconciles the producer before opening the World owner transaction. The + * continuously held fence is checked locally through commit; no remote call occurs under locks. + */ + public GameDesignPublicationTerminalEvidence complete( + byte[] operationBytes, byte[] terminalBytes) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World publication terminal must authenticate outside an ambient transaction"); + } + VerifiedTerminal verified = + Objects.requireNonNull( + verifier.authenticateAndVerifyAndHold(operationBytes.clone(), terminalBytes.clone()), + "World publication terminal verifier returned no authenticated evidence"); + WorldPublicationTerminal.Request request = Objects.requireNonNull(verified.request()); + if (!request.exactBytes(terminalBytes) + || !java.util.Arrays.equals(request.operationBytes(), operationBytes)) { + verified.authority().close(); + throw new IllegalArgumentException( + "Authenticated Game Design terminal evidence differs from the submitted immutable bytes"); + } + HeldTerminalAuthority held = Objects.requireNonNull(verified.authority()); + try (held) { + held.requireHeld(); + GameDesignPublicationTerminalEvidence result = repository.complete(request, held); + held.requireHeld(); + return result; + } + } + + private static VerifiedTerminal denyByDefault(byte[] operationBytes, byte[] terminalBytes) { + throw new TerminalDeniedException( + "World publication terminal has no authenticated exact Game Design producer verifier"); + } + + @FunctionalInterface + public interface TerminalAuthorityVerifier { + /** Must authenticate the configured Game Design peer before decoding the supplied bytes. */ + VerifiedTerminal authenticateAndVerifyAndHold(byte[] operationBytes, byte[] terminalBytes); + } + + public record VerifiedTerminal( + WorldPublicationTerminal.Request request, HeldTerminalAuthority authority) { + public VerifiedTerminal { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(authority, "authority"); + } + } + + /** + * Local held-authentication/currentness assertion; must not perform RPC while World locks exist. + */ + public interface HeldTerminalAuthority extends AutoCloseable { + void requireHeld(); + + @Override + void close(); + } + + public static final class TerminalDeniedException extends IllegalStateException { + public TerminalDeniedException(String message) { + super(message); + } + } +} diff --git a/services/world-management-service/src/main/resources/db/migration/V44__world_publication_terminal_handoff.sql b/services/world-management-service/src/main/resources/db/migration/V44__world_publication_terminal_handoff.sql new file mode 100644 index 0000000000..bda08d2c32 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V44__world_publication_terminal_handoff.sql @@ -0,0 +1,354 @@ +-- Retain the authenticated Game Design terminal result before World leaves FROZEN. The owner +-- transition and immutable receipt are committed atomically; absence or uncertainty never settles. +CREATE TABLE world_design_publication_terminal ( + publication_fence UUID PRIMARY KEY + REFERENCES world_design_publication_fence_attempt(publication_fence) ON DELETE RESTRICT, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + publication_request_id VARCHAR(256) NOT NULL, + request_digest VARCHAR(64) NOT NULL, + publish_workflow_id VARCHAR(537) NOT NULL, + freeze_version_state_epoch BIGINT NOT NULL CHECK (freeze_version_state_epoch > 0), + applied_commit_id VARCHAR(256) NOT NULL, + content_digest VARCHAR(64) NOT NULL, + digest_schema_version INTEGER NOT NULL CHECK (digest_schema_version > 0), + outcome VARCHAR(16) NOT NULL CHECK (outcome IN ('PUBLISHED', 'NO_PUBLICATION')), + publication_version_state_epoch BIGINT, + published_release_bundle_ref VARCHAR(512), + published_release_bundle_digest VARCHAR(71), + operation_bytes BYTEA NOT NULL CHECK (octet_length(operation_bytes) > 0), + terminal_evidence_bytes BYTEA NOT NULL CHECK (octet_length(terminal_evidence_bytes) > 0), + terminal_evidence_digest VARCHAR(64) NOT NULL CHECK (terminal_evidence_digest ~ '^[0-9a-f]{64}$'), + world_evidence_bytes BYTEA NOT NULL CHECK (octet_length(world_evidence_bytes) > 0), + world_request_json TEXT NOT NULL, + selector_receipt_bytes BYTEA NOT NULL CHECK (octet_length(selector_receipt_bytes) > 0), + original_account_binding_bytes BYTEA NOT NULL CHECK (octet_length(original_account_binding_bytes) > 0), + applied_result_bytes BYTEA NOT NULL CHECK (octet_length(applied_result_bytes) > 0), + release_content_bytes BYTEA NOT NULL, + recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uq_world_publication_terminal_scope_request UNIQUE + (target_namespace, canonical_tenant_id, canonical_version_id, publication_request_id), + CONSTRAINT ck_world_publication_terminal_identity CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND octet_length(publication_request_id) BETWEEN 1 AND 256 + AND position(':' IN publication_request_id) = 0 + AND request_digest ~ '^[0-9a-f]{64}$' + AND publish_workflow_id = 'publish:' || canonical_tenant_id::TEXT + || ':publish-request:' || publication_request_id + AND octet_length(applied_commit_id) BETWEEN 1 AND 256 + AND content_digest ~ '^[0-9a-f]{64}$' + ), + CONSTRAINT ck_world_publication_terminal_outcome_shape CHECK ( + (outcome = 'PUBLISHED' + AND publication_version_state_epoch IS NOT NULL + AND publication_version_state_epoch = freeze_version_state_epoch + 1 + AND published_release_bundle_ref IS NOT NULL + AND octet_length(published_release_bundle_ref) BETWEEN 1 AND 512 + AND published_release_bundle_digest IS NOT NULL + AND published_release_bundle_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(release_content_bytes) > 0) + OR + (outcome = 'NO_PUBLICATION' + AND publication_version_state_epoch IS NULL + AND published_release_bundle_ref IS NULL + AND published_release_bundle_digest IS NULL + AND octet_length(release_content_bytes) = 0) + ) +); + +-- [jooq ignore start] +REVOKE ALL ON world_design_publication_terminal FROM PUBLIC; + +CREATE FUNCTION world_validate_publication_terminal() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + attempt "${serviceSchema}".world_design_publication_fence_attempt%ROWTYPE; + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + 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; + identity_row "${serviceSchema}".world_authored_version_identity%ROWTYPE; + intake_row "${serviceSchema}".world_authored_source_intake%ROWTYPE; + world_request JSONB; + world_evidence JSONB; + freeze_request JSONB; + expected_tuples JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'World publication terminal evidence is immutable' USING ERRCODE = '55000'; + END IF; + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' THEN + RAISE EXCEPTION 'World publication terminal requires writable READ COMMITTED' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT attempt FROM "${serviceSchema}".world_design_publication_fence_attempt + WHERE publication_fence=NEW.publication_fence; + SELECT * INTO STRICT owner_row FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE target_namespace=attempt.target_namespace + AND canonical_tenant_id=attempt.canonical_tenant_id + AND local_tenant_key=attempt.local_tenant_key AND version_id=attempt.version_id + FOR UPDATE; + SELECT * INTO STRICT frozen FROM "${serviceSchema}".world_canonical_frozen_topology + WHERE publication_fence=NEW.publication_fence; + SELECT * INTO STRICT identity_row FROM "${serviceSchema}".world_authored_version_identity + WHERE operation_id=attempt.version_identity_operation_id; + SELECT * INTO STRICT intake_row FROM "${serviceSchema}".world_authored_source_intake + WHERE operation_id=attempt.intake_operation_id; + SELECT * INTO STRICT graph FROM "${serviceSchema}".world_topology_draft_commit + WHERE request_id=frozen.request_id AND commit_id=frozen.commit_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 application FROM "${serviceSchema}".world_draft_graph_application + WHERE request_id=frozen.request_id AND commit_id=frozen.commit_id + AND operation_id=receipt.operation_id; + + world_request := NEW.world_request_json::JSONB; + world_evidence := convert_from(NEW.world_evidence_bytes, 'UTF8')::JSONB; + freeze_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_request->'suppliedOwnedAffectedTuples'); + + IF attempt.owner_binding_schema_version IS DISTINCT FROM 1 + OR owner_row.owner_freeze_phase IS DISTINCT FROM 'FROZEN' + OR owner_row.current_publication_fence IS DISTINCT FROM NEW.publication_fence + OR NEW.target_namespace IS DISTINCT FROM attempt.target_namespace + OR NEW.canonical_tenant_id IS DISTINCT FROM attempt.canonical_tenant_id + OR NEW.canonical_version_id IS DISTINCT FROM attempt.canonical_version_id + OR NEW.publication_request_id IS DISTINCT FROM attempt.publication_request_id + OR NEW.request_digest IS DISTINCT FROM attempt.request_digest + OR NEW.publish_workflow_id IS DISTINCT FROM attempt.publish_workflow_id + OR NEW.freeze_version_state_epoch IS DISTINCT FROM attempt.version_state_epoch + OR NEW.applied_commit_id IS DISTINCT FROM attempt.applied_commit_id + OR NEW.content_digest IS DISTINCT FROM attempt.content_digest + OR NEW.digest_schema_version IS DISTINCT FROM attempt.digest_schema_version THEN + RAISE EXCEPTION 'World terminal differs from exact current V25 publication owner' + USING ERRCODE = '23514'; + END IF; + + IF encode(sha256(NEW.terminal_evidence_bytes), 'hex') IS DISTINCT FROM NEW.terminal_evidence_digest + OR jsonb_typeof(world_request) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(world_request)) <> 13 + OR jsonb_typeof(world_evidence) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(world_evidence)) <> 5 + OR world_evidence->>'schema' IS DISTINCT FROM 'world-published-start-location-evidence/v1' + OR world_evidence->'request' IS DISTINCT FROM world_request + OR decode(world_evidence->>'selectorReceiptBytesBase64','base64') IS DISTINCT FROM NEW.selector_receipt_bytes + OR decode(world_evidence->>'originalAccountBindingBytesBase64','base64') IS DISTINCT FROM NEW.original_account_binding_bytes + OR decode(world_evidence->>'appliedResultBytesBase64','base64') IS DISTINCT FROM NEW.applied_result_bytes + OR world_request->>'targetNamespace' IS DISTINCT FROM attempt.target_namespace + OR world_request->>'canonicalTenantId' IS DISTINCT FROM attempt.canonical_tenant_id::TEXT + OR world_request->>'canonicalVersionId' IS DISTINCT FROM attempt.canonical_version_id::TEXT + OR world_request->>'intakeRequestId' IS DISTINCT FROM attempt.intake_request_id::TEXT + OR world_request->>'publicationFence' IS DISTINCT FROM attempt.publication_fence::TEXT + OR world_request->>'publicationRequestId' IS DISTINCT FROM attempt.publication_request_id + OR world_request->>'requestDigest' IS DISTINCT FROM attempt.request_digest + OR world_request->>'versionStateEpoch' IS DISTINCT FROM attempt.version_state_epoch::TEXT + OR world_request->>'publishWorkflowId' IS DISTINCT FROM attempt.publish_workflow_id + OR world_request->>'appliedCommitId' IS DISTINCT FROM attempt.applied_commit_id + OR world_request->>'contentDigest' IS DISTINCT FROM attempt.content_digest + OR world_request->>'digestSchemaVersion' IS DISTINCT FROM attempt.digest_schema_version::TEXT + OR world_request->'worldAffectedTuples' IS DISTINCT FROM expected_tuples + OR freeze_request->>'targetNamespace' IS DISTINCT FROM attempt.target_namespace + OR freeze_request->>'canonicalTenantId' IS DISTINCT FROM attempt.canonical_tenant_id::TEXT + OR freeze_request->>'canonicalVersionId' IS DISTINCT FROM attempt.canonical_version_id::TEXT + OR freeze_request->>'publicationFence' IS DISTINCT FROM attempt.publication_fence::TEXT + OR freeze_request->>'publicationRequestId' IS DISTINCT FROM attempt.publication_request_id + OR freeze_request->>'requestDigest' IS DISTINCT FROM attempt.request_digest + OR freeze_request->>'versionStateEpoch' IS DISTINCT FROM attempt.version_state_epoch::TEXT + OR freeze_request->>'publishWorkflowId' IS DISTINCT FROM attempt.publish_workflow_id + OR freeze_request->>'appliedCommitId' IS DISTINCT FROM attempt.applied_commit_id + OR freeze_request->>'contentDigest' IS DISTINCT FROM attempt.content_digest + OR freeze_request->>'digestSchemaVersion' IS DISTINCT FROM attempt.digest_schema_version::TEXT + OR identity_row.target_namespace IS DISTINCT FROM attempt.target_namespace + OR identity_row.canonical_tenant_id IS DISTINCT FROM attempt.canonical_tenant_id + OR identity_row.canonical_version_id IS DISTINCT FROM attempt.canonical_version_id + OR identity_row.local_tenant_key IS DISTINCT FROM attempt.local_tenant_key + OR identity_row.local_version_key IS DISTINCT FROM attempt.version_id + OR identity_row.intake_operation_id IS DISTINCT FROM attempt.intake_operation_id + OR identity_row.intake_request_id IS DISTINCT FROM attempt.intake_request_id + OR identity_row.source_operation_id IS DISTINCT FROM attempt.source_operation_id + OR identity_row.source_evidence_digest IS DISTINCT FROM attempt.source_evidence_digest + OR identity_row.intake_receipt_digest IS DISTINCT FROM attempt.intake_receipt_digest + OR intake_row.target_namespace IS DISTINCT FROM attempt.target_namespace + OR intake_row.canonical_tenant_id IS DISTINCT FROM attempt.canonical_tenant_id + OR intake_row.local_tenant_key IS DISTINCT FROM attempt.local_tenant_key + OR intake_row.intake_request_id IS DISTINCT FROM attempt.intake_request_id + OR intake_row.source_operation_id IS DISTINCT FROM attempt.source_operation_id + OR intake_row.source_evidence_digest IS DISTINCT FROM attempt.source_evidence_digest + OR intake_row.receipt_digest IS DISTINCT FROM attempt.intake_receipt_digest + OR frozen.request_id IS DISTINCT FROM graph.request_id + OR frozen.commit_id IS DISTINCT FROM graph.commit_id + OR frozen.graph_bytes IS DISTINCT FROM graph.graph_bytes + OR application.account_binding_bytes IS DISTINCT FROM NEW.original_account_binding_bytes + OR receipt.account_binding_bytes IS DISTINCT FROM NEW.original_account_binding_bytes + OR receipt.receipt_bytes IS DISTINCT FROM NEW.selector_receipt_bytes + OR application.result_bytes IS DISTINCT FROM NEW.applied_result_bytes + OR graph.binding_digest IS DISTINCT FROM receipt.binding_digest + OR receipt.graph_digest IS DISTINCT FROM ('sha256:' || frozen.graph_sha256) THEN + RAISE EXCEPTION 'World terminal does not bind the exact immutable source, selector, APPLIED result and freeze checkpoint' + USING ERRCODE = '23514'; + END IF; + IF NEW.outcome='PUBLISHED' + AND (NEW.publication_version_state_epoch IS DISTINCT FROM attempt.version_state_epoch + 1 + OR NEW.published_release_bundle_digest IS DISTINCT FROM + ('sha256:' || encode(sha256(NEW.release_content_bytes), 'hex'))) THEN + RAISE EXCEPTION 'PUBLISHED World terminal lacks the exact next Game Design publication epoch' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_world_publication_terminal_validate + BEFORE INSERT ON world_design_publication_terminal FOR EACH ROW + EXECUTE FUNCTION world_validate_publication_terminal(); +CREATE TRIGGER trg_world_publication_terminal_immutable + BEFORE UPDATE OR DELETE ON world_design_publication_terminal FOR EACH ROW + EXECUTE FUNCTION world_reject_publication_attempt_history_mutation(); +CREATE TRIGGER trg_world_publication_terminal_no_truncate + BEFORE TRUNCATE ON world_design_publication_terminal FOR EACH STATEMENT + EXECUTE FUNCTION world_reject_publication_attempt_history_mutation(); + +-- A valid-looking receipt is not a terminal result until the same transaction commits the +-- matching owner phase. This deferred check observes the post-CAS row at transaction commit. +CREATE FUNCTION world_require_publication_terminal_owner_phase() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + expected_phase TEXT; + actual_phase TEXT; +BEGIN + expected_phase := CASE WHEN NEW.outcome='PUBLISHED' THEN 'PUBLISHED' ELSE 'ABORTED' END; + SELECT o.owner_freeze_phase INTO actual_phase + FROM "${serviceSchema}".world_design_publication_fence_attempt a + JOIN "${serviceSchema}".world_design_publication_fence_owner o + ON o.target_namespace=a.target_namespace + AND o.canonical_tenant_id=a.canonical_tenant_id + AND o.local_tenant_key=a.local_tenant_key AND o.version_id=a.version_id + WHERE a.publication_fence=NEW.publication_fence + AND a.owner_binding_schema_version=1 + AND a.target_namespace=NEW.target_namespace + AND a.canonical_tenant_id=NEW.canonical_tenant_id + AND a.canonical_version_id=NEW.canonical_version_id + AND a.publication_request_id=NEW.publication_request_id + AND a.request_digest=NEW.request_digest + AND a.publish_workflow_id=NEW.publish_workflow_id + AND a.version_state_epoch=NEW.freeze_version_state_epoch + AND a.applied_commit_id=NEW.applied_commit_id + AND a.content_digest=NEW.content_digest + AND a.digest_schema_version=NEW.digest_schema_version + AND o.current_publication_fence=NEW.publication_fence; + IF NOT FOUND OR actual_phase IS DISTINCT FROM expected_phase THEN + RAISE EXCEPTION 'World terminal receipt must commit with its exact owner phase' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER trg_world_publication_terminal_owner_phase_commit + AFTER INSERT ON world_design_publication_terminal + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION world_require_publication_terminal_owner_phase(); + +-- Preserve the original OPEN-to-FROZEN writer while allowing only a just-inserted immutable V44 +-- terminal row to authorize FROZEN-to-PUBLISHED/ABORTED. No reopen or reconciliation transition +-- is introduced by this migration. +CREATE OR REPLACE FUNCTION world_protect_publication_fence_owner() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'World publication-fence owner rows cannot be deleted' USING ERRCODE = '55000'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.owner_freeze_phase = 'OPEN' AND NEW.current_publication_fence IS NULL THEN RETURN NEW; END IF; + RAISE EXCEPTION 'World publication-fence owner rows must be created OPEN without a fence' USING ERRCODE = '55000'; + END IF; + IF OLD.target_namespace IS NOT DISTINCT FROM NEW.target_namespace + AND OLD.canonical_tenant_id IS NOT DISTINCT FROM NEW.canonical_tenant_id + AND OLD.local_tenant_key IS NOT DISTINCT FROM NEW.local_tenant_key + AND OLD.version_id IS NOT DISTINCT FROM NEW.version_id + AND OLD.owner_freeze_phase='OPEN' AND NEW.owner_freeze_phase='FROZEN' + AND OLD.current_publication_fence IS NULL AND NEW.current_publication_fence IS NOT NULL THEN + RETURN NEW; + END IF; + IF OLD.target_namespace IS NOT DISTINCT FROM NEW.target_namespace + AND OLD.canonical_tenant_id IS NOT DISTINCT FROM NEW.canonical_tenant_id + AND OLD.local_tenant_key IS NOT DISTINCT FROM NEW.local_tenant_key + AND OLD.version_id IS NOT DISTINCT FROM NEW.version_id + AND OLD.owner_freeze_phase='FROZEN' + AND OLD.current_publication_fence IS NOT DISTINCT FROM NEW.current_publication_fence + AND NEW.owner_freeze_phase IN ('PUBLISHED','ABORTED') + AND EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_design_publication_terminal t + WHERE t.publication_fence=OLD.current_publication_fence + AND t.target_namespace=OLD.target_namespace + AND t.canonical_tenant_id=OLD.canonical_tenant_id + AND t.canonical_version_id=(SELECT a.canonical_version_id + FROM "${serviceSchema}".world_design_publication_fence_attempt a + WHERE a.publication_fence=OLD.current_publication_fence) + AND ((NEW.owner_freeze_phase='PUBLISHED' AND t.outcome='PUBLISHED') + OR (NEW.owner_freeze_phase='ABORTED' AND t.outcome='NO_PUBLICATION')) + ) THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'World publication-fence owner binding or phase transition is immutable' + USING ERRCODE = '55000'; +END; +$$; + +-- Fresh allocation now requires the completed terminal handoff, not merely the earlier freeze. +-- All other V35/V40 guards, source checks and historical input bytes remain unchanged. +DO $migration$ +DECLARE + original TEXT; + phase_anchor TEXT := $anchor$ IF publication_owner.owner_freeze_phase IS DISTINCT FROM 'FROZEN' + OR publication_owner.current_publication_fence IS DISTINCT FROM capture_row.publication_fence THEN + RAISE EXCEPTION 'Canonical preparation requires the exact still-FROZEN V25 source owner' + USING ERRCODE = '23514'; + END IF;$anchor$; + replacement TEXT := $replacement$ IF publication_owner.owner_freeze_phase IS DISTINCT FROM 'PUBLISHED' + OR publication_owner.current_publication_fence IS DISTINCT FROM capture_row.publication_fence + OR NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_design_publication_terminal t + WHERE t.publication_fence=capture_row.publication_fence + AND t.target_namespace=identity_row.target_namespace + AND t.canonical_tenant_id=identity_row.canonical_tenant_id + AND t.canonical_version_id=identity_row.canonical_version_id + AND t.outcome='PUBLISHED' + AND t.publication_request_id=capture_row.freeze_request_json::JSONB->>'publicationRequestId' + AND t.request_digest=capture_row.freeze_request_json::JSONB->>'requestDigest' + AND t.publish_workflow_id=capture_row.freeze_request_json::JSONB->>'publishWorkflowId' + AND t.applied_commit_id=capture_row.freeze_request_json::JSONB->>'appliedCommitId' + AND t.content_digest=capture_row.freeze_request_json::JSONB->>'contentDigest' + AND t.digest_schema_version=(capture_row.freeze_request_json::JSONB->>'digestSchemaVersion')::INTEGER + AND t.published_release_bundle_ref=binding_row.release_attestation_json::JSONB->>'publishedReleaseBundleRef' + AND t.publication_version_state_epoch=(binding_row.release_attestation_json::JSONB->>'versionStateEpoch')::BIGINT + AND t.world_request_json::JSONB=jsonb_set( + binding_row.release_attestation_json::JSONB->'worldStartLocationEvidence'->'request', + '{versionStateEpoch}',to_jsonb(t.freeze_version_state_epoch::TEXT),FALSE) + ) THEN + RAISE EXCEPTION 'Canonical preparation requires the exact published V44 terminal for this retained release and frozen World source' + USING ERRCODE = '23514'; + END IF;$replacement$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_prepare_canonical_instance(text,text)'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,phase_anchor,'')))/length(phase_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V35 FROZEN preparation phase guard'; + END IF; + EXECUTE replace(original,phase_anchor,replacement); +END; +$migration$; +-- [jooq ignore stop] 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 58c4967657..81d602c6a3 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 @@ -11,6 +11,7 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.HexFormat; import java.util.LinkedHashMap; @@ -24,6 +25,7 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +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; @@ -31,7 +33,14 @@ 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.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Participant; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.ReleaseContent; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; @@ -207,6 +216,227 @@ void releaseSelectorMaterializesItsOriginalRoomAndExactlyRetriesWithSeparateRunt assertOrigin(); } + @Test + void publishedTerminalUsesExactOwnerEvidenceRetriesAndRejectsChangedReleaseContent() { + Fixture f = fixture(); + var original = application(generationFreePlan(f)); + var selectedRoom = + original.plan().graph().nodes().stream() + .filter( + node -> + node.mutation().getAggregateType() + == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .map(node -> node.templateId()) + .toList() + .getLast(); + var applied = withStartRoom(original, selectedRoom); + appliedComponent().apply(applied); + var frozen = capture(applied.plan()); + var selector = + publishedEvidence( + publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + var input = preparationInput(f, frozen, selector); + var terminal = isolatedTerminalEvidence(input); + UUID fence = selector.request().publicationFence(); + assertThat(publicationOwnerPhase(fence)).isEqualTo("FROZEN"); + + byte[] originalTerminal = terminal.canonicalBytes(); + var service = publicationTerminalComponent(terminal); + assertThat(service.complete(terminal.operationBytes(), originalTerminal).canonicalBytes()) + .containsExactly(originalTerminal); + assertThat(publicationOwnerPhase(fence)).isEqualTo("PUBLISHED"); + assertThat(publicationTerminalBytes(fence)).containsExactly(originalTerminal); + assertThat(service.complete(terminal.operationBytes(), originalTerminal).canonicalBytes()) + .containsExactly(originalTerminal); + + var bundle = terminal.releaseContent(); + var changedBundle = + new ReleaseContent( + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.publishedReleaseBundleRef(), + bundle.versionNumber(), + bundle.attestationSchemaVersion(), + bundle.publishWorkflowId(), + bundle.manifestHash(), + bundle.manifestSchemaVersion(), + bundle.artifactDigests(), + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + List.of("LOOK", "CHANGED"), + bundle.generationConfigRevision(), + bundle.worldStartLocationEvidence()); + var changedTerminal = + new GameDesignPublicationTerminalEvidence( + terminal.operationBytes(), + Outcome.PUBLISHED, + changedBundle, + terminal.publicationVersionStateEpoch()); + assertThatThrownBy( + () -> + service.complete( + changedTerminal.operationBytes(), changedTerminal.canonicalBytes())) + .isInstanceOf(WorldPublicationTerminalRepository.PublicationTerminalConflictException.class) + .hasMessageContaining("changed complete terminal evidence"); + assertThat(publicationTerminalBytes(fence)).containsExactly(originalTerminal); + assertThat(publicationOwnerPhase(fence)).isEqualTo("PUBLISHED"); + + var materialized = preparationComponent(preparationRepository()).prepare(input); + assertThat(materialized.startLocation().roomTemplateId()).isEqualTo(selectedRoom); + assertThat(publicationOwnerPhase(fence)).isEqualTo("PUBLISHED"); + assertOrigin(); + } + + @Test + void rawTerminalReceiptCannotCommitWithoutMatchingOwnerPhaseCas() { + Fixture f = fixture(); + var original = application(generationFreePlan(f)); + var selectedRoom = + original.plan().graph().nodes().stream() + .filter( + node -> + node.mutation().getAggregateType() + == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .map(node -> node.templateId()) + .toList() + .getLast(); + var applied = withStartRoom(original, selectedRoom); + appliedComponent().apply(applied); + var frozen = capture(applied.plan()); + var selector = + publishedEvidence( + publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + var input = preparationInput(f, frozen, selector); + // This isolated producer fixture exercises the actual retained World rows and SQL guards. + var request = + WorldPublicationTerminal.Request.fromStored( + isolatedTerminalEvidence(input).canonicalBytes()); + UUID fence = selector.request().publicationFence(); + + assertThat(publicationOwnerPhase(fence)).isEqualTo("FROZEN"); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + insertPublicationTerminal(request); + return null; + })) + .hasMessageContaining("World terminal receipt must commit with its exact owner phase"); + assertThat(publicationOwnerPhase(fence)).isEqualTo("FROZEN"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_design_publication_terminal WHERE publication_fence=?", + fence)) + .get(0, Long.class)) + .isZero(); + assertOrigin(); + } + + @Test + void onlyPositiveNoPublicationEvidenceCanSealWorldAsAbortedAndCannotPrepare() { + Fixture f = fixture(); + var base = application(generationFreePlan(f)); + // Use an authored ROOM from this exact graph rather than an unbound external identifier. + var authoredRoom = + base.plan().graph().nodes().stream() + .filter( + node -> + node.mutation().getAggregateType() + == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .map(node -> node.templateId()) + .toList() + .getFirst(); + var applied = withStartRoom(base, authoredRoom); + appliedComponent().apply(applied); + var frozen = capture(applied.plan()); + var selector = + publishedEvidence( + publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + var input = preparationInput(f, frozen, selector); + var published = isolatedTerminalEvidence(input); + var noPublication = + new GameDesignPublicationTerminalEvidence( + published.operationBytes(), Outcome.NO_PUBLICATION, null, null); + UUID fence = selector.request().publicationFence(); + var service = publicationTerminalComponent(noPublication); + byte[] result = + service + .complete(noPublication.operationBytes(), noPublication.canonicalBytes()) + .canonicalBytes(); + assertThat(result).containsExactly(noPublication.canonicalBytes()); + assertThat(publicationOwnerPhase(fence)).isEqualTo("ABORTED"); + assertThat( + service + .complete(noPublication.operationBytes(), noPublication.canonicalBytes()) + .canonicalBytes()) + .containsExactly(result); + assertThat(publicationTerminalBytes(fence)).containsExactly(result); + + assertThatThrownBy(() -> preparationComponent(preparationRepository()).prepare(input)) + .isInstanceOf( + WorldPublicationTerminalRepository.PublicationTerminalConflictException.class); + assertThat(publicationOwnerPhase(fence)).isEqualTo("ABORTED"); + assertThat(count(f, "world_instance")).isZero(); + assertOrigin(); + } + + private String publicationOwnerPhase(UUID fence) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT owner_freeze_phase FROM world_design_publication_fence_owner " + + "WHERE current_publication_fence=?", + fence)) + .get("owner_freeze_phase", String.class); + } + + private byte[] publicationTerminalBytes(UUID fence) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT terminal_evidence_bytes FROM world_design_publication_terminal " + + "WHERE publication_fence=?", + fence)) + .get("terminal_evidence_bytes", byte[].class); + } + + private void insertPublicationTerminal(WorldPublicationTerminal.Request request) { + var world = request.worldEvidence().request(); + dsl.execute( + "INSERT INTO world_design_publication_terminal (publication_fence,target_namespace," + + "canonical_tenant_id,canonical_version_id,publication_request_id,request_digest," + + "publish_workflow_id,freeze_version_state_epoch,applied_commit_id,content_digest," + + "digest_schema_version,outcome,publication_version_state_epoch," + + "published_release_bundle_ref,published_release_bundle_digest,operation_bytes," + + "terminal_evidence_bytes,terminal_evidence_digest,world_evidence_bytes,world_request_json," + + "selector_receipt_bytes,original_account_binding_bytes,applied_result_bytes,release_content_bytes) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + world.publicationFence(), + world.targetNamespace(), + world.canonicalTenantId(), + world.canonicalVersionId(), + world.publicationRequestId(), + world.requestDigest(), + world.publishWorkflowId(), + world.versionStateEpoch(), + world.appliedCommitId(), + world.contentDigest(), + world.digestSchemaVersion(), + request.evidence().outcome().name(), + request.publicationVersionStateEpoch(), + request.releaseBundleRef(), + request.releaseBundleDigest(), + request.operationBytes(), + request.terminalBytes(), + sha256Digest(request.terminalBytes()).substring("sha256:".length()), + request.worldEvidenceBytes(), + request.worldRequestJson(), + request.selectorReceiptBytes(), + request.originalAccountBindingBytes(), + request.appliedResultBytes(), + request.releaseContentBytes()); + } + @Test void lifecycleReadFollowsCurrentWorldEpochAndReturnsExactCanonicalServiceEcho() { Fixture f = fixture(); @@ -1214,7 +1444,7 @@ private WorldCanonicalInstancePreparation.Input preparationInput( "generation-free", 2L, 97L, - "release-" + UUID.randomUUID(), + "release-" + frozen.request().freeze().publicationRequestId(), false, null); var freeze = frozen.request().freeze(); @@ -1395,22 +1625,149 @@ private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleReadRequ private WorldCanonicalInstancePreparationService preparationComponent( WorldCanonicalInstancePreparationRepository repository) { - // Stipulated local verifier only: no production producer, currentness, lifecycle or admission - // claim. + // Isolated GD-terminal fixture proves the actual World V44 transaction and released gate only. + // It does not prove authenticated GD production or cross-service transport/currentness. return new WorldCanonicalInstancePreparationService( repository, - input -> - new WorldCanonicalInstancePreparationService.HeldCommitAuthority() { - private boolean open = true; + input -> { + completeIsolatedPublicationTerminal(input); + return new WorldCanonicalInstancePreparationService.HeldCommitAuthority() { + private boolean open = true; - public void requireHeld() { - if (!open) throw new IllegalStateException("closed fixture authority"); - } + public void requireHeld() { + if (!open) throw new IllegalStateException("closed fixture authority"); + } - public void close() { - open = false; - } - }); + public void close() { + open = false; + } + }; + }); + } + + private GameDesignPublicationTerminalEvidence isolatedTerminalEvidence( + WorldCanonicalInstancePreparation.Input input) { + var release = input.completeLaunchBinding().evidence().releaseAttestation(); + var world = Objects.requireNonNull(release.worldStartLocationEvidence()); + var originalAccount = + DraftAuthorizationFenceBinding.fromStored(world.originalAccountBindingBytes()); + var selection = + publicationSelection( + input.topologyPlan().sourceBinding().plan(), + world.request().publicationRequestId(), + world.request().versionStateEpoch()); + if (!selection.digest().equals("sha256:" + world.request().requestDigest())) { + throw new IllegalStateException( + "Isolated publication selection differs from the retained World request digest"); + } + var account = + new AccountPublicationAuthorizationBinding( + UUID.nameUUIDFromBytes( + (world.request().publicationFence() + "/account-operation") + .getBytes(StandardCharsets.UTF_8)), + UUID.nameUUIDFromBytes( + (world.request().publicationFence() + "/account-fence") + .getBytes(StandardCharsets.UTF_8)), + new AccountPublicationAuthorizationBinding.PreallocationInput( + originalAccount.actorAccountId(), selection), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + originalAccount.actorAccountId().toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + var operation = new GameDesignPublicationOperationBinding(account, world); + var participants = + release.participantDigests().stream() + .map( + participant -> + new Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionIdPresent() ? participant.baseVersionId() : null, + participant.appliedCommitId(), + participant.contentDigest(), + participant.digestSchemaVersion(), + participant.abilitySchemaDigestPresent() + ? participant.abilitySchemaDigest() + : null, + null, + null)) + .toList(); + var content = + new ReleaseContent( + release.canonicalTenantId(), + release.canonicalVersionId(), + release.publishedReleaseBundleRef(), + 1, + "v2", + release.publishWorkflowId(), + release.manifestHash(), + release.manifestSchemaVersion(), + release.artifactDigests(), + release.requiredManifestAssetKeys(), + participants, + release.commandDefinitions(), + release.generationConfigRevision(), + world); + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), Outcome.PUBLISHED, content, release.versionStateEpoch()); + } + + private void completeIsolatedPublicationTerminal(WorldCanonicalInstancePreparation.Input input) { + var evidence = isolatedTerminalEvidence(input); + publicationTerminalComponent(evidence) + .complete(evidence.operationBytes(), evidence.canonicalBytes()); + } + + private WorldPublicationTerminalService publicationTerminalComponent( + GameDesignPublicationTerminalEvidence evidence) { + byte[] operationBytes = evidence.operationBytes(); + return new WorldPublicationTerminalService( + new WorldPublicationTerminalRepository(dsl, manager), + (suppliedOperation, terminalBytes) -> { + var upstream = GameDesignPublicationTerminalEvidence.fromStored(terminalBytes); + if (!java.util.Arrays.equals(operationBytes, suppliedOperation) + || !java.util.Arrays.equals(upstream.operationBytes(), suppliedOperation)) { + throw new IllegalArgumentException("isolated terminal operation mismatch"); + } + return new WorldPublicationTerminalService.VerifiedTerminal( + WorldPublicationTerminal.Request.fromStored(terminalBytes), + new WorldPublicationTerminalService.HeldTerminalAuthority() { + public void requireHeld() {} + + public void close() {} + }); + }); + } + + private AuthoredDraftPublishSelectionBinding publicationSelection( + WorldDraftTopologyCommitPlan plan, String publicationRequest, long freezeEpoch) { + var binding = plan.binding(); + var intent = + new AuthoredDraftPublishSelectionBinding.PublishIntent( + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + publicationRequest, + Long.toString(freezeEpoch), + "isolated-world-terminal-fixture", + binding.requestId(), + binding.commitId(), + binding.digest()); + return AuthoredDraftPublishSelectionBinding.capture( + intent, + binding.target(), + binding, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + binding.target(), + binding.requestId(), + binding.commitId(), + binding.digest(), + "[]", + OffsetDateTime.parse("2026-01-01T00:00:00Z"))); } private PreparedLifecycleFixture materializedLifecycleFixture() { @@ -1613,6 +1970,7 @@ private WorldPublishedStartLocationRepository publishedSelectors() { private WorldCanonicalFrozenTopology capture(WorldDraftTopologyCommitPlan plan) { var owner = plan.ownerBinding(); String publicationRequest = "selector-" + UUID.randomUUID(); + var selection = publicationSelection(plan, publicationRequest, 1L); var evidence = new WorldDesignPublicationFenceEvidence( owner.targetNamespace(), @@ -1627,7 +1985,7 @@ private WorldCanonicalFrozenTopology capture(WorldDraftTopologyCommitPlan plan) owner.sourceEvidenceDigest(), owner.intakeReceiptDigest(), publicationRequest, - "a".repeat(64), + selection.digest().substring("sha256:".length()), 1, "publish:" + owner.canonicalTenantId() + ":publish-request:" + publicationRequest); var attempt = diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationTest.java index fd092dad7e..88521ed104 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationTest.java @@ -263,7 +263,7 @@ void defaultServiceDeniesBeforeRepositoryAccess() { assertThatThrownBy( () -> new WorldCanonicalInstancePreparationService(repository).prepare(input)) .isInstanceOf(WorldCanonicalInstancePreparationService.PreparationDeniedException.class) - .hasMessageContaining("no authenticated source/release and Account commit verifier"); + .hasMessageContaining("no authenticated source/release terminal verifier"); verifyNoInteractions(repository); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalServiceTest.java new file mode 100644 index 0000000000..bccd2c31bf --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalServiceTest.java @@ -0,0 +1,22 @@ +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 net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalService; +import org.junit.jupiter.api.Test; + +class WorldPublicationTerminalServiceTest { + @Test + void productionDefaultDeniesOpaqueEvidenceBeforeDecodeOrOwnerStorage() { + var repository = mock(WorldPublicationTerminalRepository.class); + var service = new WorldPublicationTerminalService(repository); + + assertThatThrownBy(() -> service.complete(new byte[0], new byte[0])) + .isInstanceOf(WorldPublicationTerminalService.TerminalDeniedException.class) + .hasMessageContaining("no authenticated exact Game Design producer verifier"); + verifyNoInteractions(repository); + } +} From 193990b73e2f727c76a8b73a5154481b11ad010f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 07:01:57 +1300 Subject: [PATCH 03/12] docs(proof): record terminal delivery component limits and merged formatting --- .../game-authoring-publishing-and-activation.md | 4 ++-- .../implementation-tracking/world-runtime-and-movement.md | 4 ++-- .../WorldDraftGraphApplicationPostgresIntegrationTest.java | 3 ++- 3 files changed, 6 insertions(+), 5 deletions(-) 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 e3687a69bf..5e6644e733 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,9 +6,9 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The unpublished terminal-read candidate adds a separate unregistered Game Design owner RPC and concrete reloading file-backed mTLS client for Account/World exact operation recovery. Closed request/response codecs preserve original operation and stored terminal bytes, explicit `UNKNOWN` is limited to absent/pending operations, and retained V50 terminal history without the captured extension fails precondition. Physical socket definitions exercise authenticated Game Design server pre-send denial and Account/World receiver identity; their owner source is an explicitly isolated double and they are transport-only proof. Additional PostgreSQL definitions dispatch the actual handler through the independent owner service to genuine stored `PUBLISHED`/`NO_PUBLICATION` results, absent/pending results and retained V50-to-V51 history without backfill; their upstream creator/source/World authority remains isolated. No validation has run for this candidate: formatting, proto generation, compilation, physical tests, jOOQ and PostgreSQL execution remain integration obligations. The standalone components do not register or enable public publication, authenticated normal World freeze/terminal orchestration, Account settlement or runtime activation. +The #3035 terminal-read candidate adds a separate unregistered Game Design owner RPC and concrete reloading file-backed mTLS client for Account/World exact operation recovery. Closed request/response codecs preserve original operation and stored terminal bytes, explicit `UNKNOWN` is limited to absent/pending operations, and retained V50 terminal history without the captured extension fails precondition. Executed physical socket unit tests use an explicitly isolated owner double and are transport-only proof. Twelve PostgreSQL definitions include actual committed `PUBLISHED`/`NO_PUBLICATION` owner readback, absent/pending results, retained V50-to-V51 history without backfill, and physical mTLS against the actual owner service with exact lost-response recovery and wrong-peer rejection. Their upstream creator/source/World inputs remain explicitly isolated. Local component checks, proto generation, compilation, jOOQ and packaged builds pass; all 169 Game Design integration cases skip without Docker, including those twelve definitions. They are not executed PostgreSQL or live composition proof. The standalone components do not register or enable public publication, authenticated normal World freeze/terminal orchestration, Account settlement or runtime activation. -The forward V51 candidate extends the actual Game Design publication seal with closed terminal evidence, the complete release content digest and the original committed publication Version epoch. Existing V50 receipt bytes and retained results stay unchanged, with no historical epoch or evidence backfill. The shared operation adapter keeps the exact original authorization/freeze bytes. Readback checks the captured complete content against the immutable release while retaining the original epoch after later Version movement. Codec vectors and PostgreSQL definitions cover lossless content, typed no-publication, raw terminal substitution, rollback and later lifecycle movement. Local formatting, compilation, jOOQ generation, PostgreSQL migration execution and focused tests are deferred to integration and are not claimed as passed. Authenticated World delivery, Account currentness, complete live five-owner publication and runtime activation remain open under the [canonical publication handoff](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff-target-state). +The forward V51 candidate extends the actual Game Design publication seal with closed terminal evidence, the complete release content digest and the original committed publication Version epoch. Existing V50 receipt bytes and retained results stay unchanged, with no historical epoch or evidence backfill. The shared operation adapter keeps the exact original authorization/freeze bytes. Readback checks the captured complete content against the immutable release while retaining the original epoch after later Version movement. Executed codec vectors and unexecuted PostgreSQL definitions cover lossless content, typed no-publication, raw terminal substitution, rollback and later lifecycle movement. Local component checks and schema generation pass; jOOQ simulation is not PostgreSQL migration or concurrency proof. Authenticated World delivery, Account currentness, complete live five-owner publication and runtime activation remain open under the [canonical publication handoff](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff-target-state). 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). 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 9575481c60..14e1f339a2 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,9 +6,9 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status -The V44 World publication-terminal candidate adds an unregistered, default-denied owner operation with immutable exact-retry PUBLISHED/ABORTED readback. Its explicit verifier consumes the separate Game Design terminal read; the owner transaction checks and seals the original freeze, source, Account/APPLIED and selector evidence. Fresh V35 preparation now requires that exact retained PUBLISHED terminal and original frozen capture rather than FROZEN alone; it does not capture new source after terminalization. New PostgreSQL definitions exercise the owner transitions and preparation using explicitly isolated synthetic upstream evidence. They are not executed proof of the real Game Design producer, live mTLS/service composition, or production authorization, and validation for this unpublished batch remains pending. +The #3035 V44 World publication-terminal candidate adds an unregistered, default-denied owner operation with immutable exact-retry PUBLISHED/ABORTED readback. Its explicit verifier consumes the separate Game Design terminal read; the owner transaction checks and seals the original freeze, source, Account/APPLIED and selector evidence. The terminal receipt and matching original owner phase must commit together, and independent readback rechecks their complete binding. Fresh V35 preparation now requires that exact retained PUBLISHED terminal and original frozen capture rather than FROZEN alone; it does not capture new source after terminalization. New PostgreSQL definitions exercise the owner transitions and preparation using explicitly isolated upstream evidence. Local component checks, schema generation and packaged builds pass, but all 170 World integration cases skip without Docker. They are not executed proof of PostgreSQL constraints, the real Game Design producer, live mTLS/service composition, or production authorization. -The local World delivery correction behind #3029 adds an unregistered, default-denied V43 canonical activation operation and an immutable exact-retry result. The owner transaction independently reconstructs the same complete association/materialization evidence, locks the actual lifecycle row and commits its `PREPARING -> ACTIVE` CAS with the result; raw SQL cannot commit a success ledger without that CAS or activate the canonical row through the legacy numeric writer. New definitions cover stale outcomes, exact concurrent retry, lost held-authority rollback, self-consistent forged evidence rejected against independent owner rows, and historical recovery after later lifecycle movement. Validation and PostgreSQL execution for this unpublished batch remain pending; these definitions and an explicitly isolated verifier do not supply authenticated live activation, placement, region preparation or admission. The [World API contract](../../architecture/microservices/world-management-service/api-contracts.md#canonical-instance-activation-and-lifecycle-readback) owns the operation and historical-versus-current evidence distinction. +The #3035 World delivery correction behind #3029 adds an unregistered, default-denied V43 canonical activation operation and an immutable exact-retry result. The owner transaction independently reconstructs the same complete association/materialization evidence, locks the actual lifecycle row and commits its `PREPARING -> ACTIVE` CAS with the result; raw SQL cannot commit a success ledger without that CAS or activate the canonical row through the legacy numeric writer. New definitions cover stale outcomes, exact concurrent retry, lost held-authority rollback, self-consistent forged evidence rejected against independent owner rows, and historical recovery after later lifecycle movement. Local component checks pass, while PostgreSQL execution remains unavailable locally without Docker; these definitions and an explicitly isolated verifier do not supply authenticated live activation, placement, region preparation or admission. The [World API contract](../../architecture/microservices/world-management-service/api-contracts.md#canonical-instance-activation-and-lifecycle-readback) owns the operation and historical-versus-current evidence distinction. Fresh Account lifecycle/serving authority remains a concrete missing producer, distinct from original Draft and publication authorization. Account's existing fresh-control bootstrap capture supplies committed exact-tenant `tenantAdmin` source evidence, but does not authenticate a lifecycle caller or produce fresh serving entitlement, billing/quota classification or capacity commitment. The gameplay-only numeric entitlement DTO and source-lock primitives cannot supply those missing facts. No `CommitTenantCapacityAdmission`, lifecycle participant hold, capacity usage/reservation ledger or complete canonical fresh-tenant billing source exists in this candidate; production activation therefore remains denied under [Versioning and Runtime](../../architecture/system-architecture-versioning-runtime.md#serving-entitlement-and-shutdown-gates). A clearly labeled isolated upstream authority composition can exercise real owner transitions for bounded fixture proof, but cannot count as any of those production producers or authorize player admission. 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 b864660608..35dc31b52f 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 @@ -438,7 +438,8 @@ private void insertPublicationTerminal(WorldPublicationTerminal.Request request) } @Test - void lifecycleReadPreservesPreparingStateAndDeniesLegacyNumericFailureWithExactCanonicalServiceEcho() { + void + lifecycleReadPreservesPreparingStateAndDeniesLegacyNumericFailureWithExactCanonicalServiceEcho() { Fixture f = fixture(); var original = application(generationFreePlan(f)); var roomTemplateId = From e6f1e49dcc866ff6d4cf4e9c62c13489e840796e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 08:28:18 +1300 Subject: [PATCH 04/12] feat: authenticate publication terminal delivery and settle exact owner pair --- .github/workflows/ci.yml | 25 +- .../world-management-service/api-contracts.md | 6 + ...ame-authoring-publishing-and-activation.md | 12 +- .../world-runtime-and-movement.md | 8 +- .../v1/publication_terminal_service.proto | 36 + ...licationTerminalReconciliationService.java | 231 +++++++ ...blicationAuthorizationFenceRepository.java | 343 +++++++++- ...tion_authorization_terminal_settlement.sql | 227 +++++++ .../AccountPublicationTerminalFixtures.java | 450 ++++++++++++ ...tionTerminalReconciliationServiceTest.java | 250 +++++++ ...orizationFencePostgresIntegrationTest.java | 594 +++++++++++++++- ...ationTerminalRepositoryEntryPointTest.java | 27 + .../world/WorldPublicationTerminalClient.java | 154 +++++ ...ldPublicationTerminalCompletionClient.java | 159 +++++ ...ublicationTerminalCompletionGrpcCodec.java | 159 +++++ .../WorldPublicationTerminalReadEvidence.java | 131 ++++ ...WorldPublicationTerminalReadGrpcCodec.java | 57 ++ ...orldPublicationTerminalClientMtlsTest.java | 511 ++++++++++++++ ...ationTerminalCompletionClientMtlsTest.java | 466 +++++++++++++ ...cationTerminalCompletionGrpcCodecTest.java | 100 +++ ...dPublicationTerminalReadGrpcCodecTest.java | 277 ++++++++ ...anonicalInstancePreparationRepository.java | 2 +- ...licationTerminalCompletionGrpcService.java | 234 +++++++ ...rldPublicationTerminalReadGrpcService.java | 122 ++++ .../WorldPublicationTerminalRepository.java | 88 ++- ...44__world_publication_terminal_handoff.sql | 2 +- ...aphApplicationPostgresIntegrationTest.java | 638 +++++++++++++++++- ...tionTerminalCompletionGrpcServiceTest.java | 136 ++++ ...ublicationTerminalReadGrpcServiceTest.java | 130 ++++ 29 files changed, 5526 insertions(+), 49 deletions(-) create mode 100644 protos/world-management/v1/publication_terminal_service.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/authorpublication/AccountPublicationTerminalReconciliationService.java create mode 100644 services/account-service/src/main/resources/db/migration/V80__publication_authorization_terminal_settlement.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authorpublication/AccountPublicationTerminalFixtures.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authorpublication/AccountPublicationTerminalReconciliationServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authorpublication/PublicationTerminalRepositoryEntryPointTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublicationTerminalClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublicationTerminalCompletionClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublicationTerminalCompletionGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublicationTerminalReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublicationTerminalReadGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublicationTerminalClientMtlsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublicationTerminalCompletionClientMtlsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublicationTerminalCompletionGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublicationTerminalReadGrpcCodecTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalCompletionGrpcService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadGrpcService.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalCompletionGrpcServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadGrpcServiceTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2645a878b8..ae0a8224da 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2204,12 +2204,22 @@ jobs: --require-case 'net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalOutcomePostgresIntegrationTest#migrationDoesNotInventAccountOutcomesForRetainedStatusOnlyRows()' \ game-design-service + - name: Run Account publication settlement and consumer component proof + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + ./gradlew :account-service:integrationTest \ + --tests integration.net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest \ + --tests integration.net.firedevops.firemud.accountservice.authorpublication.AccountPublicationTerminalReconciliationServiceTest \ + -PfullCheck --no-build-cache --no-configuration-cache + - 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 + path: | + services/account-service/build/test-results/integrationTest/TEST-*PublicationAuthorizationFencePostgresIntegrationTest.xml + services/account-service/build/test-results/integrationTest/TEST-*AccountPublicationTerminalReconciliationServiceTest.xml if-no-files-found: error retention-days: 7 @@ -2231,6 +2241,18 @@ jobs: --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()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#exactIdenticalOwnerReadbacksSettleOnlyAfterBothOwnersAndPreserveRetryIdentity()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#publishedOwnerPairSettlesPublicationOrderAndAllowsSourceTransition()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#revokeOrderRequiresExactNoPublicationPairBeforeDefinitiveSourceAbort()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#lateRuntimeRollbackRetainsValidOwnerPairAndWaitingSourceIntent()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#directSqlSourceTransitionNeedsTwoMatchingPublicationOwnerRowsAndImmutableRetries()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#revokeOrderAcceptsOnlyTwoMatchingNoPublicationRowsForDefinitiveAbort()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#lateSourceTransitionRollbackRetainsWaitingChangeAndOwnerRows()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest#v79PublicationOrderAndWaitingSourceChangeSurviveV80WithoutInventedOwnerResults()' \ + --require-suite integration.net.firedevops.firemud.accountservice.authorpublication.AccountPublicationTerminalReconciliationServiceTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.authorpublication.AccountPublicationTerminalReconciliationServiceTest#concreteOwnerClientsRunOutsideReadCommittedAccountTransactionsAndExactPairIsRetained()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authorpublication.AccountPublicationTerminalReconciliationServiceTest#gameDesignUnknownNeverFabricatesWorldRequestOrOwnerResult()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authorpublication.AccountPublicationTerminalReconciliationServiceTest#ambientOwnerTransactionRejectsRecoveryBeforeRepositoryOrClientUse()' \ account-service - name: Capture World Account-bound graph application PostgreSQL raw XML @@ -2248,6 +2270,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#canonicalPreparationKeepsOriginalPublicationEpochForLaterReleaseResolution()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#publishedTerminalUsesExactOwnerEvidenceRetriesAndRejectsChangedReleaseContent()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#rawTerminalReceiptCannotCommitWithoutMatchingOwnerPhaseCas()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#onlyPositiveNoPublicationEvidenceCanSealWorldAsAbortedAndCannotPrepare()' \ diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 2e7227e059..b63eae785b 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -111,6 +111,12 @@ Game Design completes the handoff through one outcome-typed terminal operation, Terminal retries are exact only when the complete request, digest, fence, outcome, and evidence match the stored terminal result. Changed or omitted input returns `IDEMPOTENCY_CONFLICT`; a conflicting nonterminal request, unknown fence, contradictory bundle/digest evidence, or unavailable owner read remains `RECONCILIATION_REQUIRED` and must not release the freeze. A failed or ambiguous publication therefore reuses the original `publicationRequestId` and `publicationFence` until WMS and Game Design agree on the durable bundle/version outcome; it cannot mint a second freeze or resume Draft writes by timeout. +The standalone `WorldPublicationTerminalCompletionService.CompleteWorldPublicationTerminal` adapter carries that same original operation and immutable terminal selection, not a new publication identity. Its closed schema-1 envelope binds the exact workload namespace, complete original operation bytes and complete Game Design terminal bytes. World authenticates the same-namespace Game Design workload and rejects end-user context before decoding, then independently reads Game Design's sealed terminal through the authenticated owner client outside every World transaction. The complete read request, operation, outcome and terminal bytes must match; copied expected bytes, an unavailable read or `UNKNOWN` cannot advance World. The verified immutable evidence and caller binding remain held locally through the existing atomic World owner transition, without an RPC under owner locks. The response echoes the complete request and actual committed terminal. The request/response domains are `world-publication-terminal-completion-request/v1` and `world-publication-terminal-completion-response/v1`, using the existing four-byte byte-length framing. This explicit adapter remains unregistered; transport and owner-storage component proof do not establish a live publication workflow or runtime activation. + +`WorldPublicationTerminalReadService.ReadWorldPublicationTerminal` is the separate Account-to-World publication recovery read, not the authored-Draft terminal read or a terminal mutation. It requires the exact same-namespace Account workload and no authenticated end-user context before decoding or owner access. Its closed schema-1 request binds the namespace, a distinct non-nil read UUID and the complete expected immutable [Game Design terminal evidence](../game-design-service/version-control.md#publication-freeze-and-owner-handoff-target-state), including the original publication operation. This expected evidence is a selection, not proof that World committed it. One independent read-only `REPEATABLE_READ` owner snapshot joins the actual retained World terminal, original freeze attempt and matching owner phase, and exact-compares every original binding and retained byte. The complete request is echoed; a missing World terminal returns `UNKNOWN` without a payload only after that same snapshot proves the exact matching original attempt and owner remain `FROZEN`. Actual World `PUBLISHED` returns the unchanged matching Game Design `PUBLISHED` terminal, and actual World `ABORTED` returns the unchanged matching `NO_PUBLICATION` terminal. Missing association, contradictory phase or substituted evidence denies rather than fabricating an outcome. + +The request and response use distinct `world-publication-terminal-read-request/v1` and `world-publication-terminal-read-response/v1` domains with the publication operation's four-byte byte-length framing. Canonical decoding and expected bytes confer no workload identity. The concrete Account client verifies the exact World workload before sending metadata/body, then verifies the complete response echo. Account still obtains Game Design's definitive result independently and compares both owners before its own [publication settlement](../account-service/api-contracts.md#account-owned-publication-authorization-fence); a copied Game Design payload, one owner's response or `UNKNOWN` cannot release that fence. This standalone read neither registers a production writer nor grants new publication, lifecycle or admission authority; implementation and executed proof limits remain in the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). + World Management also exposes a read-only design-time synchronization surface so Game Design can validate convergence before publish: - `GetDraftDesignDigest(GetDraftDesignDigestRequest)` returns `{tenantId, scope, appliedCommitId, contentDigest, digestSchemaVersion}`. 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 5e6644e733..cb2c20d908 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,15 +6,17 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The #3035 terminal-read candidate adds a separate unregistered Game Design owner RPC and concrete reloading file-backed mTLS client for Account/World exact operation recovery. Closed request/response codecs preserve original operation and stored terminal bytes, explicit `UNKNOWN` is limited to absent/pending operations, and retained V50 terminal history without the captured extension fails precondition. Executed physical socket unit tests use an explicitly isolated owner double and are transport-only proof. Twelve PostgreSQL definitions include actual committed `PUBLISHED`/`NO_PUBLICATION` owner readback, absent/pending results, retained V50-to-V51 history without backfill, and physical mTLS against the actual owner service with exact lost-response recovery and wrong-peer rejection. Their upstream creator/source/World inputs remain explicitly isolated. Local component checks, proto generation, compilation, jOOQ and packaged builds pass; all 169 Game Design integration cases skip without Docker, including those twelve definitions. They are not executed PostgreSQL or live composition proof. The standalone components do not register or enable public publication, authenticated normal World freeze/terminal orchestration, Account settlement or runtime activation. +The current local terminal-settlement candidate adds an unregistered Account reconciler and V80 immutable owner-result storage. It independently obtains exact definitive Game Design and World results outside Account transactions, requires their complete terminal bytes and outcome to match, then retains both immutable owner results before settling the original source fence in a short transaction. The source-lock ordering is aligned across result retention and source transitions. World now has unregistered, default-denied authenticated completion and Account read adapters: completion authenticates the exact same-namespace Game Design workload, rereads Game Design's sealed result, then commits the matching World `PUBLISHED`/`ABORTED` terminal through the existing owner transaction; the separate read adapter returns exact retained World evidence to Account. These candidates do not supply the current original publication-authorizing creator producer or separate lifecycle/serving authority, and no component is registered. All new definitions and validation are pending the parent gate; local Docker is unavailable, upstream inputs in World PostgreSQL definitions are isolated/mocked, and transport tests use a server double. No live publication, production readiness, or activation proof follows. A retained original publication epoch may precede a later launch-resolution epoch while the exact immutable release content remains bound. -The forward V51 candidate extends the actual Game Design publication seal with closed terminal evidence, the complete release content digest and the original committed publication Version epoch. Existing V50 receipt bytes and retained results stay unchanged, with no historical epoch or evidence backfill. The shared operation adapter keeps the exact original authorization/freeze bytes. Readback checks the captured complete content against the immutable release while retaining the original epoch after later Version movement. Executed codec vectors and unexecuted PostgreSQL definitions cover lossless content, typed no-publication, raw terminal substitution, rollback and later lifecycle movement. Local component checks and schema generation pass; jOOQ simulation is not PostgreSQL migration or concurrency proof. Authenticated World delivery, Account currentness, complete live five-owner publication and runtime activation remain open under the [canonical publication handoff](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff-target-state). +The #3035 terminal-read candidate adds a separate unregistered Game Design owner RPC and concrete reloading file-backed mTLS client for Account/World exact operation recovery. Closed request/response codecs preserve original operation and stored terminal bytes, explicit `UNKNOWN` is limited to absent/pending operations, and retained V50 terminal history without the captured extension fails precondition. Executed physical socket unit tests use an explicitly isolated owner double and are transport-only proof. Twelve PostgreSQL definitions include actual committed `PUBLISHED`/`NO_PUBLICATION` owner readback, absent/pending results, retained V50-to-V51 history without backfill, and physical mTLS against the actual owner service with exact lost-response recovery and wrong-peer rejection. Their upstream creator/source/World inputs remain explicitly isolated. Local component checks, proto generation, compilation, jOOQ and packaged builds pass; all 169 Game Design integration cases skip without Docker, including those twelve definitions. They are not executed PostgreSQL or live composition proof. The standalone components do not register or enable public publication, current creator authorization, runtime lifecycle/serving authority or activation. -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 forward V51 candidate extends the actual Game Design publication seal with closed terminal evidence, the complete release content digest and the original committed publication Version epoch. Existing V50 receipt bytes and retained results stay unchanged, with no historical epoch or evidence backfill. The shared operation adapter keeps the exact original authorization/freeze bytes. Readback checks the captured complete content against the immutable release while retaining the original epoch after later Version movement. Executed codec vectors and unexecuted PostgreSQL definitions cover lossless content, typed no-publication, raw terminal substitution, rollback and later lifecycle movement. Local component checks and schema generation pass; jOOQ simulation is not PostgreSQL migration or concurrency proof. Current creator authorization, complete live five-owner publication and runtime activation remain open under the [canonical publication handoff](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff-target-state); the terminal transport/settlement candidates above are not live composition proof. + +The #3029 integration, published at `c51596a42`, 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. Earlier local front-end proof reported 570 unit outcomes with one skip, 161 integration skips, and 230 architecture-contract checks; that is not new combined proof. Corrected-state PostgreSQL execution remains pending. Public publication and current creator permission remain denied/open; the Account settlement and authenticated World terminal adapter candidates now exist but remain unregistered and unproved as live composition 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. +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, actual five-owner publication and live release remain open and denied. Authenticated World terminal completion and Account both-owner settlement now have unregistered local candidates, but their new validation and production composition remain outstanding. 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. @@ -237,7 +239,7 @@ Design-time revoke is explicit through `RevokePluginVersion`. Upload verificatio ### World Design Authoring Handoff -Game Design owns revision history, commits, version state, and publish orchestration; World Management owns authoritative Draft and Published world template rows. `SaveRevision` is version-scoped and carries typed `worldDesignMutation` payloads, including `WORLD_GENERATION_SUBTREE`, through the canonical World Management API. The first caller path saves revision history and applies the concrete change through that API rather than directly mutating World tables or treating opaque revision JSON as the authoritative world graph. The current seam permits only Draft version design-time writes; Published, Active, Failed, and Retired scopes are rejected. Publication freeze and terminal handoff are target-only owner operations; their exact fields and current absent implementation/proof are maintained by the [World Management owner contract](../../architecture/microservices/world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state), rather than repeated in this tracker. +Game Design owns revision history, commits, version state, and publish orchestration; World Management owns authoritative Draft and Published world template rows. `SaveRevision` is version-scoped and carries typed `worldDesignMutation` payloads, including `WORLD_GENERATION_SUBTREE`, through the canonical World Management API. The first caller path saves revision history and applies the concrete change through that API rather than directly mutating World tables or treating opaque revision JSON as the authoritative world graph. The current seam permits only Draft version design-time writes; Published, Active, Failed, and Retired scopes are rejected. World terminal completion and Account terminal readback have unregistered local authenticated adapters, and Account has a candidate for retaining both matching owner outcomes before settlement. The current freeze/publication producer, creator currentness, registration, live composition and executed proof remain absent or unproved; exact owner semantics remain in the [World Management owner contract](../../architecture/microservices/world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state), rather than repeated in this tracker. ### Validation and Proof 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 14e1f339a2..b2864e4c23 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 current local publication-handoff candidate adds unregistered, default-denied World completion and Account read adapters plus Account's two-owner terminal reconciliation. World completion authenticates the exact same-namespace Game Design workload, independently rereads Game Design's definitive terminal outside the World transaction, then commits the matching `PUBLISHED`/`ABORTED` terminal and owner phase atomically; the Account read adapter authenticates Account and independently returns exact retained World terminal evidence. Account reads Game Design and World outside its owner transaction, compares the complete original operation and terminal bytes, retains both immutable matching owner results, and only then settles the source fence under consistent source-lock ordering. V44 canonical preparation consumes that exact retained `PUBLISHED` terminal and original frozen capture. The components remain unregistered and default-denied; they do not supply the current original publication-authorizing creator producer or the distinct fresh lifecycle/serving authority needed for admission. New definitions and validation are pending the parent gate; local Docker is unavailable, upstream inputs in World PostgreSQL cases are isolated/mocked, and transport tests use a server double. This is not live publication, production readiness, or activation proof. The original publication epoch can precede a later launch-resolution epoch while retaining the exact immutable release content. + The #3035 V44 World publication-terminal candidate adds an unregistered, default-denied owner operation with immutable exact-retry PUBLISHED/ABORTED readback. Its explicit verifier consumes the separate Game Design terminal read; the owner transaction checks and seals the original freeze, source, Account/APPLIED and selector evidence. The terminal receipt and matching original owner phase must commit together, and independent readback rechecks their complete binding. Fresh V35 preparation now requires that exact retained PUBLISHED terminal and original frozen capture rather than FROZEN alone; it does not capture new source after terminalization. New PostgreSQL definitions exercise the owner transitions and preparation using explicitly isolated upstream evidence. Local component checks, schema generation and packaged builds pass, but all 170 World integration cases skip without Docker. They are not executed proof of PostgreSQL constraints, the real Game Design producer, live mTLS/service composition, or production authorization. The #3035 World delivery correction behind #3029 adds an unregistered, default-denied V43 canonical activation operation and an immutable exact-retry result. The owner transaction independently reconstructs the same complete association/materialization evidence, locks the actual lifecycle row and commits its `PREPARING -> ACTIVE` CAS with the result; raw SQL cannot commit a success ledger without that CAS or activate the canonical row through the legacy numeric writer. New definitions cover stale outcomes, exact concurrent retry, lost held-authority rollback, self-consistent forged evidence rejected against independent owner rows, and historical recovery after later lifecycle movement. Local component checks pass, while PostgreSQL execution remains unavailable locally without Docker; these definitions and an explicitly isolated verifier do not supply authenticated live activation, placement, region preparation or admission. The [World API contract](../../architecture/microservices/world-management-service/api-contracts.md#canonical-instance-activation-and-lifecycle-readback) owns the operation and historical-versus-current evidence distinction. @@ -14,7 +16,7 @@ Fresh Account lifecycle/serving authority remains a concrete missing producer, d 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. V44 now requires fresh canonical materialization to consume the exact retained PUBLISHED terminal and original capture; tests for this continuation use isolated synthetic upstream evidence and remain pending validation. The live authenticated Game Design terminal producer/service composition, complete protected current authorization and lifecycle/Game Session handoff remain open. No activation or public canonical writer is enabled. +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. V44 now requires fresh canonical materialization to consume the exact retained PUBLISHED terminal and original capture; tests for this continuation use isolated synthetic upstream evidence and remain pending validation. The terminal completion/read adapters now exist as unregistered candidates, but the current original publication-authorizing creator producer, separate fresh lifecycle/serving authority and 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. @@ -87,7 +89,7 @@ At exact published `19d8719e99aa1c39e2fc7aa1e31ab18d1ed07b69`, [CI37333148281](h The current publication candidate reuses one six-family database graph reader for both FROZEN capture and explicitly unwired OPEN region staging. OPEN staging resolves committed intake and V27 private keys under the existing owner lock, checks the enclosing commit's exact Game Design source provenance, and returns immutable unverified content without applying it or advancing synchronized visibility. At source `9cf395d17398fe0b7fef8fae3a9e58d59e2ed949`, raw XML from [CI37326159559](https://github.com/benhook1013/FireMUD/actions/runs/37326159559) records all eight publication-fence PostgreSQL cases passing and all eight graph cases executing: two passed and six failed, with no skips. Four staging fixtures supplied a blank Game Design tenant key; two schema-denial assertions expected jOOQ exceptions instead of Spring's translated `DataIntegrityViolationException`. The fixtures now use the exact retained intake source key and check the actual translated exception plus SQLSTATE `23514` and the applicable owner constraint, preserving no-mutation assertions. Workflow-dispatch metadata pins the source; runner checkout was not independently verified. Corrected execution remains open; staged representation and freeze storage still do not prove an authenticated owner apply, synchronized normal reads, release eligibility, fresh canonical content production or runtime topology materialization. -The authored-publication candidate qualifies the shared V25 writer/freeze lock through the exact V27 canonical Version, committed source intake and private World Version association. V28 retains immutable six-family graph bytes, source/attempt bindings and exact retry readback, but every capture remains `CAPTURED_UNVERIFIED`: the ledger and caller-supplied affected tuples do not prove a complete synchronized owner commit. New captures require the exact still-frozen attempt; historical readback does not create another capture after terminal state. The ordered REGION plan independently derives both required tuples. A shared immutable graph codec preserves the existing six-family bytes; the pure stager updates supported existing region rows, retains untouched families and complete bindings, and rejects missing, duplicate or inconsistent targets without partial output. Staging neither authenticates input nor writes content, advances epochs, reports `APPLIED` or creates release eligibility. The focused World check passes with 246 clean unit results; all 61 PostgreSQL methods compile but skip locally without Docker. Graph fixtures stipulate synthetic content/ledger rows, restore normal triggers before the tested boundary and preserve V24 canonical-key write denial; they do not prove a canonical content producer. Raw XML from [CI37310255054](https://github.com/benhook1013/FireMUD/actions/runs/37310255054) records eight fence executions, seven passing and one failing because the cross-Version fixture assigned contradictory tenant-source rows. The fixture now preserves one authoritative tenant source for both distinct Version receipts and also asserts contradictory-source denial; corrected PostgreSQL execution remains open. That prerequisite failure prevented later graph capture, so the four graph cases have no executed runner proof. No ordinary writer, authenticated freeze/terminal producer, complete owner-commit producer, released-graph reader or canonical lifecycle route consumes these components yet. Canonical Game Session instance UUID to private World run association and atomic complete released-topology materialization remain required before `PREPARING`; source/descriptor receipts and numeric aliases are not substitutes. +The authored-publication candidate qualifies the shared V25 writer/freeze lock through the exact V27 canonical Version, committed source intake and private World Version association. V28 retains immutable six-family graph bytes, source/attempt bindings and exact retry readback, but every capture remains `CAPTURED_UNVERIFIED`: the ledger and caller-supplied affected tuples do not prove a complete synchronized owner commit. New captures require the exact still-frozen attempt; historical readback does not create another capture after terminal state. The ordered REGION plan independently derives both required tuples. A shared immutable graph codec preserves the existing six-family bytes; the pure stager updates supported existing region rows, retains untouched families and complete bindings, and rejects missing, duplicate or inconsistent targets without partial output. Staging neither authenticates input nor writes content, advances epochs, reports `APPLIED` or creates release eligibility. The focused World check passes with 246 clean unit results; all 61 PostgreSQL methods compile but skip locally without Docker. Graph fixtures stipulate synthetic content/ledger rows, restore normal triggers before the tested boundary and preserve V24 canonical-key write denial; they do not prove a canonical content producer. Raw XML from [CI37310255054](https://github.com/benhook1013/FireMUD/actions/runs/37310255054) records eight fence executions, seven passing and one failing because the cross-Version fixture assigned contradictory tenant-source rows. The fixture now preserves one authoritative tenant source for both distinct Version receipts and also asserts contradictory-source denial; corrected PostgreSQL execution remains open. That prerequisite failure prevented later graph capture, so the four graph cases have no executed runner proof. No ordinary writer or authenticated freeze producer is available; the terminal completion/read adapters described above remain unregistered and lack live production composition. Complete owner-commit production, a released-graph reader and a canonical lifecycle route also remain absent. Canonical Game Session instance UUID to private World run association and atomic complete released-topology materialization remain required before `PREPARING`; source/descriptor receipts and numeric aliases are not substitutes. The held-back World mutation algorithm now uses full-tuple, expected-epoch SQL predicates for its declared aggregate and scope advances. An absent epoch can be claimed only from zero with a conflict-safe insert; stale, negative or overflowing expected counters cannot succeed. A losing advance raises `DRAFT_WRITE_CONFLICT` inside the existing owner transaction rather than committing content under an unconditional epoch save. The focused mutation suite executed 29 cases successfully. The consolidated World check, boot JAR, formatting, static analysis, links and Markdown passed with 227 unit executions and no unit skips; all 55 PostgreSQL integration methods, including five new deterministic race, tuple-isolation and rollback cases, compiled but skipped locally without Docker. The subsequent exact-source CI execution is recorded below. This closes a local storage primitive, not complete affected-scope validation, immutable complete-input retry binding, source-qualified content materialization, synchronized Draft visibility, Account authorization, publication or lifecycle. The registered mutation remains denied. [ADR 0129](../../architecture/decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) remains the target contract. @@ -229,7 +231,7 @@ These links add decision provenance only; they do not upgrade world runtime, lif ### Draft World Topology, Generation, and Mutation Authority - World Management is the canonical owner of version-scoped Draft mutation through typed `ApplyWorldDesignMutation` operations for regions, zones, rooms, room exits, generation rules, world-entity spawn bindings, and generated world subtrees. Runtime instance mutation and live Published-version editing are not routed through this design-time API. -- Publication handoff remains target-only and unproved in the current slice. [World Management API Contracts](../../architecture/microservices/world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state) is the sole canonical owner-operation contract; Game Design [Version Control](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff) owns cross-service handoff/orchestration context, while WMS [runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md) records local status/proof consequences. This tracker records only that status and proof rather than repeating operation fields. +- Authenticated terminal completion and Account-to-World terminal readback now have unregistered local candidates, and Account's reconciliation candidate retains both exact matching owner results before source settlement. The end-to-end publication handoff remains unproved: the current freeze/publication producer, current original publication-authorizing creator producer, production registration/composition, executed PostgreSQL proof and separate fresh lifecycle/serving authority are still missing or denied. [World Management API Contracts](../../architecture/microservices/world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state) is the sole canonical owner-operation contract; Game Design [Version Control](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff) owns cross-service handoff/orchestration context, while WMS [runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md) records local status/proof consequences. This tracker records only that status and proof rather than repeating operation fields. - Each successful Draft mutation uses an applied-revision ledger or equivalent guard in the same transaction as the write. The idempotency identity includes `(tenantId, versionId, commitId, revisionId, operationType, aggregateType, aggregateId)`. Replaying a `revisionId` is a no-op; stale `expectedDraftRevisionEpoch` or `expectedDraftScopeRevisionEpoch` values fail closed as `DRAFT_WRITE_CONFLICT` rather than being rebased or merged. The contract also exposes typed application outcomes including `APPLIED`, `NO_OP_ALREADY_APPLIED`, `DRAFT_WRITE_CONFLICT`, `UNRESOLVED_REFERENCE`, `OUT_OF_SYNC`, `INVALID_VERSION_STATE`, and `UNSUPPORTED_SCOPE`. - Generation targets are typed scope enums: `REGION_SUBTREE`, `ZONE_SUBTREE`, and `NEW_EMPTY_REGION`. Scope epochs are keyed by tenant, version, scope type, and positive scope id. One canonical positive scope-id reader and normalized scope-id representation are used across region, zone, room, room-exit, generation-rule, spawn-binding, and generated-subtree validation; declared scope is validated before topology upserts reach the repository. - `REPLACE_SCOPE` deterministically clears and replaces prior generated rooms, exits, generation rules, and spawn bindings within a supported region or zone scope. Generated exits and spawn bindings may target only rooms created by the same payload. Spawn-binding replacement clears prior in-scope bindings, rejects out-of-scope bindings, and rejects unsupported `NEW_EMPTY_REGION` combinations. diff --git a/protos/world-management/v1/publication_terminal_service.proto b/protos/world-management/v1/publication_terminal_service.proto new file mode 100644 index 0000000000..17fe61db7d --- /dev/null +++ b/protos/world-management/v1/publication_terminal_service.proto @@ -0,0 +1,36 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Explicit authenticated World owner read, without runtime lifecycle registration. +service WorldPublicationTerminalReadService { + rpc ReadWorldPublicationTerminal(ReadWorldPublicationTerminalRequest) + returns (ReadWorldPublicationTerminalResponse); +} + +message ReadWorldPublicationTerminalRequest { + bytes canonical_request_bytes = 1; +} + +message ReadWorldPublicationTerminalResponse { + // Exact request echo, explicit UNKNOWN or unchanged committed terminal evidence. + bytes canonical_response_bytes = 1; +} + +// Authenticated Game Design completion of the exact original publication operation. +service WorldPublicationTerminalCompletionService { + rpc CompleteWorldPublicationTerminal(CompleteWorldPublicationTerminalRequest) + returns (CompleteWorldPublicationTerminalResponse); +} + +message CompleteWorldPublicationTerminalRequest { + bytes canonical_request_bytes = 1; +} + +message CompleteWorldPublicationTerminalResponse { + // Exact original operation and terminal evidence echo after the World owner commit. + bytes canonical_response_bytes = 1; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authorpublication/AccountPublicationTerminalReconciliationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authorpublication/AccountPublicationTerminalReconciliationService.java new file mode 100644 index 0000000000..dd9bb84f9b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authorpublication/AccountPublicationTerminalReconciliationService.java @@ -0,0 +1,231 @@ +package net.firedevops.firemud.accountservice.authorpublication; + +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFenceRepository.Owner; +import net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFenceRepository.OwnerResultSnapshot; +import net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFenceRepository.Settlement; +import net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFenceRepository.TerminalSnapshot; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.world.WorldPublicationTerminalClient; +import net.firedevops.firemud.common.world.WorldPublicationTerminalReadEvidence; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Unregistered recovery component; it neither authenticates a creator nor enables publication. */ +public final class AccountPublicationTerminalReconciliationService { + private final PublicationAuthorizationFenceRepository repository; + private final GameDesignPublicationTerminalClient gameDesignClient; + private final WorldPublicationTerminalClient worldClient; + private final String namespace; + private final TransactionTemplate ownerTransaction; + + public AccountPublicationTerminalReconciliationService( + PublicationAuthorizationFenceRepository repository, + PlatformTransactionManager transactionManager, + GameDesignPublicationTerminalClient gameDesignClient, + WorldPublicationTerminalClient worldClient, + String namespace) { + this.repository = Objects.requireNonNull(repository); + this.gameDesignClient = Objects.requireNonNull(gameDesignClient); + this.worldClient = Objects.requireNonNull(worldClient); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical owner workload namespace required"); + } + this.namespace = namespace; + ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + /** + * Recovers only exact terminal readbacks for this complete allocated operation. Owner RPCs run + * between short Account transactions; unavailable or UNKNOWN evidence leaves the order pending. + */ + public Optional reconcile(byte[] operationBytes) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Publication terminal recovery cannot join an ambient transaction"); + } + GameDesignPublicationOperationBinding operation = + GameDesignPublicationOperationBinding.fromStored(operationBytes); + byte[] canonicalOperation = operation.canonicalBytes(); + if (!Arrays.equals(operationBytes, canonicalOperation)) { + throw new IllegalArgumentException("Noncanonical original Game Design publication operation"); + } + + Optional initial = + Objects.requireNonNull( + ownerTransaction.execute(status -> repository.readOriginalOperation(operation))); + if (initial.isEmpty()) { + return Optional.empty(); + } + TerminalSnapshot before = initial.orElseThrow(); + if (before.ordering() == PublicationAuthorizationFenceRepository.Ordering.RESERVED + || before.settlement() != Settlement.PENDING) { + return Optional.of(before.settlement()); + } + + Optional gameDesignEvidence = + before.gameDesignResult().map(AccountPublicationTerminalReconciliationService::terminal); + if (gameDesignEvidence.isEmpty()) { + gameDesignEvidence = readGameDesign(operation); + } + + Optional worldEvidence = + before.worldResult().map(AccountPublicationTerminalReconciliationService::terminal); + if (gameDesignEvidence.isPresent()) { + GameDesignPublicationTerminalEvidence design = gameDesignEvidence.orElseThrow(); + if (!Arrays.equals(design.operationBytes(), canonicalOperation)) { + throw new IllegalArgumentException( + "Game Design terminal result changed the original operation"); + } + if (worldEvidence.isPresent()) { + requireIdenticalTerminal(design, worldEvidence.orElseThrow()); + } else { + worldEvidence = readWorld(operation, design); + } + } + + Optional finalGameDesign = gameDesignEvidence; + Optional finalWorld = worldEvidence; + return Optional.ofNullable( + ownerTransaction.execute( + status -> { + TerminalSnapshot current = + repository + .readOriginalOperation(operation) + .orElseThrow( + () -> + new IllegalStateException( + "Original publication operation disappeared")); + if (current.ordering() != before.ordering()) { + throw new IllegalStateException( + "Original publication ordering changed during recovery"); + } + retainExactMissing(operation, Owner.GAME_DESIGN, finalGameDesign, current); + current = + repository + .readOriginalOperation(operation) + .orElseThrow( + () -> + new IllegalStateException( + "Original publication operation disappeared")); + if (current.ordering() != before.ordering()) { + throw new IllegalStateException( + "Original publication ordering changed during recovery"); + } + retainExactMissing(operation, Owner.WORLD, finalWorld, current); + return repository.readSettlement(operation); + })); + } + + private Optional readGameDesign( + GameDesignPublicationOperationBinding operation) { + try { + GameDesignPublicationTerminalReadEvidence.ReadRequest request = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + namespace, operation.canonicalBytes()); + GameDesignPublicationTerminalReadEvidence.ReadResult response = + Objects.requireNonNull(gameDesignClient.read(request)); + if (!Arrays.equals(request.canonicalBytes(), response.request().canonicalBytes())) { + throw new IllegalArgumentException("Game Design changed the exact terminal read request"); + } + if (response.status() == GameDesignPublicationTerminalReadEvidence.Status.UNKNOWN) { + return Optional.empty(); + } + GameDesignPublicationTerminalEvidence terminal = response.terminalEvidence().orElseThrow(); + if (!Arrays.equals(terminal.operationBytes(), operation.canonicalBytes()) + || !terminal.outcome().name().equals(response.status().name())) { + throw new IllegalArgumentException( + "Game Design returned a changed publication terminal result"); + } + return Optional.of(terminal); + } catch (RuntimeException unavailableOrInvalid) { + return Optional.empty(); + } + } + + private Optional readWorld( + GameDesignPublicationOperationBinding operation, + GameDesignPublicationTerminalEvidence gameDesignEvidence) { + try { + WorldPublicationTerminalReadEvidence.Request request = + WorldPublicationTerminalReadEvidence.Request.create( + namespace, gameDesignEvidence.canonicalBytes()); + WorldPublicationTerminalReadEvidence.ReadResult response = + Objects.requireNonNull(worldClient.read(request)); + if (!Arrays.equals(request.canonicalBytes(), response.request().canonicalBytes())) { + throw new IllegalArgumentException( + "World changed the exact publication terminal read request"); + } + WorldPublicationTerminalReadEvidence.Status expectedStatus = + gameDesignEvidence.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? WorldPublicationTerminalReadEvidence.Status.PUBLISHED + : WorldPublicationTerminalReadEvidence.Status.ABORTED; + if (response.status() == WorldPublicationTerminalReadEvidence.Status.UNKNOWN) { + return Optional.empty(); + } + GameDesignPublicationTerminalEvidence terminal = response.terminalEvidence().orElseThrow(); + if (response.status() != expectedStatus + || !Arrays.equals(terminal.canonicalBytes(), gameDesignEvidence.canonicalBytes()) + || !Arrays.equals(terminal.operationBytes(), operation.canonicalBytes())) { + throw new IllegalArgumentException( + "World returned changed or contradictory terminal evidence"); + } + return Optional.of(terminal); + } catch (RuntimeException unavailableOrInvalid) { + return Optional.empty(); + } + } + + private void retainExactMissing( + GameDesignPublicationOperationBinding operation, + Owner owner, + Optional candidate, + TerminalSnapshot snapshot) { + if (candidate.isEmpty()) { + return; + } + Optional existing = + owner == Owner.GAME_DESIGN ? snapshot.gameDesignResult() : snapshot.worldResult(); + GameDesignPublicationTerminalEvidence terminal = candidate.orElseThrow(); + if (existing.isPresent()) { + if (!Arrays.equals(existing.orElseThrow().operationBytes(), operation.canonicalBytes()) + || !Arrays.equals(existing.orElseThrow().terminalBytes(), terminal.canonicalBytes())) { + throw new IllegalArgumentException( + "Concurrent publication recovery changed immutable owner evidence"); + } + return; + } + repository.recordOwnerResult(operation, owner, terminal); + } + + private static GameDesignPublicationTerminalEvidence terminal(OwnerResultSnapshot result) { + GameDesignPublicationTerminalEvidence terminal = + GameDesignPublicationTerminalEvidence.fromStored(result.terminalBytes()); + if (terminal.outcome() != result.outcome() + || !Arrays.equals(terminal.operationBytes(), result.operationBytes())) { + throw new IllegalStateException( + "Stored publication owner result differs from its terminal bytes"); + } + return terminal; + } + + private static void requireIdenticalTerminal( + GameDesignPublicationTerminalEvidence gameDesign, + GameDesignPublicationTerminalEvidence world) { + if (!Arrays.equals(gameDesign.canonicalBytes(), world.canonicalBytes())) { + throw new IllegalArgumentException("Game Design and World terminal evidence differs"); + } + } +} 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 index c6ccb3ae68..ed73d36940 100644 --- 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 @@ -11,8 +11,11 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -23,8 +26,9 @@ * 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. + * cannot settle publication; only exact owner terminal evidence supplied by the separate concrete + * authenticated clients can be retained. SQL guards establish structural consistency, not peer + * authentication. */ public final class PublicationAuthorizationFenceRepository { private final DSLContext dsl; @@ -42,6 +46,17 @@ public enum Ordering { REVOKE_ORDER } + public enum Owner { + GAME_DESIGN, + WORLD + } + + public enum Settlement { + PENDING, + PUBLISHED, + NO_PUBLICATION + } + public record Snapshot( Ordering ordering, byte[] binding, OffsetDateTime reservedAt, OffsetDateTime orderedAt) { public Snapshot { @@ -54,6 +69,40 @@ public byte[] binding() { } } + public record OwnerResultSnapshot( + GameDesignPublicationTerminalEvidence.Outcome outcome, + byte[] operationBytes, + byte[] terminalBytes, + OffsetDateTime recordedAt) { + public OwnerResultSnapshot { + operationBytes = operationBytes.clone(); + terminalBytes = terminalBytes.clone(); + } + + @Override + public byte[] operationBytes() { + return operationBytes.clone(); + } + + @Override + public byte[] terminalBytes() { + return terminalBytes.clone(); + } + } + + public record TerminalSnapshot( + Ordering ordering, + Settlement settlement, + Optional gameDesignResult, + Optional worldResult) { + public TerminalSnapshot { + Objects.requireNonNull(ordering); + Objects.requireNonNull(settlement); + gameDesignResult = Objects.requireNonNull(gameDesignResult); + worldResult = Objects.requireNonNull(worldResult); + } + } + public Snapshot reserve(AccountPublicationAuthorizationBinding binding) { requireTransaction(); lockSources(binding.sources()); @@ -123,22 +172,137 @@ public Snapshot claimPublicationOrder(AccountPublicationAuthorizationBinding bin public Snapshot read(AccountPublicationAuthorizationBinding binding) { requireTransaction(); + lockSources(binding.sources()); 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) { + Record unlocked = unlockedOperation(operationId); + if (unlocked == null) { return Optional.empty(); } - var binding = - AccountPublicationAuthorizationBinding.fromStored(row.get("binding", byte[].class)); + AccountPublicationAuthorizationBinding binding = originalBinding(unlocked); + lockSources(binding.sources()); + Record row = operation(operationId); requireExact(row, binding); return Optional.of(binding); } + /** + * Reads the full post-allocation operation after learning the immutable Account source vector + * without a row lock. Shared source locks are always held before the operation row is locked. + */ + public Optional readOriginalOperation( + GameDesignPublicationOperationBinding candidate) { + requireTransaction(); + Objects.requireNonNull(candidate); + Record unlocked = unlockedOperation(candidate.account().operationId()); + if (unlocked == null) { + return Optional.empty(); + } + AccountPublicationAuthorizationBinding original = originalBinding(unlocked); + requireCandidateAccount(candidate, original); + lockSources(original.sources()); + Record row = operation(original.operationId()); + requireExact(row, original); + requireCandidateAccount(candidate, original); + Ordering ordering = Ordering.valueOf(row.get("ordering", String.class)); + Optional gameDesign = readOwnerResultLocked(candidate, Owner.GAME_DESIGN); + Optional world = readOwnerResultLocked(candidate, Owner.WORLD); + return Optional.of( + new TerminalSnapshot(ordering, settlement(ordering, gameDesign, world), gameDesign, world)); + } + + /** + * Stores a result returned through the explicitly authenticated owner client. SQL itself proves + * only structural consistency; it cannot prove that a caller authenticated either owner. + */ + public OwnerResultSnapshot recordOwnerResult( + GameDesignPublicationOperationBinding originalBinding, + Owner owner, + GameDesignPublicationTerminalEvidence terminal) { + requireTransaction(); + Objects.requireNonNull(originalBinding); + Objects.requireNonNull(owner); + Objects.requireNonNull(terminal); + GameDesignPublicationOperationBinding operationBinding = + GameDesignPublicationOperationBinding.fromStored(originalBinding.canonicalBytes()); + GameDesignPublicationTerminalEvidence terminalEvidence = + GameDesignPublicationTerminalEvidence.fromStored(terminal.canonicalBytes()); + if (!Arrays.equals(operationBinding.canonicalBytes(), terminalEvidence.operationBytes())) { + throw new IllegalArgumentException( + "Owner terminal result differs from exact original operation"); + } + + AccountPublicationAuthorizationBinding account = operationBinding.account(); + lockSources(account.sources()); + Record row = operation(account.operationId()); + requireExact(row, account); + Ordering ordering = Ordering.valueOf(row.get("ordering", String.class)); + if (ordering == Ordering.RESERVED) { + throw new IllegalStateException( + "Reservation alone cannot record publication terminal evidence"); + } + if (ordering == Ordering.REVOKE_ORDER + && terminalEvidence.outcome() + != GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION) { + throw new IllegalStateException("Revocation order permits only no-publication evidence"); + } + + Optional current = readOwnerResultLocked(operationBinding, owner); + if (current.isPresent()) { + OwnerResultSnapshot stored = current.orElseThrow(); + requireSameResult(stored, operationBinding, terminalEvidence); + return stored; + } + Owner otherOwner = owner == Owner.GAME_DESIGN ? Owner.WORLD : Owner.GAME_DESIGN; + Optional counterpart = readOwnerResultLocked(operationBinding, otherOwner); + if (counterpart.isPresent()) { + requireSameResult(counterpart.orElseThrow(), operationBinding, terminalEvidence); + } + dsl.execute( + "INSERT INTO account_publication_authorization_owner_results" + + " (operation_id, owner, outcome, operation_bytes, terminal_bytes)" + + " VALUES (?, ?, ?, ?, ?)", + account.operationId(), + owner.name(), + terminalEvidence.outcome().name(), + operationBinding.canonicalBytes(), + terminalEvidence.canonicalBytes()); + return readOwnerResultLocked(operationBinding, owner) + .orElseThrow(() -> new IllegalStateException("Publication owner result did not read back")); + } + + /** Absence means UNKNOWN; retained bytes are structural storage, not authentication evidence. */ + public Optional readOwnerResult( + GameDesignPublicationOperationBinding originalBinding, Owner owner) { + requireTransaction(); + Objects.requireNonNull(originalBinding); + Objects.requireNonNull(owner); + AccountPublicationAuthorizationBinding account = originalBinding.account(); + lockSources(account.sources()); + Record row = operation(account.operationId()); + requireExact(row, account); + return readOwnerResultLocked(originalBinding, owner); + } + + /** Settlement is derived only from immutable order and two byte-identical owner results. */ + public Settlement readSettlement(GameDesignPublicationOperationBinding originalBinding) { + requireTransaction(); + Objects.requireNonNull(originalBinding); + AccountPublicationAuthorizationBinding account = originalBinding.account(); + lockSources(account.sources()); + Record row = operation(account.operationId()); + requireExact(row, account); + Ordering ordering = Ordering.valueOf(row.get("ordering", String.class)); + Optional gameDesign = + readOwnerResultLocked(originalBinding, Owner.GAME_DESIGN); + Optional world = readOwnerResultLocked(originalBinding, Owner.WORLD); + return settlement(ordering, gameDesign, world); + } + /** Called by the existing source-change writer under its shared source locks. */ public void revokeAffected(List sources) { requireTransaction(); @@ -156,16 +320,32 @@ public void revokeAffected(List sources) { } /** - * No terminal shortcut exists: neither expiry, FAILED, nor Draft readback releases this order. + * Every related publication must have its two matching owner results under the original source + * order. Expiry, FAILED, and Draft readback are never terminal publication evidence. */ public boolean allAffectedSettled(List sources) { requireTransaction(); lockSources(sources); List affected = affectedOperations(sources); + Map originals = new java.util.LinkedHashMap<>(); + for (UUID id : affected) { + Record unlocked = unlockedOperation(id); + AccountPublicationAuthorizationBinding original = originalBinding(unlocked); + originals.put(id, original); + } for (UUID id : affected) { - operation(id); + AccountPublicationAuthorizationBinding original = originals.get(id); + Record row = operation(id); + requireExact(row, original); + Ordering ordering = Ordering.valueOf(row.get("ordering", String.class)); + Optional gameDesign = + readStoredOwnerResultLocked(original, Owner.GAME_DESIGN); + Optional world = readStoredOwnerResultLocked(original, Owner.WORLD); + if (settlement(ordering, gameDesign, world) == Settlement.PENDING) { + return false; + } } - return affected.isEmpty(); + return true; } private List affectedOperations(List sources) { @@ -183,8 +363,146 @@ private List affectedOperations(List sources) { .toList(); } + private AccountPublicationAuthorizationBinding originalBinding(Record row) { + if (row == null) { + throw new IllegalStateException("Affected publication operation disappeared"); + } + return AccountPublicationAuthorizationBinding.fromStored(row.get("binding", byte[].class)); + } + + private Optional readOwnerResultLocked( + GameDesignPublicationOperationBinding candidate, Owner owner) { + return readOwnerResultLocked(candidate.account(), candidate, owner); + } + + private Optional readStoredOwnerResultLocked( + AccountPublicationAuthorizationBinding original, Owner owner) { + return readOwnerResultLocked(original, null, owner); + } + + private Optional readOwnerResultLocked( + AccountPublicationAuthorizationBinding original, + GameDesignPublicationOperationBinding candidate, + Owner owner) { + Record result = ownerResultRow(original, owner); + if (result == null) return Optional.empty(); + OwnerResultSnapshot decoded = structuralOwnerResult(result, original); + GameDesignPublicationOperationBinding storedOperation = + GameDesignPublicationOperationBinding.fromStored(decoded.operationBytes()); + requireCandidateAccount(storedOperation, original); + GameDesignPublicationTerminalEvidence.fromStored(decoded.terminalBytes()); + if (candidate != null) { + if (!Arrays.equals(candidate.canonicalBytes(), decoded.operationBytes())) { + throw new IllegalArgumentException( + "Stored owner result differs from the exact candidate operation"); + } + } + return Optional.of(decoded); + } + + private Record ownerResultRow(AccountPublicationAuthorizationBinding original, Owner owner) { + return dsl.fetchOne( + "SELECT outcome, operation_bytes, terminal_bytes, recorded_at" + + " FROM account_publication_authorization_owner_results" + + " WHERE operation_id = ? AND owner = ?", + original.operationId(), + owner.name()); + } + + private static OwnerResultSnapshot structuralOwnerResult( + Record row, AccountPublicationAuthorizationBinding original) { + byte[] operationBytes = row.get("operation_bytes", byte[].class); + byte[] terminalBytes = row.get("terminal_bytes", byte[].class); + var operationReader = new DraftAuthorizationFenceBinding.FrameReader(operationBytes); + operationReader.expect(GameDesignPublicationOperationBinding.SCHEMA); + if (!Arrays.equals(operationReader.bytes(), original.canonicalBytes())) { + throw new IllegalStateException( + "Stored publication owner operation changed its Account binding"); + } + if (operationReader.bytes().length == 0) { + throw new IllegalStateException( + "Stored publication owner operation omits the World checkpoint"); + } + operationReader.requireEnd(); + + var terminalReader = new DraftAuthorizationFenceBinding.FrameReader(terminalBytes); + terminalReader.expect(GameDesignPublicationTerminalEvidence.SCHEMA); + if (!Arrays.equals(terminalReader.bytes(), operationBytes)) { + throw new IllegalStateException( + "Stored publication terminal changed its complete operation bytes"); + } + GameDesignPublicationTerminalEvidence.Outcome outcome = + GameDesignPublicationTerminalEvidence.Outcome.valueOf(terminalReader.text()); + if (outcome == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED) { + if (terminalReader.bytes().length == 0) { + throw new IllegalStateException("Published terminal omits release evidence bytes"); + } + String epoch = terminalReader.text(); + DraftAuthorizationFenceBinding.decimal(epoch, false); + try { + Long.parseLong(epoch); + } catch (NumberFormatException invalid) { + throw new IllegalStateException("Published terminal epoch exceeds owner range", invalid); + } + } + terminalReader.requireEnd(); + if (!outcome.name().equals(row.get("outcome", String.class))) { + throw new IllegalStateException( + "Stored publication owner outcome differs from terminal bytes"); + } + return new OwnerResultSnapshot( + outcome, operationBytes, terminalBytes, row.get("recorded_at", OffsetDateTime.class)); + } + + private static void requireCandidateAccount( + GameDesignPublicationOperationBinding candidate, + AccountPublicationAuthorizationBinding original) { + if (!Arrays.equals(candidate.account().canonicalBytes(), original.canonicalBytes())) { + throw new IllegalArgumentException( + "Game Design operation changed the original Account binding"); + } + } + + private static void requireSameResult( + OwnerResultSnapshot existing, + GameDesignPublicationOperationBinding operation, + GameDesignPublicationTerminalEvidence terminal) { + if (existing.outcome() != terminal.outcome() + || !Arrays.equals(existing.operationBytes(), operation.canonicalBytes()) + || !Arrays.equals(existing.terminalBytes(), terminal.canonicalBytes())) { + throw new IllegalArgumentException("Changed or contradictory publication terminal evidence"); + } + } + + private static Settlement settlement( + Ordering ordering, + Optional gameDesign, + Optional world) { + if (ordering == Ordering.RESERVED || gameDesign.isEmpty() || world.isEmpty()) { + return Settlement.PENDING; + } + OwnerResultSnapshot design = gameDesign.orElseThrow(); + OwnerResultSnapshot worldResult = world.orElseThrow(); + if (design.outcome() != worldResult.outcome() + || !Arrays.equals(design.operationBytes(), worldResult.operationBytes()) + || !Arrays.equals(design.terminalBytes(), worldResult.terminalBytes())) { + return Settlement.PENDING; + } + if (ordering == Ordering.REVOKE_ORDER + && design.outcome() != GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION) { + return Settlement.PENDING; + } + return design.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? Settlement.PUBLISHED + : Settlement.NO_PUBLICATION; + } + private void lockSources(List sources) { - for (String key : sources.stream().map(SourceEvidence::key).distinct().sorted().toList()) { + lockSourceKeys(sources.stream().map(SourceEvidence::key).toList()); + } + + private void lockSourceKeys(List sourceKeys) { + for (String key : sourceKeys.stream().distinct().sorted().toList()) { dsl.execute( "INSERT INTO account_draft_authorization_source_locks (source_key)" + " VALUES (?) ON CONFLICT DO NOTHING", @@ -215,6 +533,11 @@ private Record operation(UUID id) { id); } + private Record unlockedOperation(UUID id) { + return dsl.fetchOne( + "SELECT * FROM account_publication_authorization_fences WHERE operation_id = ?", id); + } + private Record requireExact(Record row, AccountPublicationAuthorizationBinding binding) { if (row == null || !binding.operationId().equals(row.get("operation_id", UUID.class)) diff --git a/services/account-service/src/main/resources/db/migration/V80__publication_authorization_terminal_settlement.sql b/services/account-service/src/main/resources/db/migration/V80__publication_authorization_terminal_settlement.sql new file mode 100644 index 0000000000..3946d46c2b --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V80__publication_authorization_terminal_settlement.sql @@ -0,0 +1,227 @@ +-- Internal structural storage for authenticated publication owner readbacks. A valid row is not +-- itself proof that either owner authenticated its producer; only the unregistered Account +-- reconciler may supply owner provenance through the concrete mTLS clients. +CREATE TABLE account_publication_authorization_owner_results ( + operation_id UUID NOT NULL REFERENCES account_publication_authorization_fences(operation_id), + owner VARCHAR(16) NOT NULL CHECK (owner IN ('GAME_DESIGN', 'WORLD')), + outcome VARCHAR(16) NOT NULL CHECK (outcome IN ('PUBLISHED', 'NO_PUBLICATION')), + operation_bytes BYTEA NOT NULL CHECK (octet_length(operation_bytes) > 0), + terminal_bytes BYTEA NOT NULL CHECK (octet_length(terminal_bytes) > 0), + recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (operation_id, owner) +); + +-- [jooq ignore start] +CREATE FUNCTION account_publication_authorization_read_frame( + encoded BYTEA, + position_value INTEGER, + OUT frame_value BYTEA, + OUT next_position INTEGER) +RETURNS RECORD LANGUAGE plpgsql IMMUTABLE STRICT AS $$ +DECLARE + frame_length BIGINT; + encoded_length INTEGER := octet_length(encoded); +BEGIN + IF position_value < 1 OR position_value > encoded_length - 3 + OR get_byte(encoded, position_value - 1) >= 128 THEN + RAISE EXCEPTION 'Publication terminal byte frame is truncated or oversized' + USING ERRCODE = '23514'; + END IF; + frame_length := get_byte(encoded, position_value - 1)::BIGINT * 16777216 + + get_byte(encoded, position_value)::BIGINT * 65536 + + get_byte(encoded, position_value + 1)::BIGINT * 256 + + get_byte(encoded, position_value + 2)::BIGINT; + IF frame_length > encoded_length - position_value - 3 THEN + RAISE EXCEPTION 'Publication terminal byte frame is incomplete' + USING ERRCODE = '23514'; + END IF; + frame_value := substring(encoded FROM position_value + 4 FOR frame_length::INTEGER); + next_position := position_value + 4 + frame_length::INTEGER; + RETURN; +END; +$$; + +CREATE FUNCTION account_publication_authorization_owner_result_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + fence account_publication_authorization_fences%ROWTYPE; + key_value TEXT; + operation_prefix BYTEA; + terminal_prefix BYTEA; + parsed_frame BYTEA; + next_position INTEGER; + epoch_frame BYTEA; + epoch_text TEXT; + other_outcome TEXT; + other_operation BYTEA; + other_terminal BYTEA; + tail BYTEA; + terminal_tail_length INTEGER; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Publication owner results are immutable' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO fence FROM account_publication_authorization_fences + WHERE operation_id = NEW.operation_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Original publication authorization is absent' + USING ERRCODE = '23514'; + END IF; + -- Match the existing Java source-key order before taking the operation lock. + FOR key_value IN SELECT source.source_key + FROM account_publication_authorization_sources source + WHERE source.operation_id = NEW.operation_id + ORDER BY account_publication_authorization_source_sort_key(source.source_key) LOOP + PERFORM 1 FROM account_draft_authorization_source_locks lock_row + WHERE lock_row.source_key = key_value FOR UPDATE; + END LOOP; + SELECT * INTO fence FROM account_publication_authorization_fences + WHERE operation_id = NEW.operation_id FOR UPDATE; + IF fence.ordering = 'RESERVED' THEN + RAISE EXCEPTION 'Publication reservation cannot record terminal owner results' + USING ERRCODE = '23514'; + END IF; + IF fence.ordering = 'REVOKE_ORDER' AND NEW.outcome <> 'NO_PUBLICATION' THEN + RAISE EXCEPTION 'Revocation order permits only no-publication owner results' + USING ERRCODE = '23514'; + END IF; + IF (SELECT count(*) FROM account_publication_authorization_sources + WHERE operation_id = NEW.operation_id) + <> jsonb_array_length(fence.source_vector) THEN + RAISE EXCEPTION 'Complete original publication source capture is required' + USING ERRCODE = '23514'; + END IF; + + operation_prefix := account_tenant_creation_authorization_frame( + convert_to('game-design-publication-operation/v1', 'UTF8')) + || account_tenant_creation_authorization_frame(fence.binding); + IF substring(NEW.operation_bytes FROM 1 FOR octet_length(operation_prefix)) + IS DISTINCT FROM operation_prefix THEN + RAISE EXCEPTION 'Owner operation must contain the complete original Account binding' + USING ERRCODE = '23514'; + END IF; + SELECT decoded_frame.frame_value, decoded_frame.next_position + INTO parsed_frame, next_position + FROM account_publication_authorization_read_frame( + NEW.operation_bytes, octet_length(operation_prefix) + 1) AS decoded_frame; + IF octet_length(parsed_frame) = 0 OR next_position <> octet_length(NEW.operation_bytes) + 1 THEN + RAISE EXCEPTION 'Owner operation must retain one complete World publication checkpoint' + USING ERRCODE = '23514'; + END IF; + + terminal_prefix := account_tenant_creation_authorization_frame( + convert_to('game-design-publication-terminal/v1', 'UTF8')) + || account_tenant_creation_authorization_frame(NEW.operation_bytes) + || account_tenant_creation_authorization_frame(convert_to(NEW.outcome, 'UTF8')); + IF NEW.outcome = 'NO_PUBLICATION' THEN + IF NEW.terminal_bytes IS DISTINCT FROM terminal_prefix THEN + RAISE EXCEPTION 'No-publication terminal bytes must bind the complete original operation' + USING ERRCODE = '23514'; + END IF; + ELSE + IF substring(NEW.terminal_bytes FROM 1 FOR octet_length(terminal_prefix)) + IS DISTINCT FROM terminal_prefix THEN + RAISE EXCEPTION 'Published terminal bytes must bind the complete original operation' + USING ERRCODE = '23514'; + END IF; + tail := substring(NEW.terminal_bytes FROM octet_length(terminal_prefix) + 1); + SELECT decoded_frame.frame_value, decoded_frame.next_position + INTO parsed_frame, next_position + FROM account_publication_authorization_read_frame(tail, 1) AS decoded_frame; + IF octet_length(parsed_frame) = 0 THEN + RAISE EXCEPTION 'Published terminal requires complete release evidence bytes' + USING ERRCODE = '23514'; + END IF; + SELECT decoded_frame.frame_value, decoded_frame.next_position + INTO epoch_frame, terminal_tail_length + FROM account_publication_authorization_read_frame(tail, next_position) AS decoded_frame; + IF terminal_tail_length <> octet_length(tail) + 1 THEN + RAISE EXCEPTION 'Published terminal has trailing or incomplete evidence bytes' + USING ERRCODE = '23514'; + END IF; + epoch_text := convert_from(epoch_frame, 'UTF8'); + IF epoch_text !~ '^[1-9][0-9]*$' OR char_length(epoch_text) > 19 + OR (char_length(epoch_text) = 19 AND epoch_text > '9223372036854775807') THEN + RAISE EXCEPTION 'Published terminal requires canonical positive publication epoch' + USING ERRCODE = '23514'; + END IF; + END IF; + + SELECT outcome, operation_bytes, terminal_bytes + INTO other_outcome, other_operation, other_terminal + FROM account_publication_authorization_owner_results + WHERE operation_id = NEW.operation_id AND owner <> NEW.owner; + IF FOUND AND (other_outcome IS DISTINCT FROM NEW.outcome + OR other_operation IS DISTINCT FROM NEW.operation_bytes + OR other_terminal IS DISTINCT FROM NEW.terminal_bytes) THEN + RAISE EXCEPTION 'Publication owners must retain byte-identical terminal evidence' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_publication_authorization_owner_no_truncate() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Publication owner results cannot be truncated' + USING ERRCODE = '23514'; + RETURN NULL; +END; +$$; + +CREATE OR REPLACE FUNCTION account_publication_authorization_source_transition_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + key_value TEXT; + publication_id UUID; + publication_ordering TEXT; + result_count INTEGER; + outcome_count INTEGER; + operation_count INTEGER; + terminal_count INTEGER; +BEGIN + -- Serialize direct SQL source changes with every publication that references a changed scope. + FOR key_value IN SELECT changed.source_key FROM account_draft_authorization_changed_scopes changed + WHERE changed.change_id = OLD.change_id + ORDER BY account_publication_authorization_source_sort_key(changed.source_key) LOOP + PERFORM 1 FROM account_draft_authorization_source_locks lock_row + WHERE lock_row.source_key = key_value FOR UPDATE; + END LOOP; + FOR publication_id IN + SELECT DISTINCT publication.operation_id + FROM account_draft_authorization_changed_scopes changed + JOIN account_publication_authorization_sources publication USING (source_key) + WHERE changed.change_id = OLD.change_id + ORDER BY publication.operation_id LOOP + SELECT ordering INTO publication_ordering + FROM account_publication_authorization_fences + WHERE operation_id = publication_id FOR UPDATE; + SELECT count(*), count(DISTINCT outcome), + count(DISTINCT encode(operation_bytes, 'hex')), + count(DISTINCT encode(terminal_bytes, 'hex')) + INTO result_count, outcome_count, operation_count, terminal_count + FROM account_publication_authorization_owner_results + WHERE operation_id = publication_id; + IF publication_ordering = 'RESERVED' OR result_count <> 2 + OR outcome_count <> 1 OR operation_count <> 1 OR terminal_count <> 1 + OR (publication_ordering = 'REVOKE_ORDER' AND EXISTS ( + SELECT 1 FROM account_publication_authorization_owner_results + WHERE operation_id = publication_id AND outcome <> 'NO_PUBLICATION')) THEN + RAISE EXCEPTION 'Publication-specific matching owner terminal evidence is required' + USING ERRCODE = '23514'; + END IF; + END LOOP; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_publication_authorization_owner_result_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_publication_authorization_owner_results + FOR EACH ROW EXECUTE FUNCTION account_publication_authorization_owner_result_guard(); +CREATE TRIGGER account_publication_authorization_owner_results_no_truncate + BEFORE TRUNCATE ON account_publication_authorization_owner_results + FOR EACH STATEMENT EXECUTE FUNCTION account_publication_authorization_owner_no_truncate(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authorpublication/AccountPublicationTerminalFixtures.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authorpublication/AccountPublicationTerminalFixtures.java new file mode 100644 index 0000000000..c21a332024 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authorpublication/AccountPublicationTerminalFixtures.java @@ -0,0 +1,450 @@ +package integration.net.firedevops.firemud.accountservice.authorpublication; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.OffsetDateTime; +import java.util.Base64; +import java.util.HexFormat; +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.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +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.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence.OwnedAffectedTuple; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence.Request; +import tools.jackson.databind.ObjectMapper; + +/** + * Fixed isolated complete DTO fixtures copied from the common publication carrier tests. + * Account/World inputs are stipulated; these fixtures exercise Account's decoders and persistence, + * not either upstream service's durable state or authenticated transport. + */ +final class AccountPublicationTerminalFixtures { + 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 REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID ROOM_ID = uuid("77777777-7777-4777-8777-777777777777"); + private static final UUID REGION_ID = uuid("88888888-8888-4888-8888-888888888888"); + private static final UUID ZONE_ID = uuid("99999999-9999-4999-8999-999999999999"); + 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(); + + private AccountPublicationTerminalFixtures() {} + + static Scenario scenario() throws Exception { + DraftCommitBinding draft = freshGraphBinding(); + byte[] draftFenceBytes = draftFence(draft).canonicalBytes(); + byte[] appliedResult = appliedResult(draft, draftFenceBytes); + var appliedJson = JSON.readTree(appliedResult); + byte[] receiptBytes = + Base64.getDecoder().decode(appliedJson.get("startLocationReceiptBase64").textValue()); + + String publishRequestId = "publication-request"; + String namespace = "test"; + var target = draft.target(); + var selected = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + publishRequestId, + "5", + "ISOLATED fixed notes", + draft.requestId(), + draft.commitId(), + draft.digest()), + target, + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + draft.requestId(), + draft.commitId(), + draft.digest(), + "[]", + OffsetDateTime.parse("2026-10-07T00:00:00Z"))); + var input = + new AccountPublicationAuthorizationBinding.PreallocationInput( + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), selected); + var account = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + input, + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + input.actorAccountId().toString(), + "3", + "4", + null, + null, + new byte[] {7}))); + + var seedRequest = publishedSelectorRequest(draft, publishRequestId, selected.digest()); + var world = + new WorldPublishedStartLocationEvidence( + seedRequest, receiptBytes, draftFenceBytes, appliedResult); + var operation = new GameDesignPublicationOperationBinding(account, world); + var noPublicationTerminal = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION, + null, + null); + var publishedTerminal = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED, + releaseContent(operation), + 6L); + return new Scenario(account, operation, noPublicationTerminal, publishedTerminal); + } + + 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_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 DraftCommitBinding.TargetProof( + TENANT_ID, VERSION_ID, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + REQUEST_ID, + COMMIT_ID, + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + REGION_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + REGION_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + REGION_ID, + declaration)), + new DraftCommitBinding.RevisionPayload( + "1", + ZONE_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ZONE_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", ZONE_ID, null)), + new DraftCommitBinding.RevisionPayload( + "2", + ROOM_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ROOM_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", ROOM_ID, null))), + List.of( + affected("REGION", REGION_ID, "REGION_SUBTREE", REGION_ID), + affected("ZONE", ZONE_ID, "REGION_SUBTREE", REGION_ID), + affected("ROOM", ROOM_ID, "ZONE_SUBTREE", ZONE_ID)) + .stream() + .flatMap(List::stream) + .toList()); + } + + private static DraftAuthorizationFenceBinding draftFence(DraftCommitBinding draft) { + return new DraftAuthorizationFenceBinding( + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + draft.requestId(), + draft.commitId(), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + TENANT_ID, + VERSION_ID, + draft.baseCommitId(), + "0", + draft.canonicalBytes(), + draft.canonicalBytes(), + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd").toString(), + null, + "1", + null, + null, + new byte[] {4, 5}))); + } + + private static byte[] appliedResult(DraftCommitBinding draft, byte[] draftFenceBytes) + throws Exception { + var accountRequest = + new net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence.Request( + 1, "test", UUID.randomUUID(), draftFenceBytes); + var account = accountRequest.accountBinding(); + byte[] graph = graphBytes(accountRequest, draft); + String graphDigest = sha256(graph); + var receipt = + WorldDraftStartLocationEvidence.create( + "test", + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + sha256(draftFenceBytes), + draft.digest(), + new RoomTemplateRef(TENANT_ID, VERSION_ID, ROOM_ID), + graphDigest); + byte[] operation = appliedOperation(accountRequest, draft); + 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)); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(graph)); + result.put("graphDigest", graphDigest); + result.put( + "startLocationReceiptBase64", Base64.getEncoder().encodeToString(receipt.canonicalBytes())); + result.put("startLocationReceiptDigest", receipt.receiptDigest()); + 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 Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(result)); + } + + private static byte[] appliedOperation( + net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence.Request request, + DraftCommitBinding draft) + throws Exception { + var output = new ByteArrayOutputStream(); + var frames = new DataOutputStream(output); + frame(frames, "world-draft-terminal-operation/v1"); + var account = request.accountBinding(); + for (UUID id : + List.of( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId())) frame(frames, id.toString()); + frame(frames, 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))) frame(frames, value); + frame(frames, sha256(account.canonicalBytes())); + frame(frames, account.canonicalBytes()); + return output.toByteArray(); + } + + private static byte[] graphBytes( + net.firedevops.firemud.common.authoring.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 (var 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", "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + 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 GameDesignPublicationTerminalEvidence.ReleaseContent releaseContent( + GameDesignPublicationOperationBinding operation) { + var world = operation.world(); + String digest = "sha256:" + "a".repeat(64); + long versionRowId = operation.account().input().selection().target().gameDesignVersionRowId(); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new GameDesignPublicationTerminalEvidence.Participant( + owner, + Long.toString(versionRowId), + null, + world.request().appliedCommitId(), + owner.equals("WORLD_MANAGEMENT") + ? world.request().contentDigest() + : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + owner.equals("GAME_LOGIC") ? digest : null, + null, + null)) + .toList(); + return new GameDesignPublicationTerminalEvidence.ReleaseContent( + world.request().canonicalTenantId(), + world.request().canonicalVersionId(), + "ISOLATED-bundle", + 1, + "v2", + world.request().publishWorkflowId(), + digest, + 1, + List.of(), + List.of(), + participants, + List.of("LOOK"), + "generation-1", + world); + } + + private static Request publishedSelectorRequest( + DraftCommitBinding draft, String publishRequestId, String selectionDigest) { + var tuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + String workflow = + PublicationDigestRequestBinding.full(TENANT_ID.toString(), "42", publishRequestId) + .derivedWorkflowIdentity(); + return new Request( + "test", + TENANT_ID, + VERSION_ID, + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + publishRequestId, + selectionDigest.substring(7), + 5L, + workflow, + draft.commitId().toString(), + "b".repeat(64), + 3, + tuples); + } + + 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 DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_DESIGN_AGGREGATE_TYPE_" + family, + templateId.toString(), + "AGGREGATE", + templateId.toString(), + "0"), + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_DESIGN_AGGREGATE_TYPE_" + family, + templateId.toString(), + scopeType, + scopeId.toString(), + "0")); + } + + private static void frame(DataOutputStream output, String value) throws Exception { + frame(output, value.getBytes(StandardCharsets.UTF_8)); + } + + private static void frame(DataOutputStream output, byte[] value) throws Exception { + output.writeInt(value.length); + output.write(value); + } + + private static String sha256(byte[] value) throws Exception { + return "sha256:" + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + record Scenario( + AccountPublicationAuthorizationBinding account, + GameDesignPublicationOperationBinding operation, + GameDesignPublicationTerminalEvidence noPublicationTerminal, + GameDesignPublicationTerminalEvidence publishedTerminal) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authorpublication/AccountPublicationTerminalReconciliationServiceTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authorpublication/AccountPublicationTerminalReconciliationServiceTest.java new file mode 100644 index 0000000000..be928de95b --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authorpublication/AccountPublicationTerminalReconciliationServiceTest.java @@ -0,0 +1,250 @@ +package integration.net.firedevops.firemud.accountservice.authorpublication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.time.OffsetDateTime; +import java.util.EnumMap; +import java.util.Map; +import java.util.Optional; +import net.firedevops.firemud.accountservice.authorpublication.AccountPublicationTerminalReconciliationService; +import net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFenceRepository.Owner; +import net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFenceRepository.OwnerResultSnapshot; +import net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFenceRepository.Settlement; +import net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFenceRepository.TerminalSnapshot; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.world.WorldPublicationTerminalClient; +import net.firedevops.firemud.common.world.WorldPublicationTerminalReadEvidence; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Synthetic concrete-client transport doubles test transaction placement, never actual mTLS proof. + */ +class AccountPublicationTerminalReconciliationServiceTest { + private static final String NAMESPACE = "test"; + + @Test + void concreteOwnerClientsRunOutsideReadCommittedAccountTransactionsAndExactPairIsRetained() + throws Exception { + var fixture = AccountPublicationTerminalFixtures.scenario(); + var repository = mock(PublicationAuthorizationFenceRepository.class); + var gameDesignClient = mock(GameDesignPublicationTerminalClient.class); + var worldClient = mock(WorldPublicationTerminalClient.class); + var manager = new TestTransactionManager(); + var stored = new EnumMap(Owner.class); + when(repository.readOriginalOperation(any(GameDesignPublicationOperationBinding.class))) + .thenAnswer( + invocation -> { + assertInsideOwnerTransaction(); + var candidate = (GameDesignPublicationOperationBinding) invocation.getArgument(0); + assertThat(candidate.canonicalBytes()) + .containsExactly(fixture.operation().canonicalBytes()); + return Optional.of(snapshot(stored)); + }); + when(repository.readSettlement(any(GameDesignPublicationOperationBinding.class))) + .thenAnswer( + invocation -> { + assertInsideOwnerTransaction(); + var gameDesign = stored.get(Owner.GAME_DESIGN); + var world = stored.get(Owner.WORLD); + return gameDesign != null + && world != null + && java.util.Arrays.equals(gameDesign.terminalBytes(), world.terminalBytes()) + ? Settlement.NO_PUBLICATION + : Settlement.PENDING; + }); + when(repository.recordOwnerResult( + any(GameDesignPublicationOperationBinding.class), any(), any())) + .thenAnswer( + invocation -> { + assertInsideOwnerTransaction(); + Owner owner = invocation.getArgument(1); + GameDesignPublicationTerminalEvidence terminal = invocation.getArgument(2); + var result = + new OwnerResultSnapshot( + terminal.outcome(), + terminal.operationBytes(), + terminal.canonicalBytes(), + OffsetDateTime.parse("2026-10-07T00:00:00Z")); + OwnerResultSnapshot prior = stored.putIfAbsent(owner, result); + return prior == null ? result : prior; + }); + when(gameDesignClient.read(any())) + .thenAnswer( + invocation -> { + assertOutsideOwnerTransaction(manager); + var request = + (GameDesignPublicationTerminalReadEvidence.ReadRequest) invocation.getArgument(0); + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.operationBytes()) + .containsExactly(fixture.operation().canonicalBytes()); + return new GameDesignPublicationTerminalReadEvidence.ReadResult( + request, + GameDesignPublicationTerminalReadEvidence.Status.NO_PUBLICATION, + Optional.of(fixture.noPublicationTerminal())); + }); + when(worldClient.read(any())) + .thenAnswer( + invocation -> { + assertOutsideOwnerTransaction(manager); + var request = + (WorldPublicationTerminalReadEvidence.Request) invocation.getArgument(0); + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.expectedTerminalEvidenceBytes()) + .containsExactly(fixture.noPublicationTerminal().canonicalBytes()); + return new WorldPublicationTerminalReadEvidence.ReadResult( + request, + WorldPublicationTerminalReadEvidence.Status.ABORTED, + Optional.of(fixture.noPublicationTerminal())); + }); + + var service = + new AccountPublicationTerminalReconciliationService( + repository, manager, gameDesignClient, worldClient, NAMESPACE); + assertThat(service.reconcile(fixture.operation().canonicalBytes())) + .contains(Settlement.NO_PUBLICATION); + assertThat(stored).containsKeys(Owner.GAME_DESIGN, Owner.WORLD); + assertThat(stored.get(Owner.GAME_DESIGN).terminalBytes()) + .containsExactly(fixture.noPublicationTerminal().canonicalBytes()); + assertThat(stored.get(Owner.WORLD).terminalBytes()) + .containsExactly(fixture.noPublicationTerminal().canonicalBytes()); + assertThat(manager.commits).isEqualTo(2); + verify(gameDesignClient).read(any()); + verify(worldClient).read(any()); + verify(repository) + .recordOwnerResult(any(), org.mockito.ArgumentMatchers.eq(Owner.GAME_DESIGN), any()); + verify(repository) + .recordOwnerResult(any(), org.mockito.ArgumentMatchers.eq(Owner.WORLD), any()); + } + + @Test + void gameDesignUnknownNeverFabricatesWorldRequestOrOwnerResult() throws Exception { + var fixture = AccountPublicationTerminalFixtures.scenario(); + var repository = mock(PublicationAuthorizationFenceRepository.class); + var gameDesignClient = mock(GameDesignPublicationTerminalClient.class); + var worldClient = mock(WorldPublicationTerminalClient.class); + var manager = new TestTransactionManager(); + when(repository.readOriginalOperation(any(GameDesignPublicationOperationBinding.class))) + .thenAnswer( + invocation -> { + assertInsideOwnerTransaction(); + return Optional.of( + new TerminalSnapshot( + PublicationAuthorizationFenceRepository.Ordering.PUBLICATION_ORDER, + Settlement.PENDING, + Optional.empty(), + Optional.empty())); + }); + when(repository.readSettlement(any(GameDesignPublicationOperationBinding.class))) + .thenReturn(Settlement.PENDING); + when(gameDesignClient.read(any())) + .thenAnswer( + invocation -> { + assertOutsideOwnerTransaction(manager); + var request = + (GameDesignPublicationTerminalReadEvidence.ReadRequest) invocation.getArgument(0); + return new GameDesignPublicationTerminalReadEvidence.ReadResult( + request, + GameDesignPublicationTerminalReadEvidence.Status.UNKNOWN, + Optional.empty()); + }); + var service = + new AccountPublicationTerminalReconciliationService( + repository, manager, gameDesignClient, worldClient, NAMESPACE); + + assertThat(service.reconcile(fixture.operation().canonicalBytes())) + .contains(Settlement.PENDING); + verify(gameDesignClient).read(any()); + verifyNoInteractions(worldClient); + verify(repository, never()).recordOwnerResult(any(), any(), any()); + assertThat(manager.commits).isEqualTo(2); + } + + @Test + void ambientOwnerTransactionRejectsRecoveryBeforeRepositoryOrClientUse() throws Exception { + var fixture = AccountPublicationTerminalFixtures.scenario(); + var repository = mock(PublicationAuthorizationFenceRepository.class); + var gameDesignClient = mock(GameDesignPublicationTerminalClient.class); + var worldClient = mock(WorldPublicationTerminalClient.class); + var manager = new TestTransactionManager(); + var service = + new AccountPublicationTerminalReconciliationService( + repository, manager, gameDesignClient, worldClient, NAMESPACE); + var ambient = new TransactionTemplate(manager); + ambient.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ambient.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ambient.execute( + status -> { + assertThatThrownBy(() -> service.reconcile(fixture.operation().canonicalBytes())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + verifyNoInteractions(repository, gameDesignClient, worldClient); + return null; + }); + } + + private static TerminalSnapshot snapshot(Map stored) { + return new TerminalSnapshot( + PublicationAuthorizationFenceRepository.Ordering.PUBLICATION_ORDER, + Settlement.PENDING, + Optional.ofNullable(stored.get(Owner.GAME_DESIGN)), + Optional.ofNullable(stored.get(Owner.WORLD))); + } + + private static void assertInsideOwnerTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + } + + private static void assertOutsideOwnerTransaction(TestTransactionManager manager) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(manager.commits).isGreaterThanOrEqualTo(1); + } + + private static final class TestTransactionManager extends AbstractPlatformTransactionManager { + private int commits; + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected boolean isExistingTransaction(Object transaction) { + return false; + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) { + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.isReadOnly()).isFalse(); + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + commits++; + } + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} 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 index 0f904bf888..bf143232c5 100644 --- 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 @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.io.ByteArrayOutputStream; import java.time.OffsetDateTime; import java.util.List; import java.util.Map; @@ -16,12 +17,16 @@ 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.accountservice.authorpublication.PublicationAuthorizationFenceRepository.Owner; +import net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFenceRepository.Settlement; 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.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -40,7 +45,8 @@ /** * 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. + * publication. Structural terminal rows in the focused SQL tests below are deliberately synthetic: + * they test PostgreSQL integrity/ordering guards only and are not transport or owner proof. */ @Testcontainers(disabledWithoutDocker = true) class PublicationAuthorizationFencePostgresIntegrationTest { @@ -247,7 +253,8 @@ void waitingChangeDeniesNewReservationAndUnrelatedScopeStillProceeds() { @Test void concurrentPublicationClaimAndSourceChangeChooseOneDurableOrder() throws Exception { Context context = context(); - var binding = binding(); + var fixture = AccountPublicationTerminalFixtures.scenario(); + var binding = fixture.account(); tx(context, () -> context.publication().reserve(binding)); var change = change(binding); CountDownLatch ready = new CountDownLatch(2); @@ -281,9 +288,486 @@ void concurrentPublicationClaimAndSourceChangeChooseOneDurableOrder() throws Exc assertThat(tx(context, () -> context.draft().readSourceChange(change)).status()) .isEqualTo("WAITING"); assertThat(tx(context, () -> context.draft().sourceMutationPermitted(change))).isFalse(); + tx( + context, + () -> { + context + .publication() + .recordOwnerResult( + fixture.operation(), Owner.GAME_DESIGN, fixture.noPublicationTerminal()); + context + .publication() + .recordOwnerResult( + fixture.operation(), Owner.WORLD, fixture.noPublicationTerminal()); + return null; + }); + if (winner == Ordering.PUBLICATION_ORDER) { + assertThat(tx(context, () -> context.draft().sourceMutationPermitted(change))).isTrue(); + txRun(context, () -> context.draft().markSourceCommitted(change)); + } else { + assertThat(tx(context, () -> context.draft().sourceAbortPermitted(change))).isTrue(); + tx( + context, + () -> { + context.draft().markSourceAborted(change, SourceChangeAbortReason.DEFINITIVE_ABORT); + return null; + }); + } + assertThat(tx(context, () -> context.draft().readSourceChange(change)).status()) + .isEqualTo(winner == Ordering.PUBLICATION_ORDER ? "SOURCE_COMMITTED" : "SOURCE_ABORTED"); } } + @Test + void exactIdenticalOwnerReadbacksSettleOnlyAfterBothOwnersAndPreserveRetryIdentity() + throws Exception { + Context context = context(); + var fixture = AccountPublicationTerminalFixtures.scenario(); + tx(context, () -> context.publication().reserve(fixture.account())); + tx(context, () -> context.publication().claimPublicationOrder(fixture.account())); + var initial = + tx( + context, + () -> context.publication().readOriginalOperation(fixture.operation()).orElseThrow()); + assertThat(initial.ordering()).isEqualTo(Ordering.PUBLICATION_ORDER); + assertThat(initial.settlement()).isEqualTo(Settlement.PENDING); + assertThat(initial.gameDesignResult()).isEmpty(); + assertThat(initial.worldResult()).isEmpty(); + var change = change(fixture.account()); + assertThat(tx(context, () -> context.draft().requestSourceChange(change))).isFalse(); + + var design = + tx( + context, + () -> + context + .publication() + .recordOwnerResult( + fixture.operation(), Owner.GAME_DESIGN, fixture.noPublicationTerminal())); + assertThat( + tx( + context, + () -> + context + .publication() + .recordOwnerResult( + fixture.operation(), + Owner.GAME_DESIGN, + fixture.noPublicationTerminal()))) + .satisfies( + retry -> { + assertThat(retry.outcome()).isEqualTo(design.outcome()); + assertThat(retry.operationBytes()).containsExactly(design.operationBytes()); + assertThat(retry.terminalBytes()).containsExactly(design.terminalBytes()); + assertThat(retry.recordedAt()).isEqualTo(design.recordedAt()); + }); + assertThat(tx(context, () -> context.publication().readSettlement(fixture.operation()))) + .isEqualTo(Settlement.PENDING); + var incomplete = + tx( + context, + () -> context.publication().readOriginalOperation(fixture.operation()).orElseThrow()); + assertThat(incomplete.settlement()).isEqualTo(Settlement.PENDING); + assertThat(incomplete.gameDesignResult()).isPresent(); + assertThat(incomplete.worldResult()).isEmpty(); + assertThat(tx(context, () -> context.draft().sourceMutationPermitted(change))).isFalse(); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .publication() + .recordOwnerResult( + fixture.operation(), + Owner.GAME_DESIGN, + fixture.publishedTerminal()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Changed or contradictory"); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .publication() + .recordOwnerResult( + fixture.operation(), Owner.WORLD, fixture.publishedTerminal()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Changed or contradictory"); + assertThat(tx(context, () -> context.publication().readSettlement(fixture.operation()))) + .isEqualTo(Settlement.PENDING); + + tx( + context, + () -> + context + .publication() + .recordOwnerResult( + fixture.operation(), Owner.WORLD, fixture.noPublicationTerminal())); + assertThat(tx(context, () -> context.publication().readSettlement(fixture.operation()))) + .isEqualTo(Settlement.NO_PUBLICATION); + var settled = + tx( + context, + () -> context.publication().readOriginalOperation(fixture.operation()).orElseThrow()); + assertThat(settled.settlement()).isEqualTo(Settlement.NO_PUBLICATION); + assertThat(settled.gameDesignResult()).isPresent(); + assertThat(settled.worldResult()).isPresent(); + assertThat(tx(context, () -> context.draft().sourceMutationPermitted(change))).isTrue(); + txRun(context, () -> context.draft().markSourceCommitted(change)); + assertThat(tx(context, () -> context.draft().readSourceChange(change)).status()) + .isEqualTo("SOURCE_COMMITTED"); + } + + @Test + void publishedOwnerPairSettlesPublicationOrderAndAllowsSourceTransition() throws Exception { + Context context = context(); + var fixture = AccountPublicationTerminalFixtures.scenario(); + tx(context, () -> context.publication().reserve(fixture.account())); + tx(context, () -> context.publication().claimPublicationOrder(fixture.account())); + var change = change(fixture.account()); + assertThat(tx(context, () -> context.draft().requestSourceChange(change))).isFalse(); + tx( + context, + () -> { + context + .publication() + .recordOwnerResult( + fixture.operation(), Owner.GAME_DESIGN, fixture.publishedTerminal()); + return null; + }); + assertThat(tx(context, () -> context.draft().sourceMutationPermitted(change))).isFalse(); + tx( + context, + () -> + context + .publication() + .recordOwnerResult(fixture.operation(), Owner.WORLD, fixture.publishedTerminal())); + assertThat(tx(context, () -> context.publication().readSettlement(fixture.operation()))) + .isEqualTo(Settlement.PUBLISHED); + assertThat(tx(context, () -> context.draft().sourceMutationPermitted(change))).isTrue(); + txRun(context, () -> context.draft().markSourceCommitted(change)); + assertThat(tx(context, () -> context.draft().readSourceChange(change).status())) + .isEqualTo("SOURCE_COMMITTED"); + } + + @Test + void revokeOrderRequiresExactNoPublicationPairBeforeDefinitiveSourceAbort() throws Exception { + Context context = context(); + var fixture = AccountPublicationTerminalFixtures.scenario(); + tx(context, () -> context.publication().reserve(fixture.account())); + var change = change(fixture.account()); + assertThat(tx(context, () -> context.draft().requestSourceChange(change))).isFalse(); + assertThat(tx(context, () -> context.publication().read(fixture.account()).ordering())) + .isEqualTo(Ordering.REVOKE_ORDER); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .publication() + .recordOwnerResult( + fixture.operation(), + Owner.GAME_DESIGN, + fixture.publishedTerminal()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Revocation order"); + assertThat(tx(context, () -> context.draft().sourceAbortPermitted(change))).isFalse(); + tx( + context, + () -> + context + .publication() + .recordOwnerResult( + fixture.operation(), Owner.GAME_DESIGN, fixture.noPublicationTerminal())); + assertThat(tx(context, () -> context.draft().sourceAbortPermitted(change))).isFalse(); + tx( + context, + () -> + context + .publication() + .recordOwnerResult( + fixture.operation(), Owner.WORLD, fixture.noPublicationTerminal())); + assertThat(tx(context, () -> context.publication().readSettlement(fixture.operation()))) + .isEqualTo(Settlement.NO_PUBLICATION); + assertThat(tx(context, () -> context.draft().sourceAbortPermitted(change))).isTrue(); + tx( + context, + () -> { + context.draft().markSourceAborted(change, SourceChangeAbortReason.DEFINITIVE_ABORT); + return null; + }); + assertThat(tx(context, () -> context.draft().readSourceChange(change).status())) + .isEqualTo("SOURCE_ABORTED"); + } + + @Test + void lateRuntimeRollbackRetainsValidOwnerPairAndWaitingSourceIntent() throws Exception { + Context context = context(); + var fixture = AccountPublicationTerminalFixtures.scenario(); + tx(context, () -> context.publication().reserve(fixture.account())); + tx(context, () -> context.publication().claimPublicationOrder(fixture.account())); + var change = change(fixture.account()); + assertThat(tx(context, () -> context.draft().requestSourceChange(change))).isFalse(); + tx( + context, + () -> { + context + .publication() + .recordOwnerResult( + fixture.operation(), Owner.GAME_DESIGN, fixture.noPublicationTerminal()); + context + .publication() + .recordOwnerResult(fixture.operation(), Owner.WORLD, fixture.noPublicationTerminal()); + return null; + }); + assertThatThrownBy( + () -> + tx( + context, + () -> { + context.draft().markSourceCommitted(change); + throw new IllegalStateException("fixture rollback after owner settlement"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("fixture rollback"); + assertThat(tx(context, () -> context.draft().readSourceChange(change).status())) + .isEqualTo("WAITING"); + assertThat(tx(context, () -> context.publication().readSettlement(fixture.operation()))) + .isEqualTo(Settlement.NO_PUBLICATION); + assertThat(tx(context, () -> context.draft().sourceMutationPermitted(change))).isTrue(); + txRun(context, () -> context.draft().markSourceCommitted(change)); + assertThat(tx(context, () -> context.draft().readSourceChange(change).status())) + .isEqualTo("SOURCE_COMMITTED"); + } + + @Test + void directSqlSourceTransitionNeedsTwoMatchingPublicationOwnerRowsAndImmutableRetries() { + Context context = context(); + var binding = binding(); + tx(context, () -> context.publication().reserve(binding)); + tx(context, () -> context.publication().claimPublicationOrder(binding)); + var change = change(binding); + assertThat(tx(context, () -> context.draft().requestSourceChange(change))).isFalse(); + assertThat(tx(context, () -> context.draft().sourceMutationPermitted(change))).isFalse(); + + assertThatThrownBy( + () -> txRun(context, () -> transitionSourceSql(context, change, "SOURCE_COMMITTED"))) + .isInstanceOf(DataAccessException.class); + assertThat(tx(context, () -> context.draft().readSourceChange(change)).status()) + .isEqualTo("WAITING"); + + byte[] operationBytes = structuralOperationBytes(binding); + byte[] noPublication = structuralTerminalBytes(operationBytes, "NO_PUBLICATION"); + assertThatThrownBy( + () -> + txRun( + context, + () -> + insertStructuralOwnerResult( + context, + binding, + "GAME_DESIGN", + "PUBLISHED", + operationBytes, + structuralTerminalBytes( + operationBytes, "PUBLISHED", "9223372036854775808")))) + .isInstanceOf(DataAccessException.class); + txRun( + context, + () -> + insertStructuralOwnerResult( + context, binding, "GAME_DESIGN", "NO_PUBLICATION", operationBytes, noPublication)); + assertThatThrownBy( + () -> + txRun( + context, + () -> + insertStructuralOwnerResult( + context, + binding, + "WORLD", + "PUBLISHED", + operationBytes, + structuralTerminalBytes(operationBytes, "PUBLISHED")))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + txRun( + context, + () -> + insertStructuralOwnerResult( + context, + binding, + "GAME_DESIGN", + "NO_PUBLICATION", + operationBytes, + noPublication))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_publication_authorization_owner_results" + + " SET terminal_bytes=decode('01','hex') WHERE operation_id=? AND owner='GAME_DESIGN'", + binding.operationId()))) + .isInstanceOf(DataAccessException.class); + + txRun( + context, + () -> + insertStructuralOwnerResult( + context, binding, "WORLD", "NO_PUBLICATION", operationBytes, noPublication)); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "DELETE FROM account_publication_authorization_owner_results WHERE operation_id=?", + binding.operationId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute("TRUNCATE account_publication_authorization_owner_results"))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> tx(context, () -> context.draft().sourceMutationPermitted(change))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Published World selector evidence"); + assertThat(tx(context, () -> context.draft().readSourceChange(change)).status()) + .isEqualTo("WAITING"); + + // The database trigger proves structural pair consistency only. It does not authenticate the + // stipulated owner rows; this direct SQL transition is not Account runtime proof. + txRun(context, () -> transitionSourceSql(context, change, "SOURCE_COMMITTED")); + assertThat(tx(context, () -> context.draft().readSourceChange(change)).status()) + .isEqualTo("SOURCE_COMMITTED"); + } + + @Test + void revokeOrderAcceptsOnlyTwoMatchingNoPublicationRowsForDefinitiveAbort() { + 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); + + byte[] operationBytes = structuralOperationBytes(binding); + assertThatThrownBy( + () -> + txRun( + context, + () -> + insertStructuralOwnerResult( + context, + binding, + "GAME_DESIGN", + "PUBLISHED", + operationBytes, + structuralTerminalBytes(operationBytes, "PUBLISHED")))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> txRun(context, () -> transitionSourceSql(context, change, "SOURCE_ABORTED"))) + .isInstanceOf(DataAccessException.class); + + byte[] noPublication = structuralTerminalBytes(operationBytes, "NO_PUBLICATION"); + txRun( + context, + () -> + insertStructuralOwnerResult( + context, binding, "GAME_DESIGN", "NO_PUBLICATION", operationBytes, noPublication)); + txRun( + context, + () -> + insertStructuralOwnerResult( + context, binding, "WORLD", "NO_PUBLICATION", operationBytes, noPublication)); + assertThatThrownBy( + () -> + txRun( + context, + () -> + insertStructuralOwnerResult( + context, + binding, + "WORLD", + "PUBLISHED", + operationBytes, + structuralTerminalBytes(operationBytes, "PUBLISHED")))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> tx(context, () -> context.draft().sourceAbortPermitted(change))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Published World selector evidence"); + assertThat(tx(context, () -> context.draft().readSourceChange(change)).status()) + .isEqualTo("WAITING"); + // As above, this directly tests SQL structural guarding, not an authenticated World ABORTED + // read. + txRun(context, () -> transitionSourceSql(context, change, "SOURCE_ABORTED")); + assertThat(tx(context, () -> context.draft().readSourceChange(change)).status()) + .isEqualTo("SOURCE_ABORTED"); + } + + @Test + void lateSourceTransitionRollbackRetainsWaitingChangeAndOwnerRows() { + Context context = context(); + var binding = binding(); + tx(context, () -> context.publication().reserve(binding)); + tx(context, () -> context.publication().claimPublicationOrder(binding)); + var change = change(binding); + assertThat(tx(context, () -> context.draft().requestSourceChange(change))).isFalse(); + byte[] operationBytes = structuralOperationBytes(binding); + byte[] terminalBytes = structuralTerminalBytes(operationBytes, "NO_PUBLICATION"); + txRun( + context, + () -> + insertStructuralOwnerResult( + context, binding, "GAME_DESIGN", "NO_PUBLICATION", operationBytes, terminalBytes)); + txRun( + context, + () -> + insertStructuralOwnerResult( + context, binding, "WORLD", "NO_PUBLICATION", operationBytes, terminalBytes)); + + assertThatThrownBy( + () -> + txRun( + context, + () -> { + transitionSourceSql(context, change, "SOURCE_COMMITTED"); + throw new IllegalStateException( + "fixture rollback after guarded source transition"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("fixture rollback"); + assertThat(tx(context, () -> context.draft().readSourceChange(change)).status()) + .isEqualTo("WAITING"); + var retainedOwnerCount = + java.util.Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT count(*) FROM account_publication_authorization_owner_results WHERE operation_id=?", + binding.operationId())); + assertThat(retainedOwnerCount.get(0, Long.class)).isEqualTo(2L); + txRun(context, () -> transitionSourceSql(context, change, "SOURCE_COMMITTED")); + assertThat(tx(context, () -> context.draft().readSourceChange(change)).status()) + .isEqualTo("SOURCE_COMMITTED"); + } + @Test void rawSqlCannotReplaceOriginalSourceBindingOrOrderOrTruncateEvidence() { Context context = context(); @@ -502,6 +986,34 @@ void missingCurrentSchemaFailsClosedAndUpgradePreservesOriginalDraftEvidence() { .isZero(); } + @Test + void v79PublicationOrderAndWaitingSourceChangeSurviveV80WithoutInventedOwnerResults() { + Context context = context("79"); + var binding = binding(); + tx(context, () -> context.publication().reserve(binding)); + tx(context, () -> context.publication().claimPublicationOrder(binding)); + var change = change(binding); + assertThat(tx(context, () -> context.draft().requestSourceChange(change))).isFalse(); + var before = tx(context, () -> context.publication().read(binding)); + assertThat(before.ordering()).isEqualTo(Ordering.PUBLICATION_ORDER); + assertThat(tx(context, () -> context.draft().readSourceChange(change)).status()) + .isEqualTo("WAITING"); + + migrate(context.source(), "latest"); + + var after = tx(context, () -> context.publication().read(binding)); + 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(tx(context, () -> context.draft().readSourceChange(change)).status()) + .isEqualTo("WAITING"); + assertThat( + context.dsl().fetchCount(DSL.table("account_publication_authorization_owner_results"))) + .isZero(); + assertThat(tx(context, () -> context.draft().sourceMutationPermitted(change))).isFalse(); + } + private static AccountPublicationAuthorizationBinding binding() { var input = new AccountPublicationAuthorizationBinding.PreallocationInput( @@ -525,6 +1037,75 @@ private static SourceChange change(AccountPublicationAuthorizationBinding bindin return new SourceChange(UUID.randomUUID(), binding.sources(), new byte[] {9}); } + private static byte[] structuralOperationBytes(AccountPublicationAuthorizationBinding binding) { + var output = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(output, GameDesignPublicationOperationBinding.SCHEMA); + DraftAuthorizationFenceBinding.frame(output, binding.canonicalBytes()); + // Deliberately stipulated nonempty checkpoint bytes: valid only for SQL structural tests. + DraftAuthorizationFenceBinding.frame(output, new byte[] {1}); + return output.toByteArray(); + } + + private static byte[] structuralTerminalBytes(byte[] operationBytes, String outcome) { + return structuralTerminalBytes(operationBytes, outcome, "2"); + } + + private static byte[] structuralTerminalBytes( + byte[] operationBytes, String outcome, String epoch) { + var output = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(output, GameDesignPublicationTerminalEvidence.SCHEMA); + DraftAuthorizationFenceBinding.frame(output, operationBytes); + DraftAuthorizationFenceBinding.frame(output, outcome); + if ("PUBLISHED".equals(outcome)) { + // Nonempty structural placeholders exercise SQL frame shape only, never release proof. + DraftAuthorizationFenceBinding.frame(output, new byte[] {2}); + DraftAuthorizationFenceBinding.frame(output, epoch); + } + return output.toByteArray(); + } + + private static void insertStructuralOwnerResult( + Context context, + AccountPublicationAuthorizationBinding binding, + String owner, + String outcome, + byte[] operationBytes, + byte[] terminalBytes) { + context + .dsl() + .execute( + "INSERT INTO account_publication_authorization_owner_results" + + " (operation_id, owner, outcome, operation_bytes, terminal_bytes) VALUES (?, ?, ?, ?, ?)", + binding.operationId(), + owner, + outcome, + operationBytes, + terminalBytes); + } + + private static void transitionSourceSql(Context context, SourceChange change, String status) { + if ("SOURCE_COMMITTED".equals(status)) { + context + .dsl() + .execute( + "UPDATE account_draft_authorization_source_changes" + + " SET status='SOURCE_COMMITTED', committed_at=CURRENT_TIMESTAMP WHERE change_id=?", + change.changeId()); + return; + } + if ("SOURCE_ABORTED".equals(status)) { + context + .dsl() + .execute( + "UPDATE account_draft_authorization_source_changes" + + " SET status='SOURCE_ABORTED', aborted_at=CURRENT_TIMESTAMP," + + " abort_reason='DEFINITIVE_ABORT' WHERE change_id=?", + change.changeId()); + return; + } + throw new IllegalArgumentException("Unsupported source transition status"); + } + private Context context() { return context("latest"); } @@ -564,6 +1145,15 @@ private static T tx(Context context, Supplier work) { return context.transaction().execute(status -> work.get()); } + private static void txRun(Context context, Runnable work) { + tx( + context, + () -> { + work.run(); + return null; + }); + } + private static void await(CountDownLatch latch) { try { if (!latch.await(10, TimeUnit.SECONDS)) throw new IllegalStateException("fixture timeout"); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authorpublication/PublicationTerminalRepositoryEntryPointTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authorpublication/PublicationTerminalRepositoryEntryPointTest.java new file mode 100644 index 0000000000..53b4c610a0 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authorpublication/PublicationTerminalRepositoryEntryPointTest.java @@ -0,0 +1,27 @@ +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 net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFenceRepository; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; + +class PublicationTerminalRepositoryEntryPointTest { + @Test + void terminalStorageRequiresWritableOwnerTransactionBeforeReadingEvidenceOrPersistence() { + DSLContext dsl = mock(DSLContext.class); + var repository = new PublicationAuthorizationFenceRepository(dsl); + + assertThatThrownBy(() -> repository.readOriginalOperation(null)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> repository.recordOwnerResult(null, null, null)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> repository.readOwnerResult(null, null)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> repository.readSettlement(null)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(dsl); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublicationTerminalClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublicationTerminalClient.java new file mode 100644 index 0000000000..3028905635 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublicationTerminalClient.java @@ -0,0 +1,154 @@ +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.WorldPublicationTerminalReadServiceGrpc; + +/** Explicit mTLS client for the exact World publication terminal read. */ +public final class WorldPublicationTerminalClient + extends AbstractReloadingBlockingGrpcClient< + WorldPublicationTerminalReadServiceGrpc.WorldPublicationTerminalReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldPublicationTerminalClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + WorldPublicationTerminalClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when the owning Account service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("World publication terminal client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("World publication terminal client has no gRPC stub"); + } + initialized = true; + } + + /** + * Reads and validates World-owned publication terminal evidence for this exact canonical request. + */ + public WorldPublicationTerminalReadEvidence.ReadResult read( + WorldPublicationTerminalReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "World publication terminal request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readWorldPublicationTerminal(WorldPublicationTerminalReadGrpcCodec.toRequest(request)); + try { + return WorldPublicationTerminalReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid publication terminal read evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldPublicationTerminalReadServiceGrpc.WorldPublicationTerminalReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldPublicationTerminalReadServiceGrpc.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 WorldPublicationTerminalReadServiceGrpc.WorldPublicationTerminalReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "World publication terminal client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("World publication terminal 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 publication terminal read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World publication terminal read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "World publication terminal read " + label + " must be a readable file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World publication terminal read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublicationTerminalCompletionClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublicationTerminalCompletionClient.java new file mode 100644 index 0000000000..96bce891aa --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublicationTerminalCompletionClient.java @@ -0,0 +1,159 @@ +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.WorldPublicationTerminalCompletionServiceGrpc; + +/** Explicit mTLS client for exact authenticated World publication terminal completion. */ +public final class WorldPublicationTerminalCompletionClient + extends AbstractReloadingBlockingGrpcClient< + WorldPublicationTerminalCompletionServiceGrpc + .WorldPublicationTerminalCompletionServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldPublicationTerminalCompletionClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + WorldPublicationTerminalCompletionClient.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 composition explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("World publication terminal completion client is closed"); + } + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException( + "World publication terminal completion client has no gRPC stub"); + } + initialized = true; + } + + /** + * Sends the complete original operation and immutable terminal evidence, then verifies exact + * echo. + */ + public WorldPublicationTerminalCompletionGrpcCodec.Response complete( + WorldPublicationTerminalCompletionGrpcCodec.Request request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "World terminal completion must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .completeWorldPublicationTerminal( + WorldPublicationTerminalCompletionGrpcCodec.toRequest(request)); + try { + return WorldPublicationTerminalCompletionGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid publication terminal completion evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldPublicationTerminalCompletionServiceGrpc + .WorldPublicationTerminalCompletionServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldPublicationTerminalCompletionServiceGrpc.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 WorldPublicationTerminalCompletionServiceGrpc + .WorldPublicationTerminalCompletionServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "World publication terminal completion client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "World publication terminal completion 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 publication terminal completion requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World publication terminal completion requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "World publication terminal completion " + label + " must be a readable file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World publication terminal completion " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublicationTerminalCompletionGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublicationTerminalCompletionGrpcCodec.java new file mode 100644 index 0000000000..2296f665d0 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublicationTerminalCompletionGrpcCodec.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.common.world; + +import com.google.protobuf.ByteString; +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.worldmanagement.v1.CompleteWorldPublicationTerminalRequest; +import net.firedevops.firemud.worldmanagement.v1.CompleteWorldPublicationTerminalResponse; + +/** Closed canonical carrier codec for World publication terminal completion. */ +public final class WorldPublicationTerminalCompletionGrpcCodec { + private WorldPublicationTerminalCompletionGrpcCodec() {} + + /** Original publication operation and exact Game Design terminal selection. */ + public record Request( + int schemaVersion, + String targetNamespace, + byte[] operationBytes, + byte[] terminalEvidenceBytes) { + public static final int SCHEMA_VERSION = 1; + public static final String SCHEMA = "world-publication-terminal-completion-request/v1"; + + public Request { + if (schemaVersion != SCHEMA_VERSION || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException( + "Closed schema-1 World terminal completion request required"); + } + operationBytes = + GameDesignPublicationOperationBinding.fromStored(operationBytes).canonicalBytes(); + var operation = GameDesignPublicationOperationBinding.fromStored(operationBytes); + var terminal = GameDesignPublicationTerminalEvidence.fromStored(terminalEvidenceBytes); + if (!targetNamespace.equals(operation.world().request().targetNamespace()) + || !Arrays.equals(operationBytes, terminal.operationBytes())) { + throw new IllegalArgumentException( + "World terminal completion differs from its exact original operation or namespace"); + } + terminalEvidenceBytes = terminal.canonicalBytes(); + } + + @Override + public byte[] operationBytes() { + return operationBytes.clone(); + } + + @Override + public byte[] terminalEvidenceBytes() { + return terminalEvidenceBytes.clone(); + } + + public GameDesignPublicationTerminalEvidence terminalEvidence() { + return GameDesignPublicationTerminalEvidence.fromStored(terminalEvidenceBytes); + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, Integer.toString(schemaVersion)); + DraftAuthorizationFenceBinding.frame(out, targetNamespace); + DraftAuthorizationFenceBinding.frame(out, operationBytes); + DraftAuthorizationFenceBinding.frame(out, terminalEvidenceBytes); + return out.toByteArray(); + } + + public static Request fromStored(byte[] bytes) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(bytes); + reader.expect(SCHEMA); + if (!"1".equals(reader.text())) { + throw new IllegalArgumentException("Unsupported World terminal completion schema"); + } + var request = new Request(1, reader.text(), reader.bytes(), reader.bytes()); + reader.requireEnd(); + if (!Arrays.equals(bytes, request.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical World terminal completion request"); + } + return request; + } + } + + /** Exact owner result echo; the returned terminal bytes are the submitted immutable bytes. */ + public record Response(Request request, GameDesignPublicationTerminalEvidence terminalEvidence) { + public static final String SCHEMA = "world-publication-terminal-completion-response/v1"; + + public Response { + request = Request.fromStored(Objects.requireNonNull(request).canonicalBytes()); + terminalEvidence = + GameDesignPublicationTerminalEvidence.fromStored( + Objects.requireNonNull(terminalEvidence).canonicalBytes()); + if (!Arrays.equals(request.operationBytes(), terminalEvidence.operationBytes()) + || !Arrays.equals(request.terminalEvidenceBytes(), terminalEvidence.canonicalBytes())) { + throw new IllegalArgumentException( + "World terminal completion result differs from the complete original request"); + } + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, request.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, terminalEvidence.canonicalBytes()); + return out.toByteArray(); + } + + public static Response fromStored(byte[] bytes) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(bytes); + reader.expect(SCHEMA); + var response = + new Response( + Request.fromStored(reader.bytes()), + GameDesignPublicationTerminalEvidence.fromStored(reader.bytes())); + reader.requireEnd(); + if (!Arrays.equals(bytes, response.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical World terminal completion response"); + } + return response; + } + } + + public static CompleteWorldPublicationTerminalRequest toRequest(Request request) { + return CompleteWorldPublicationTerminalRequest.newBuilder() + .setCanonicalRequestBytes( + ByteString.copyFrom(Objects.requireNonNull(request).canonicalBytes())) + .build(); + } + + public static Request fromRequest(CompleteWorldPublicationTerminalRequest request) { + if (!Objects.requireNonNull(request).getUnknownFields().asMap().isEmpty() + || request.getCanonicalRequestBytes().isEmpty()) { + throw new IllegalArgumentException("Closed complete World terminal request required"); + } + return Request.fromStored(request.getCanonicalRequestBytes().toByteArray()); + } + + public static CompleteWorldPublicationTerminalResponse toResponse( + Request request, GameDesignPublicationTerminalEvidence terminalEvidence) { + var response = new Response(request, terminalEvidence); + return CompleteWorldPublicationTerminalResponse.newBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(response.canonicalBytes())) + .build(); + } + + public static Response fromResponse( + Request request, CompleteWorldPublicationTerminalResponse response) { + if (!Objects.requireNonNull(response).getUnknownFields().asMap().isEmpty() + || response.getCanonicalResponseBytes().isEmpty()) { + throw new IllegalArgumentException("Closed complete World terminal response required"); + } + Response decoded = Response.fromStored(response.getCanonicalResponseBytes().toByteArray()); + if (!Arrays.equals( + Objects.requireNonNull(request).canonicalBytes(), decoded.request().canonicalBytes())) { + throw new IllegalArgumentException( + "World terminal completion changed the complete original request echo"); + } + return decoded; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublicationTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublicationTerminalReadEvidence.java new file mode 100644 index 0000000000..9969035d68 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublicationTerminalReadEvidence.java @@ -0,0 +1,131 @@ +package net.firedevops.firemud.common.world; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; + +/** Exact World owner-read correlation. Copied GD bytes alone prove no World commit or authority. */ +public final class WorldPublicationTerminalReadEvidence { + private WorldPublicationTerminalReadEvidence() {} + + public enum Status { + UNKNOWN, + PUBLISHED, + ABORTED + } + + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + byte[] expectedTerminalEvidenceBytes) { + public static final int SCHEMA_VERSION = 1; + public static final String SCHEMA = "world-publication-terminal-read-request/v1"; + + public Request { + var terminal = + GameDesignPublicationTerminalEvidence.fromStored(expectedTerminalEvidenceBytes); + // Reuse the canonical namespace, schema and distinct read-UUID validation of the operation. + new GameDesignPublicationTerminalReadEvidence.ReadRequest( + schemaVersion, targetNamespace, readRequestId, terminal.operationBytes()); + expectedTerminalEvidenceBytes = terminal.canonicalBytes(); + } + + public static Request create(String namespace, byte[] expectedTerminalEvidenceBytes) { + return new Request( + SCHEMA_VERSION, namespace, UUID.randomUUID(), expectedTerminalEvidenceBytes); + } + + @Override + public byte[] expectedTerminalEvidenceBytes() { + return expectedTerminalEvidenceBytes.clone(); + } + + public GameDesignPublicationTerminalEvidence terminalEvidence() { + return GameDesignPublicationTerminalEvidence.fromStored(expectedTerminalEvidenceBytes); + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, Integer.toString(schemaVersion)); + DraftAuthorizationFenceBinding.frame(out, targetNamespace); + DraftAuthorizationFenceBinding.frame(out, readRequestId.toString()); + DraftAuthorizationFenceBinding.frame(out, expectedTerminalEvidenceBytes); + return out.toByteArray(); + } + + public static Request fromStored(byte[] bytes) { + var r = new DraftAuthorizationFenceBinding.FrameReader(bytes); + r.expect(SCHEMA); + r.expect("1"); + var result = new Request(1, r.text(), UUID.fromString(r.text()), r.bytes()); + r.requireEnd(); + if (!Arrays.equals(bytes, result.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical World terminal read request"); + return result; + } + } + + public record ReadResult( + Request request, + Status status, + Optional terminalEvidence) { + public static final String SCHEMA = "world-publication-terminal-read-response/v1"; + + public ReadResult { + request = Request.fromStored(Objects.requireNonNull(request).canonicalBytes()); + Objects.requireNonNull(status); + Objects.requireNonNull(terminalEvidence); + if ((status == Status.UNKNOWN) != terminalEvidence.isEmpty()) { + throw new IllegalArgumentException("UNKNOWN alone omits World terminal evidence"); + } + if (terminalEvidence.isPresent()) { + var terminal = + GameDesignPublicationTerminalEvidence.fromStored( + terminalEvidence.orElseThrow().canonicalBytes()); + var expectedStatus = + terminal.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? Status.PUBLISHED + : Status.ABORTED; + if (status != expectedStatus + || !Arrays.equals(request.expectedTerminalEvidenceBytes(), terminal.canonicalBytes())) { + throw new IllegalArgumentException( + "World result differs from exact expected terminal bytes or outcome"); + } + terminalEvidence = Optional.of(terminal); + } + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, request.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, status.name()); + terminalEvidence.ifPresent( + t -> DraftAuthorizationFenceBinding.frame(out, t.canonicalBytes())); + return out.toByteArray(); + } + + public static ReadResult fromStored(byte[] bytes) { + var r = new DraftAuthorizationFenceBinding.FrameReader(bytes); + r.expect(SCHEMA); + var request = Request.fromStored(r.bytes()); + var status = Status.valueOf(r.text()); + var terminal = + status == Status.UNKNOWN + ? Optional.empty() + : Optional.of(GameDesignPublicationTerminalEvidence.fromStored(r.bytes())); + r.requireEnd(); + var result = new ReadResult(request, status, terminal); + if (!Arrays.equals(bytes, result.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical World terminal read response"); + return result; + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublicationTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublicationTerminalReadGrpcCodec.java new file mode 100644 index 0000000000..5740c52678 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublicationTerminalReadGrpcCodec.java @@ -0,0 +1,57 @@ +package net.firedevops.firemud.common.world; + +import com.google.protobuf.ByteString; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.world.WorldPublicationTerminalReadEvidence.ReadResult; +import net.firedevops.firemud.common.world.WorldPublicationTerminalReadEvidence.Request; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublicationTerminalRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublicationTerminalResponse; + +/** Closed wire mapping; receiver authentication must precede decoding. */ +public final class WorldPublicationTerminalReadGrpcCodec { + private WorldPublicationTerminalReadGrpcCodec() {} + + public static ReadWorldPublicationTerminalRequest toRequest(Request request) { + return ReadWorldPublicationTerminalRequest.newBuilder() + .setCanonicalRequestBytes( + ByteString.copyFrom(Objects.requireNonNull(request).canonicalBytes())) + .build(); + } + + public static Request fromRequest(ReadWorldPublicationTerminalRequest request) { + if (!Objects.requireNonNull(request).getUnknownFields().asMap().isEmpty() + || request.getCanonicalRequestBytes().isEmpty()) { + throw new IllegalArgumentException("Closed complete terminal read request required"); + } + return Request.fromStored(request.getCanonicalRequestBytes().toByteArray()); + } + + public static ReadWorldPublicationTerminalResponse toResponse( + Request request, ReadResult result) { + exact(request, result); + return ReadWorldPublicationTerminalResponse.newBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(result.canonicalBytes())) + .build(); + } + + public static ReadResult fromResponse( + Request request, ReadWorldPublicationTerminalResponse response) { + if (!Objects.requireNonNull(response).getUnknownFields().asMap().isEmpty() + || response.getCanonicalResponseBytes().isEmpty()) { + throw new IllegalArgumentException("Closed complete terminal read response required"); + } + var result = ReadResult.fromStored(response.getCanonicalResponseBytes().toByteArray()); + exact(request, result); + return result; + } + + private static void exact(Request request, ReadResult result) { + if (!Arrays.equals( + Objects.requireNonNull(request).canonicalBytes(), + Objects.requireNonNull(result).request().canonicalBytes())) { + throw new IllegalArgumentException( + "Terminal read response changed the complete request echo"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublicationTerminalClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublicationTerminalClientMtlsTest.java new file mode 100644 index 0000000000..a56ab347e6 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublicationTerminalClientMtlsTest.java @@ -0,0 +1,511 @@ +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 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.ByteArrayOutputStream; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateEncodingException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Base64; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +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.WorldPublicationTerminalReadEvidence.ReadResult; +import net.firedevops.firemud.common.world.WorldPublicationTerminalReadEvidence.Request; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublicationTerminalRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublicationTerminalResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldPublicationTerminalReadServiceGrpc; +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 client proof against a labeled transport-only owner source double. */ +class WorldPublicationTerminalClientMtlsTest { + 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 ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + @TempDir static Path tempDirectory; + private static TestPki pki; + private Server server; + private WorldPublicationTerminalClient client; + private AtomicInteger headers; + private AtomicInteger bodies; + + @BeforeAll + static void createTrustedCertificates() 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 exactWorldServerReturnsExplicitUnknownAndUnchangedTerminalEvidence() throws Exception { + for (boolean published : List.of(true, false)) { + var request = WorldPublicationTerminalReadGrpcCodecTest.request(published); + for (Mode mode : List.of(Mode.UNKNOWN, Mode.EXACT)) { + startServer(pki.worldServer(), mode); + client = newClient(server); + client.init(); + var actual = client.read(request); + assertThat(actual.status()) + .isEqualTo( + mode == Mode.UNKNOWN + ? WorldPublicationTerminalReadEvidence.Status.UNKNOWN + : published + ? WorldPublicationTerminalReadEvidence.Status.PUBLISHED + : WorldPublicationTerminalReadEvidence.Status.ABORTED); + if (mode == Mode.EXACT) + assertThat(actual.terminalEvidence().orElseThrow().canonicalBytes()) + .isEqualTo( + WorldPublicationTerminalReadGrpcCodecTest.definitive(request) + .terminalEvidence() + .orElseThrow() + .canonicalBytes()); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + stopTransport(); + } + } + } + + @Test + void trustedWrongWorldWorkloadAndNamespaceReleaseNoMetadataOrBody() throws Exception { + var request = WorldPublicationTerminalReadGrpcCodecTest.request(false); + for (TestIdentity identity : List.of(pki.wrongWorkloadServer(), pki.otherNamespaceServer())) { + startServer(identity, Mode.EXACT); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + e -> + assertThat(Status.fromThrowable(e).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + stopTransport(); + } + } + + @Test + void authenticatedResponseCannotSubstituteReadIdentityOrMalformedTerminalBytes() + throws Exception { + var request = WorldPublicationTerminalReadGrpcCodecTest.request(false); + for (Mode mode : List.of(Mode.WRONG_REQUEST, Mode.WRONG_TERMINAL, Mode.MALFORMED)) { + startServer(pki.worldServer(), mode); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid publication terminal read evidence"); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + stopTransport(); + } + } + + @Test + void refusesPlaintextClasspathUnreadableFilesAndUninitializedOrClosedCalls() throws Exception { + var plain = pki.clientProperties(tempDirectory); + plain.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldPublicationTerminalClient( + new ServiceEndpointsProperties(), plain, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + var classpath = pki.clientProperties(tempDirectory); + classpath.setCaCert("classpath:ca.crt"); + assertThatThrownBy( + () -> + new WorldPublicationTerminalClient( + new ServiceEndpointsProperties(), + classpath, + new GrpcChannelFactory(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + var missing = pki.clientProperties(tempDirectory); + missing.setCaCert(tempDirectory.resolve("absent-ca.crt").toString()); + assertThatThrownBy( + () -> + new WorldPublicationTerminalClient( + new ServiceEndpointsProperties(), missing, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + startServer(pki.worldServer(), Mode.EXACT); + client = newClient(server); + var request = WorldPublicationTerminalReadGrpcCodecTest.request(false); + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + client.init(); + client.close(); + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(client::init).isInstanceOf(IllegalStateException.class); + assertThat(headers).hasValue(0); + } + + private enum Mode { + EXACT, + UNKNOWN, + WRONG_REQUEST, + WRONG_TERMINAL, + MALFORMED + } + + private void startServer(TestIdentity identity, Mode mode) throws Exception { + headers = new AtomicInteger(); + bodies = new AtomicInteger(); + var service = + new WorldPublicationTerminalReadServiceGrpc.WorldPublicationTerminalReadServiceImplBase() { + @Override + public void readWorldPublicationTerminal( + ReadWorldPublicationTerminalRequest wire, + StreamObserver observer) { + bodies.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(ACCOUNT_URI); + var request = WorldPublicationTerminalReadGrpcCodec.fromRequest(wire); + ReadWorldPublicationTerminalResponse response; + if (mode == Mode.MALFORMED) + response = + ReadWorldPublicationTerminalResponse.newBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(new byte[] {(byte) 0xff})) + .build(); + else if (mode == Mode.WRONG_TERMINAL) { + var bytes = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + bytes, WorldPublicationTerminalReadEvidence.ReadResult.SCHEMA); + DraftAuthorizationFenceBinding.frame(bytes, request.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(bytes, "ABORTED"); + DraftAuthorizationFenceBinding.frame( + bytes, + WorldPublicationTerminalReadGrpcCodecTest.changedTerminal(request) + .canonicalBytes()); + response = + ReadWorldPublicationTerminalResponse.newBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(bytes.toByteArray())) + .build(); + } else { + if (mode == Mode.WRONG_REQUEST) + request = + new Request( + 1, + NAMESPACE, + UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"), + request.expectedTerminalEvidenceBytes()); + var result = + mode == Mode.UNKNOWN + ? new ReadResult( + request, + WorldPublicationTerminalReadEvidence.Status.UNKNOWN, + Optional.empty()) + : WorldPublicationTerminalReadGrpcCodecTest.definitive(request); + response = WorldPublicationTerminalReadGrpcCodec.toResponse(request, result); + } + observer.onNext(response); + observer.onCompleted(); + } + }; + ServerInterceptor countHeaders = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + headers.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, countHeaders, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private WorldPublicationTerminalClient newClient(Server target) + throws IOException, CertificateEncodingException { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("localhost:" + target.getPort()); + return new WorldPublicationTerminalClient( + endpoints, pki.clientProperties(tempDirectory), new GrpcChannelFactory(), NAMESPACE); + } + + private record TestIdentity(String alias, PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity worldServer, + TestIdentity wrongWorkloadServer, + TestIdentity otherNamespaceServer, + TestIdentity accountClient) { + 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, "account-client", ACCOUNT_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory) + throws IOException, CertificateEncodingException { + Path clientCertificate = + writePem( + directory.resolve("account-client.crt"), + "CERTIFICATE", + accountClient.certificate().getEncoded()); + Path clientPrivateKey = + writePem( + directory.resolve("account-client.key"), + "PRIVATE KEY", + accountClient.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/WorldPublicationTerminalCompletionClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublicationTerminalCompletionClientMtlsTest.java new file mode 100644 index 0000000000..3b43dbe1de --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublicationTerminalCompletionClientMtlsTest.java @@ -0,0 +1,466 @@ +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 io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Base64; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.worldmanagement.v1.CompleteWorldPublicationTerminalRequest; +import net.firedevops.firemud.worldmanagement.v1.CompleteWorldPublicationTerminalResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldPublicationTerminalCompletionServiceGrpc; +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 mTLS transport proof against a labeled terminal owner-source double. */ +class WorldPublicationTerminalCompletionClientMtlsTest { + 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/account-service"; + private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + @TempDir static Path tempDirectory; + private static TestPki pki; + private Server server; + private WorldPublicationTerminalCompletionClient client; + private AtomicInteger headers; + private AtomicInteger bodies; + + @BeforeAll + static void createTrustedCertificates() 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 exactWorldPeerReturnsTheSameCompleteTerminalAndOperation() throws Exception { + var request = request(); + startServer(pki.worldServer(), Mode.EXACT); + client = newClient(server); + client.init(); + + var result = client.complete(request); + + assertThat(result.request().canonicalBytes()).containsExactly(request.canonicalBytes()); + assertThat(result.terminalEvidence().canonicalBytes()) + .containsExactly(request.terminalEvidenceBytes()); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + } + + @Test + void wrongWorldWorkloadAndNamespaceReleaseNoMetadataOrBody() throws Exception { + var request = request(); + for (TestIdentity identity : List.of(pki.wrongWorkloadServer(), pki.otherNamespaceServer())) { + startServer(identity, Mode.EXACT); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.complete(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + stopTransport(); + } + } + + @Test + void authenticatedWorldResponseCannotChangeRequestOrTerminal() throws Exception { + var request = request(); + for (Mode mode : List.of(Mode.WRONG_REQUEST, Mode.MALFORMED)) { + startServer(pki.worldServer(), mode); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.complete(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid publication terminal completion evidence"); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + stopTransport(); + } + } + + @Test + void requiresFileBackedMtlsAndExplicitOpenClient() throws Exception { + var plain = pki.clientProperties(tempDirectory); + plain.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldPublicationTerminalCompletionClient( + new ServiceEndpointsProperties(), plain, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + var classpath = pki.clientProperties(tempDirectory); + classpath.setCaCert("classpath:ca.crt"); + assertThatThrownBy( + () -> + new WorldPublicationTerminalCompletionClient( + new ServiceEndpointsProperties(), + classpath, + new GrpcChannelFactory(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + var missing = pki.clientProperties(tempDirectory); + missing.setCaCert(tempDirectory.resolve("absent-ca.crt").toString()); + assertThatThrownBy( + () -> + new WorldPublicationTerminalCompletionClient( + new ServiceEndpointsProperties(), missing, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + + startServer(pki.worldServer(), Mode.EXACT); + client = newClient(server); + var request = request(); + assertThatThrownBy(() -> client.complete(request)).isInstanceOf(IllegalStateException.class); + client.init(); + client.close(); + assertThatThrownBy(() -> client.complete(request)).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(client::init).isInstanceOf(IllegalStateException.class); + assertThat(headers).hasValue(0); + } + + private enum Mode { + EXACT, + WRONG_REQUEST, + MALFORMED + } + + private void startServer(TestIdentity identity, Mode mode) throws Exception { + headers = new AtomicInteger(); + bodies = new AtomicInteger(); + var request = request(); + var responseRequest = + mode == Mode.WRONG_REQUEST + ? WorldPublicationTerminalCompletionGrpcCodecTest.changedRequest(request) + : request; + var service = + new WorldPublicationTerminalCompletionServiceGrpc + .WorldPublicationTerminalCompletionServiceImplBase() { + @Override + public void completeWorldPublicationTerminal( + CompleteWorldPublicationTerminalRequest wire, + StreamObserver observer) { + bodies.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(GAME_DESIGN_URI); + WorldPublicationTerminalCompletionGrpcCodec.fromRequest(wire); + var response = + mode == Mode.MALFORMED + ? CompleteWorldPublicationTerminalResponse.newBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(new byte[] {(byte) 0xff})) + .build() + : WorldPublicationTerminalCompletionGrpcCodec.toResponse( + responseRequest, responseRequest.terminalEvidence()); + observer.onNext(response); + observer.onCompleted(); + } + }; + ServerInterceptor countHeaders = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + headers.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, countHeaders, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private WorldPublicationTerminalCompletionClient newClient(Server target) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("localhost:" + target.getPort()); + return new WorldPublicationTerminalCompletionClient( + endpoints, pki.clientProperties(tempDirectory), new GrpcChannelFactory(), NAMESPACE); + } + + private static WorldPublicationTerminalCompletionGrpcCodec.Request request() throws Exception { + var readRequest = WorldPublicationTerminalReadGrpcCodecTest.request(false); + var terminal = readRequest.terminalEvidence(); + return new WorldPublicationTerminalCompletionGrpcCodec.Request( + 1, readRequest.targetNamespace(), terminal.operationBytes(), terminal.canonicalBytes()); + } + + private record TestIdentity(String alias, PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity worldServer, + TestIdentity wrongWorkloadServer, + TestIdentity otherNamespaceServer, + TestIdentity gameDesignClient) { + 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-world-server", WRONG_WORKLOAD_URI, true), + issueIdentity(directory, caStore, caFile, "other-world-server", OTHER_WORLD_URI, true), + issueIdentity(directory, caStore, caFile, "game-design-client", GAME_DESIGN_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory) throws Exception { + Path clientCertificate = + writePem( + directory.resolve("game-design-client.crt"), + "CERTIFICATE", + gameDesignClient.certificate().getEncoded()); + Path clientPrivateKey = + writePem( + directory.resolve("game-design-client.key"), + "PRIVATE KEY", + gameDesignClient.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/WorldPublicationTerminalCompletionGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublicationTerminalCompletionGrpcCodecTest.java new file mode 100644 index 0000000000..f0894f9024 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublicationTerminalCompletionGrpcCodecTest.java @@ -0,0 +1,100 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.Arrays; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import org.junit.jupiter.api.Test; + +class WorldPublicationTerminalCompletionGrpcCodecTest { + @Test + void preservesCompleteOperationAndTerminalAcrossClosedRequestAndResponse() throws Exception { + var request = request(); + var wireRequest = WorldPublicationTerminalCompletionGrpcCodec.toRequest(request); + var decodedRequest = WorldPublicationTerminalCompletionGrpcCodec.fromRequest(wireRequest); + assertThat(decodedRequest.canonicalBytes()).containsExactly(request.canonicalBytes()); + assertThat(decodedRequest.operationBytes()).containsExactly(request.operationBytes()); + assertThat(decodedRequest.terminalEvidenceBytes()) + .containsExactly(request.terminalEvidenceBytes()); + + var wireResponse = + WorldPublicationTerminalCompletionGrpcCodec.toResponse(request, request.terminalEvidence()); + var decodedResponse = + WorldPublicationTerminalCompletionGrpcCodec.fromResponse(request, wireResponse); + assertThat(decodedResponse.canonicalBytes()) + .containsExactly( + new WorldPublicationTerminalCompletionGrpcCodec.Response( + request, request.terminalEvidence()) + .canonicalBytes()); + assertThat(decodedResponse.request().canonicalBytes()) + .containsExactly(request.canonicalBytes()); + assertThat(decodedResponse.terminalEvidence().canonicalBytes()) + .containsExactly(request.terminalEvidenceBytes()); + + byte[] escaped = request.terminalEvidenceBytes(); + escaped[0] ^= 0x7f; + assertThat(request.terminalEvidenceBytes()).isNotEqualTo(escaped); + } + + @Test + void rejectsOperationTerminalNamespaceSchemaAndWireSubstitution() throws Exception { + var request = request(); + var readRequest = WorldPublicationTerminalReadGrpcCodecTest.request(false); + var changedOperationTerminal = + WorldPublicationTerminalReadGrpcCodecTest.changedTerminal(readRequest); + assertThatThrownBy( + () -> + new WorldPublicationTerminalCompletionGrpcCodec.Request( + 1, + request.targetNamespace(), + request.operationBytes(), + changedOperationTerminal.canonicalBytes())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new WorldPublicationTerminalCompletionGrpcCodec.Request( + 2, + request.targetNamespace(), + request.operationBytes(), + request.terminalEvidenceBytes())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new WorldPublicationTerminalCompletionGrpcCodec.Request( + 1, "other", request.operationBytes(), request.terminalEvidenceBytes())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldPublicationTerminalCompletionGrpcCodec.fromRequest( + WorldPublicationTerminalCompletionGrpcCodec.toRequest(request).toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldPublicationTerminalCompletionGrpcCodec.Request.fromStored( + Arrays.copyOf(request.canonicalBytes(), request.canonicalBytes().length + 1))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static WorldPublicationTerminalCompletionGrpcCodec.Request request() throws Exception { + var readRequest = WorldPublicationTerminalReadGrpcCodecTest.request(false); + GameDesignPublicationTerminalEvidence terminal = readRequest.terminalEvidence(); + return new WorldPublicationTerminalCompletionGrpcCodec.Request( + 1, readRequest.targetNamespace(), terminal.operationBytes(), terminal.canonicalBytes()); + } + + static WorldPublicationTerminalCompletionGrpcCodec.Request changedRequest( + WorldPublicationTerminalCompletionGrpcCodec.Request original) throws Exception { + var readRequest = WorldPublicationTerminalReadGrpcCodecTest.request(false); + var changed = WorldPublicationTerminalReadGrpcCodecTest.changedTerminal(readRequest); + return new WorldPublicationTerminalCompletionGrpcCodec.Request( + 1, original.targetNamespace(), changed.operationBytes(), changed.canonicalBytes()); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublicationTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublicationTerminalReadGrpcCodecTest.java new file mode 100644 index 0000000000..944c192a25 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublicationTerminalReadGrpcCodecTest.java @@ -0,0 +1,277 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.world.WorldPublicationTerminalReadEvidence.ReadResult; +import net.firedevops.firemud.common.world.WorldPublicationTerminalReadEvidence.Request; +import net.firedevops.firemud.common.world.WorldPublicationTerminalReadEvidence.Status; +import org.junit.jupiter.api.Test; + +/** Stipulated GD terminal inputs test carrier integrity, never committed World owner state. */ +class WorldPublicationTerminalReadGrpcCodecTest { + @Test + void preservesExactExpectedEvidenceAndRequestForUnknownPublishedAndAborted() throws Exception { + for (boolean published : List.of(true, false)) { + var request = request(published); + assertThat( + WorldPublicationTerminalReadGrpcCodec.fromRequest( + WorldPublicationTerminalReadGrpcCodec.toRequest(request)) + .canonicalBytes()) + .isEqualTo(request.canonicalBytes()); + assertThat(request.terminalEvidence().canonicalBytes()) + .isEqualTo(request.expectedTerminalEvidenceBytes()); + for (var result : + List.of(new ReadResult(request, Status.UNKNOWN, Optional.empty()), definitive(request))) { + var decoded = + WorldPublicationTerminalReadGrpcCodec.fromResponse( + request, WorldPublicationTerminalReadGrpcCodec.toResponse(request, result)); + assertThat(decoded.canonicalBytes()).isEqualTo(result.canonicalBytes()); + assertThat(decoded.status()).isEqualTo(result.status()); + } + byte[] escaped = request.expectedTerminalEvidenceBytes(); + escaped[0] = 99; + assertThat(request.expectedTerminalEvidenceBytes()).isNotEqualTo(escaped); + } + } + + @Test + void rejectsUnsupportedTrailingMixedOutcomeChangedTerminalAndEchoIdentity() throws Exception { + var request = request(false); + var result = definitive(request); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + assertThatThrownBy( + () -> + WorldPublicationTerminalReadGrpcCodec.fromRequest( + WorldPublicationTerminalReadGrpcCodec.toRequest(request).toBuilder() + .setUnknownFields(unknown) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldPublicationTerminalReadGrpcCodec.fromResponse( + request, + WorldPublicationTerminalReadGrpcCodec.toResponse(request, result).toBuilder() + .setUnknownFields(unknown) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + Request.fromStored( + Arrays.copyOf(request.canonicalBytes(), request.canonicalBytes().length + 1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + ReadResult.fromStored( + Arrays.copyOf(result.canonicalBytes(), result.canonicalBytes().length + 1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new Request(2, "test", UUID.randomUUID(), request.expectedTerminalEvidenceBytes())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new Request(1, "test", new UUID(0, 0), request.expectedTerminalEvidenceBytes())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new Request(1, "other", UUID.randomUUID(), request.expectedTerminalEvidenceBytes())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new Request( + 1, + "test", + request.terminalEvidence().worldEvidence().request().publicationFence(), + request.expectedTerminalEvidenceBytes())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new ReadResult(request, Status.UNKNOWN, result.terminalEvidence())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new ReadResult(request, Status.PUBLISHED, result.terminalEvidence())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new ReadResult(request, Status.ABORTED, Optional.empty())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new ReadResult(request, Status.ABORTED, Optional.of(changedTerminal(request)))) + .isInstanceOf(IllegalArgumentException.class); + var changedRead = + new Request(1, "test", UUID.randomUUID(), request.expectedTerminalEvidenceBytes()); + assertThatThrownBy( + () -> + WorldPublicationTerminalReadGrpcCodec.fromResponse( + request, + WorldPublicationTerminalReadGrpcCodec.toResponse( + changedRead, definitive(changedRead)))) + .isInstanceOf(IllegalArgumentException.class); + byte[] malformed = request.canonicalBytes(); + malformed[0] = (byte) 0xff; + assertThatThrownBy(() -> Request.fromStored(malformed)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> Request.fromStored(request.terminalEvidence().canonicalBytes())) + .isInstanceOf(IllegalArgumentException.class); + } + + static ReadResult definitive(Request request) { + return new ReadResult( + request, + request.terminalEvidence().outcome() + == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? Status.PUBLISHED + : Status.ABORTED, + Optional.of(request.terminalEvidence())); + } + + static GameDesignPublicationTerminalEvidence changedTerminal(Request request) { + var operation = + GameDesignPublicationOperationBinding.fromStored( + request.terminalEvidence().operationBytes()); + var account = operation.account(); + var changed = + new GameDesignPublicationOperationBinding( + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), account.fenceId(), account.input(), account.sources()), + operation.world()); + return new GameDesignPublicationTerminalEvidence( + changed.canonicalBytes(), + GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION, + null, + null); + } + + static Request request(boolean published) throws Exception { + var seed = WorldPublishedStartLocationGrpcCodecTest.evidence(); + var original = DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); + var draft = + DraftCommitBinding.fromStored( + new String(original.gameDesignBinding(), StandardCharsets.UTF_8), + original.inputDigest()); + var target = draft.target(); + String requestId = "world-publication-terminal-test"; + var selected = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + requestId, + "5", + "ISOLATED fixed notes", + draft.requestId(), + draft.commitId(), + draft.digest()), + target, + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + draft.requestId(), + draft.commitId(), + draft.digest(), + "[]", + OffsetDateTime.parse("2026-10-07T00:00:00Z"))); + var account = + new AccountPublicationAuthorizationBinding( + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + new AccountPublicationAuthorizationBinding.PreallocationInput( + original.actorAccountId(), selected), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + original.actorAccountId().toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + var r = seed.request(); + var world = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + r.targetNamespace(), + r.canonicalTenantId(), + r.canonicalVersionId(), + r.intakeRequestId(), + r.publicationFence(), + requestId, + selected.digest().substring(7), + 5, + PublicationDigestRequestBinding.full( + target.canonicalTenantId().toString(), + Long.toString(target.gameDesignVersionRowId()), + requestId) + .derivedWorkflowIdentity(), + r.appliedCommitId(), + r.contentDigest(), + r.digestSchemaVersion(), + r.worldAffectedTuples()), + seed.selectorReceiptBytes(), + seed.originalAccountBindingBytes(), + seed.appliedResultBytes()); + var operation = new GameDesignPublicationOperationBinding(account, world); + GameDesignPublicationTerminalEvidence.ReleaseContent content = null; + if (published) { + String digest = "sha256:" + "a".repeat(64); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new GameDesignPublicationTerminalEvidence.Participant( + owner, + Long.toString(target.gameDesignVersionRowId()), + null, + r.appliedCommitId(), + owner.equals("WORLD_MANAGEMENT") ? r.contentDigest() : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + owner.equals("GAME_LOGIC") ? digest : null, + null, + null)) + .toList(); + content = + new GameDesignPublicationTerminalEvidence.ReleaseContent( + target.canonicalTenantId(), + target.canonicalVersionId(), + "ISOLATED-bundle", + 1, + "v2", + world.request().publishWorkflowId(), + digest, + 1, + List.of(), + List.of(), + participants, + List.of("LOOK"), + "generation-1", + world); + } + var terminal = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + published + ? GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + : GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION, + content, + published ? 6L : null); + return new Request( + 1, + "test", + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + terminal.canonicalBytes()); + } +} 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 5b557cca27..cf3c5fc20f 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 @@ -527,7 +527,7 @@ private static void requireExactPublishedRelease( || !bundle.canonicalTenantId().equals(release.canonicalTenantId()) || !bundle.canonicalVersionId().equals(release.canonicalVersionId()) || !bundle.publishedReleaseBundleRef().equals(release.publishedReleaseBundleRef()) - || terminal.publicationVersionStateEpoch() != release.versionStateEpoch() + || terminal.publicationVersionStateEpoch() > release.versionStateEpoch() || !bundle.publishWorkflowId().equals(release.publishWorkflowId()) || !bundle .publishWorkflowId() diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalCompletionGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalCompletionGrpcService.java new file mode 100644 index 0000000000..dfe35292d2 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalCompletionGrpcService.java @@ -0,0 +1,234 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldPublicationTerminalCompletionGrpcCodec; +import net.firedevops.firemud.common.world.WorldPublicationTerminalCompletionGrpcCodec.Request; +import net.firedevops.firemud.worldmanagement.v1.CompleteWorldPublicationTerminalRequest; +import net.firedevops.firemud.worldmanagement.v1.CompleteWorldPublicationTerminalResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldPublicationTerminalCompletionServiceGrpc; +import org.jooq.exception.DataAccessException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Standalone authenticated Game Design completion adapter; intentionally not runtime-registered. + */ +public final class WorldPublicationTerminalCompletionGrpcService + extends WorldPublicationTerminalCompletionServiceGrpc + .WorldPublicationTerminalCompletionServiceImplBase { + private final GameDesignPublicationTerminalClient gameDesignClient; + private final WorldPublicationTerminalService terminalService; + private final String trustedNamespace; + + public WorldPublicationTerminalCompletionGrpcService( + WorldPublicationTerminalRepository repository, + GameDesignPublicationTerminalClient gameDesignClient, + String trustedNamespace) { + Objects.requireNonNull(repository, "repository"); + this.gameDesignClient = Objects.requireNonNull(gameDesignClient, "gameDesignClient"); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.trustedNamespace = trustedNamespace; + terminalService = + new WorldPublicationTerminalService(repository, this::authenticateAndVerifyAndHold); + } + + @Override + public void completeWorldPublicationTerminal( + CompleteWorldPublicationTerminalRequest request, + StreamObserver responseObserver) { + GrpcPeerIdentity caller = GrpcPeerIdentity.current(); + if (!isAuthenticatedGameDesignPeer(caller)) { + deny(responseObserver); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive()) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("World terminal completion cannot join an ambient transaction") + .asRuntimeException()); + return; + } + + Request completion; + try { + completion = WorldPublicationTerminalCompletionGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException invalid) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("A complete canonical World terminal completion is required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(completion.targetNamespace())) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("World terminal namespace must match the authenticated peer") + .asRuntimeException()); + return; + } + + GameDesignPublicationTerminalEvidence committed; + try { + committed = + terminalService.complete(completion.operationBytes(), completion.terminalEvidenceBytes()); + } catch (UpstreamTerminalUnavailableException unavailable) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Game Design has no definitive exact terminal result yet") + .asRuntimeException()); + return; + } catch (StatusRuntimeException unavailable) { + Status.Code code = Status.fromThrowable(unavailable).getCode(); + Status resultStatus = + code == Status.Code.UNAVAILABLE + || code == Status.Code.DEADLINE_EXCEEDED + || code == Status.Code.CANCELLED + || code == Status.Code.RESOURCE_EXHAUSTED + ? Status.UNAVAILABLE + : Status.FAILED_PRECONDITION; + responseObserver.onError( + resultStatus + .withDescription("Game Design terminal authority could not be confirmed") + .asRuntimeException()); + return; + } catch (WorldPublicationTerminalRepository.PublicationTerminalConflictException conflict) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("World terminal conflicts with exact retained owner evidence") + .asRuntimeException()); + return; + } catch (WorldPublicationTerminalService.TerminalDeniedException denied) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Game Design terminal evidence is not definitive or exact") + .asRuntimeException()); + return; + } catch (org.springframework.dao.DataAccessException | DataAccessException unavailable) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("World terminal owner storage is temporarily unavailable") + .asRuntimeException()); + return; + } catch (RuntimeException failure) { + responseObserver.onError( + Status.INTERNAL.withDescription("World terminal completion failed").asRuntimeException()); + return; + } + + try { + responseObserver.onNext( + WorldPublicationTerminalCompletionGrpcCodec.toResponse(completion, committed)); + responseObserver.onCompleted(); + } catch (IllegalArgumentException | IllegalStateException inconsistent) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("World terminal commit differs from the complete request") + .asRuntimeException()); + } + } + + private WorldPublicationTerminalService.VerifiedTerminal authenticateAndVerifyAndHold( + byte[] operationBytes, byte[] terminalBytes) { + GrpcPeerIdentity caller = GrpcPeerIdentity.current(); + if (!isAuthenticatedGameDesignPeer(caller)) { + throw new WorldPublicationTerminalService.TerminalDeniedException( + "Verified same-namespace Game Design workload is required"); + } + byte[] retainedOperation = operationBytes.clone(); + byte[] selectedTerminal = terminalBytes.clone(); + var readRequest = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + trustedNamespace, retainedOperation); + GameDesignPublicationTerminalReadEvidence.ReadResult readback; + try { + readback = gameDesignClient.read(readRequest); + } catch (StatusRuntimeException failure) { + Status.Code code = Status.fromThrowable(failure).getCode(); + if (code == Status.Code.UNAVAILABLE + || code == Status.Code.DEADLINE_EXCEEDED + || code == Status.Code.CANCELLED + || code == Status.Code.RESOURCE_EXHAUSTED) { + throw new UpstreamTerminalUnavailableException(failure); + } + throw failure; + } catch (RuntimeException invalidEvidence) { + throw new WorldPublicationTerminalService.TerminalDeniedException( + "Game Design terminal read did not return valid definitive evidence"); + } + if (readback == null) { + throw new WorldPublicationTerminalService.TerminalDeniedException( + "Game Design terminal read returned no response"); + } + if (!Arrays.equals(readRequest.canonicalBytes(), readback.request().canonicalBytes())) { + throw new WorldPublicationTerminalService.TerminalDeniedException( + "Game Design terminal read changed the complete original operation"); + } + if (readback.status() == GameDesignPublicationTerminalReadEvidence.Status.UNKNOWN) { + throw new UpstreamTerminalUnavailableException(null); + } + if (readback.terminalEvidence().isEmpty()) { + throw new WorldPublicationTerminalService.TerminalDeniedException( + "Game Design terminal read omitted definitive terminal evidence"); + } + GameDesignPublicationTerminalEvidence evidence = readback.terminalEvidence().orElseThrow(); + if (!Arrays.equals(retainedOperation, evidence.operationBytes()) + || !Arrays.equals(selectedTerminal, evidence.canonicalBytes())) { + throw new WorldPublicationTerminalRepository.PublicationTerminalConflictException( + "Authenticated Game Design terminal read differs from the submitted exact evidence"); + } + var worldRequest = WorldPublicationTerminal.Request.fromStored(evidence.canonicalBytes()); + return new WorldPublicationTerminalService.VerifiedTerminal( + worldRequest, + new WorldPublicationTerminalService.HeldTerminalAuthority() { + private boolean open = true; + + @Override + public void requireHeld() { + if (!open + || !caller.equals(GrpcPeerIdentity.current()) + || !isAuthenticatedGameDesignPeer(GrpcPeerIdentity.current()) + || !Arrays.equals(retainedOperation, evidence.operationBytes()) + || !Arrays.equals(selectedTerminal, evidence.canonicalBytes())) { + throw new WorldPublicationTerminalService.TerminalDeniedException( + "Authenticated Game Design identity and exact terminal must remain stable through World commit"); + } + } + + @Override + public void close() { + open = false; + } + }); + } + + private boolean isAuthenticatedGameDesignPeer(GrpcPeerIdentity peer) { + return peer != null + && peer.isService("game-design-service") + && peer.isInNamespace(trustedNamespace) + && !SessionContext.hasAuthenticatedCallerContext(); + } + + private static void deny(StreamObserver responseObserver) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "Only the verified same-namespace Game Design workload without end-user context is allowed") + .asRuntimeException()); + } + + private static final class UpstreamTerminalUnavailableException extends RuntimeException { + private UpstreamTerminalUnavailableException(Throwable cause) { + super("Game Design terminal authority is not definitive", cause); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadGrpcService.java new file mode 100644 index 0000000000..ee3b8f010e --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadGrpcService.java @@ -0,0 +1,122 @@ +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.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.world.WorldPublicationTerminalReadEvidence.ReadResult; +import net.firedevops.firemud.common.world.WorldPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublicationTerminalRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublicationTerminalResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldPublicationTerminalReadServiceGrpc; +import org.jooq.exception.DataAccessException; + +/** Standalone authenticated exact owner read; deliberately not registered as a runtime RPC. */ +public final class WorldPublicationTerminalReadGrpcService + extends WorldPublicationTerminalReadServiceGrpc.WorldPublicationTerminalReadServiceImplBase { + private final WorldPublicationTerminalRepository repository; + private final String trustedNamespace; + + public WorldPublicationTerminalReadGrpcService( + WorldPublicationTerminalRepository 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 readWorldPublicationTerminal( + ReadWorldPublicationTerminalRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedAccountPeer(responseObserver)) return; + + WorldPublicationTerminalReadEvidence.Request readRequest; + try { + readRequest = WorldPublicationTerminalReadGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException invalid) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("A complete canonical World publication terminal read is required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(readRequest.targetNamespace())) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("World terminal namespace must match the authenticated peer") + .asRuntimeException()); + return; + } + + Optional stored; + try { + stored = + repository.readCommitted( + WorldPublicationTerminal.Request.fromStored( + readRequest.expectedTerminalEvidenceBytes())); + } catch (WorldPublicationTerminalRepository.PublicationTerminalConflictException conflict) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("World terminal differs from exact committed owner evidence") + .asRuntimeException()); + return; + } catch (org.springframework.dao.DataAccessException | DataAccessException unavailable) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("World terminal owner storage is temporarily unavailable") + .asRuntimeException()); + return; + } catch (RuntimeException failure) { + responseObserver.onError( + Status.INTERNAL.withDescription("World terminal owner read failed").asRuntimeException()); + return; + } + + ReadResult result; + if (stored.isEmpty()) { + result = + new ReadResult( + readRequest, WorldPublicationTerminalReadEvidence.Status.UNKNOWN, Optional.empty()); + } else { + GameDesignPublicationTerminalEvidence evidence = stored.orElseThrow(); + WorldPublicationTerminalReadEvidence.Status status = + evidence.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? WorldPublicationTerminalReadEvidence.Status.PUBLISHED + : WorldPublicationTerminalReadEvidence.Status.ABORTED; + result = new ReadResult(readRequest, status, Optional.of(evidence)); + } + + try { + responseObserver.onNext( + WorldPublicationTerminalReadGrpcCodec.toResponse(readRequest, result)); + responseObserver.onCompleted(); + } catch (IllegalArgumentException | IllegalStateException inconsistent) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("World terminal response differs from exact owner readback") + .asRuntimeException()); + } + } + + private boolean requireAuthenticatedAccountPeer(StreamObserver responseObserver) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer != null + && peer.isService("account-service") + && peer.isInNamespace(trustedNamespace) + && !SessionContext.hasAuthenticatedCallerContext()) { + return true; + } + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "Only the verified same-namespace Account 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/WorldPublicationTerminalRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalRepository.java index 500c85b9ee..86a1194249 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalRepository.java @@ -8,6 +8,7 @@ import java.util.Objects; import java.util.Optional; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.transaction.PlatformTransactionManager; @@ -42,14 +43,31 @@ public final class WorldPublicationTerminalRepository { + "AND o.canonical_tenant_id=a.canonical_tenant_id " + "AND o.local_tenant_key=a.local_tenant_key AND o.version_id=a.version_id " + "WHERE t.publication_fence=?"; + private static final String ORIGINAL_OWNER_READ = + "SELECT a.*, o.owner_freeze_phase, o.current_publication_fence " + + "FROM world_design_publication_fence_attempt a " + + "JOIN world_design_publication_fence_owner o " + + "ON o.target_namespace=a.target_namespace " + + "AND o.canonical_tenant_id=a.canonical_tenant_id " + + "AND o.local_tenant_key=a.local_tenant_key AND o.version_id=a.version_id " + + "WHERE a.publication_fence=? AND a.target_namespace=? " + + "AND a.canonical_tenant_id=? AND a.canonical_version_id=? " + + "AND o.current_publication_fence=a.publication_fence"; private final DSLContext dsl; + private final TransactionTemplate independentReadTransaction; private final TransactionTemplate ownerTransaction; public WorldPublicationTerminalRepository( DSLContext dsl, PlatformTransactionManager transactionManager) { this.dsl = Objects.requireNonNull(dsl, "dsl"); - ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + PlatformTransactionManager manager = Objects.requireNonNull(transactionManager); + independentReadTransaction = new TransactionTemplate(manager); + independentReadTransaction.setPropagationBehavior( + TransactionDefinition.PROPAGATION_REQUIRES_NEW); + independentReadTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + independentReadTransaction.setReadOnly(true); + ownerTransaction = new TransactionTemplate(manager); ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); } @@ -131,7 +149,16 @@ public Optional readCommitted( WorldPublicationTerminal.Request request) { Objects.requireNonNull(request, "request"); requireNoAmbientTransaction("World publication terminal readback"); - Record row = readTerminalWithOwner(request, false); + Record row = + independentReadTransaction.execute( + status -> { + requireReadOnlyRepeatableReadTransaction(); + Record terminal = readTerminalWithOwner(request, false); + if (terminal == null) { + requirePendingOwner(request); + } + return terminal; + }); if (row == null) return Optional.empty(); return Optional.of(exactReadback(request, row)); } @@ -140,19 +167,37 @@ private Record lockOriginalOwner(WorldPublicationTerminal.Request request) { var world = request.worldEvidence().request(); Record row = dsl.fetchOne( - "SELECT a.*,o.owner_freeze_phase,o.current_publication_fence " - + "FROM world_design_publication_fence_attempt a " - + "JOIN world_design_publication_fence_owner o " - + "ON o.target_namespace=a.target_namespace " - + "AND o.canonical_tenant_id=a.canonical_tenant_id " - + "AND o.local_tenant_key=a.local_tenant_key AND o.version_id=a.version_id " - + "WHERE a.publication_fence=? AND a.target_namespace=? " - + "AND a.canonical_tenant_id=? AND a.canonical_version_id=? " - + "AND o.current_publication_fence=a.publication_fence FOR UPDATE OF o", + ORIGINAL_OWNER_READ + " FOR UPDATE OF o", world.publicationFence(), world.targetNamespace(), world.canonicalTenantId(), world.canonicalVersionId()); + requireOriginalOwnerBinding(world, row); + return row; + } + + private void requirePendingOwner(WorldPublicationTerminal.Request request) { + var world = request.worldEvidence().request(); + Record owner = + dsl.fetchOne( + ORIGINAL_OWNER_READ, + world.publicationFence(), + world.targetNamespace(), + world.canonicalTenantId(), + world.canonicalVersionId()); + if (owner == null) { + throw new PublicationTerminalConflictException( + "World terminal request has no exact retained V25 attempt and current owner association"); + } + requireOriginalOwnerBinding(world, owner); + if (!"FROZEN".equals(required(owner, "owner_freeze_phase", String.class))) { + throw new PublicationTerminalConflictException( + "Missing World publication terminal conflicts with the retained owner phase"); + } + } + + private static void requireOriginalOwnerBinding( + WorldPublishedStartLocationEvidence.Request world, Record row) { if (row == null) { throw new PublicationTerminalConflictException( "World terminal request has no exact retained V25 attempt and current owner association"); @@ -174,7 +219,6 @@ private Record lockOriginalOwner(WorldPublicationTerminal.Request request) { throw new PublicationTerminalConflictException( "World terminal evidence differs from its exact immutable V25 publication checkpoint"); } - return row; } private void insertTerminal(WorldPublicationTerminal.Request request) { @@ -364,6 +408,26 @@ private void requireWritableReadCommittedTransaction() { } } + private void requireReadOnlyRepeatableReadTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World publication terminal read requires a read-only REPEATABLE READ transaction"); + } + Record settings = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"); + if (settings == null + || !"repeatable read".equalsIgnoreCase(required(settings, "isolation", String.class)) + || !"on".equalsIgnoreCase(required(settings, "read_only", String.class))) { + throw new IllegalStateException( + "World publication terminal read requires a read-only REPEATABLE READ transaction"); + } + } + public static class PublicationTerminalConflictException extends IllegalStateException { public PublicationTerminalConflictException(String message) { super(message); diff --git a/services/world-management-service/src/main/resources/db/migration/V44__world_publication_terminal_handoff.sql b/services/world-management-service/src/main/resources/db/migration/V44__world_publication_terminal_handoff.sql index bda08d2c32..9547215d6c 100644 --- a/services/world-management-service/src/main/resources/db/migration/V44__world_publication_terminal_handoff.sql +++ b/services/world-management-service/src/main/resources/db/migration/V44__world_publication_terminal_handoff.sql @@ -334,7 +334,7 @@ DECLARE AND t.content_digest=capture_row.freeze_request_json::JSONB->>'contentDigest' AND t.digest_schema_version=(capture_row.freeze_request_json::JSONB->>'digestSchemaVersion')::INTEGER AND t.published_release_bundle_ref=binding_row.release_attestation_json::JSONB->>'publishedReleaseBundleRef' - AND t.publication_version_state_epoch=(binding_row.release_attestation_json::JSONB->>'versionStateEpoch')::BIGINT + AND t.publication_version_state_epoch<=(binding_row.release_attestation_json::JSONB->>'versionStateEpoch')::BIGINT AND t.world_request_json::JSONB=jsonb_set( binding_row.release_attestation_json::JSONB->'worldStartLocationEvidence'->'request', '{versionStateEpoch}',to_jsonb(t.freeze_version_state_epoch::TEXT),FALSE) 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 35dc31b52f..99448bd122 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 @@ -18,6 +18,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @@ -33,10 +34,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.gamedesign.GameDesignPublicationTerminalClient; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Participant; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.ReleaseContent; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; @@ -46,6 +49,9 @@ 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.WorldPublicationTerminalCompletionGrpcCodec; +import net.firedevops.firemud.common.world.WorldPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.world.WorldPublicationTerminalReadGrpcCodec; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; @@ -59,6 +65,8 @@ import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; import net.firedevops.firemud.worldmanagement.v1.GenerationRuleDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublicationTerminalRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublicationTerminalResponse; import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; import net.firedevops.firemud.worldmanagement.v1.RoomExitDesignMutation; @@ -216,6 +224,76 @@ void releaseSelectorMaterializesItsOriginalRoomAndExactlyRetriesWithSeparateRunt assertOrigin(); } + @Test + void canonicalPreparationKeepsOriginalPublicationEpochForLaterReleaseResolution() { + Fixture f = fixture(); + var original = application(generationFreePlan(f)); + var selectedRoom = + original.plan().graph().nodes().stream() + .filter( + node -> + node.mutation().getAggregateType() + == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .map(node -> node.templateId()) + .toList() + .getLast(); + var applied = withStartRoom(original, selectedRoom); + appliedComponent().apply(applied); + var frozen = capture(applied.plan()); + var selector = + publishedEvidence( + publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + + long publicationEpoch = 2L; + var publicationInput = preparationInput(f, frozen, selector, publicationEpoch); + var originalTerminal = isolatedTerminalEvidence(publicationInput); + byte[] originalTerminalBytes = originalTerminal.canonicalBytes(); + assertThat(originalTerminal.publicationVersionStateEpoch()).isEqualTo(publicationEpoch); + assertThat(originalTerminal.worldEvidence().request().versionStateEpoch()) + .isEqualTo(selector.request().versionStateEpoch()); + publicationTerminalComponent(originalTerminal) + .complete(originalTerminal.operationBytes(), originalTerminalBytes); + UUID fence = selector.request().publicationFence(); + assertThat(publicationOwnerPhase(fence)).isEqualTo("PUBLISHED"); + assertThat(publicationTerminalBytes(fence)).containsExactly(originalTerminalBytes); + + var staleInput = preparationInput(f, frozen, selector, publicationEpoch - 1); + // These later descriptor epochs are isolated GD-resolution inputs: this proves World owner + // storage and binding only, not a live GD lifecycle/currentness or authorization producer. + var laterInput = preparationInput(f, frozen, selector, publicationEpoch + 1); + var changedReleaseInput = + preparationInput(f, frozen, selector, publicationEpoch + 1, List.of("LOOK", "CHANGED")); + var laterRelease = laterInput.completeLaunchBinding().evidence().releaseAttestation(); + assertThat(laterRelease.versionStateEpoch()).isEqualTo(publicationEpoch + 1); + assertThat(isolatedTerminalEvidence(laterInput).releaseContent().canonicalBytes()) + .containsExactly(originalTerminal.releaseContent().canonicalBytes()); + assertThat(isolatedTerminalEvidence(changedReleaseInput).releaseContent().canonicalBytes()) + .isNotEqualTo(originalTerminal.releaseContent().canonicalBytes()); + + var repository = preparationRepository(); + var service = preparationComponentWithRetainedTerminal(repository, originalTerminal); + assertThatThrownBy(() -> service.prepare(staleInput)) + .isInstanceOf( + WorldCanonicalInstancePreparationRepository.InvalidPreparationEvidenceException.class) + .hasMessageContaining("ReleaseContent differs"); + assertThatThrownBy(() -> service.prepare(changedReleaseInput)) + .isInstanceOf( + WorldCanonicalInstancePreparationRepository.InvalidPreparationEvidenceException.class) + .hasMessageContaining("ReleaseContent differs"); + assertThat(count(f, "world_instance")).isZero(); + + var prepared = service.prepare(laterInput); + assertThat(prepared.startLocation().roomTemplateId()).isEqualTo(selectedRoom); + assertThat(repository.readOwnerPreparation(laterInput)).contains(prepared); + assertThat(publicationOwnerPhase(fence)).isEqualTo("PUBLISHED"); + assertThat(publicationTerminalBytes(fence)).containsExactly(originalTerminalBytes); + assertThat( + WorldPublicationTerminal.request(publicationTerminalBytes(fence)) + .publicationVersionStateEpoch()) + .isEqualTo(publicationEpoch); + assertOrigin(); + } + @Test void publishedTerminalUsesExactOwnerEvidenceRetriesAndRejectsChangedReleaseContent() { Fixture f = fixture(); @@ -241,13 +319,250 @@ void publishedTerminalUsesExactOwnerEvidenceRetriesAndRejectsChangedReleaseConte assertThat(publicationOwnerPhase(fence)).isEqualTo("FROZEN"); byte[] originalTerminal = terminal.canonicalBytes(); - var service = publicationTerminalComponent(terminal); - assertThat(service.complete(terminal.operationBytes(), originalTerminal).canonicalBytes()) + var terminalRepository = new WorldPublicationTerminalRepository(dsl, manager); + var terminalReader = new WorldPublicationTerminalReadGrpcService(terminalRepository, NAMESPACE); + var readRequest = + WorldPublicationTerminalReadEvidence.Request.create(NAMESPACE, originalTerminal); + var wireReadRequest = WorldPublicationTerminalReadGrpcCodec.toRequest(readRequest); + + // Absence is an explicit UNKNOWN response; it is not evidence of abort or publication. + var unknown = readPublicationTerminalAs(terminalReader, wireReadRequest, NAMESPACE); + assertThat(unknown.error).isNull(); + assertThat(unknown.completed).isTrue(); + var unknownResult = + WorldPublicationTerminalReadGrpcCodec.fromResponse(readRequest, unknown.value); + assertThat(unknownResult.status()) + .isEqualTo(WorldPublicationTerminalReadEvidence.Status.UNKNOWN); + assertThat(unknownResult.terminalEvidence()).isEmpty(); + assertThat(unknownResult.request().canonicalBytes()) + .containsExactly(readRequest.canonicalBytes()); + + var missingOwnerTerminal = terminalWithWorldBinding(terminal, UUID.randomUUID(), null); + var missingOwnerRequest = + WorldPublicationTerminalReadEvidence.Request.create( + NAMESPACE, missingOwnerTerminal.canonicalBytes()); + var missingOwner = + readPublicationTerminalAs( + terminalReader, + WorldPublicationTerminalReadGrpcCodec.toRequest(missingOwnerRequest), + NAMESPACE); + assertThat(missingOwner.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + + String substitutedContentDigest = + selector.request().contentDigest().startsWith("f") ? "e".repeat(64) : "f".repeat(64); + var substitutedPendingTerminal = + terminalWithWorldBinding(terminal, null, substitutedContentDigest); + var substitutedPendingRequest = + WorldPublicationTerminalReadEvidence.Request.create( + NAMESPACE, substitutedPendingTerminal.canonicalBytes()); + var substitutedPending = + readPublicationTerminalAs( + terminalReader, + WorldPublicationTerminalReadGrpcCodec.toRequest(substitutedPendingRequest), + NAMESPACE); + assertThat(substitutedPending.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + + // Deliberately model an impossible retained state to ensure a missing receipt cannot disguise + // a contradictory terminal owner phase as pending UNKNOWN. + dsl.execute( + "ALTER TABLE world_design_publication_fence_owner " + + "DISABLE TRIGGER trg_world_publication_owner_protect"); + try { + assertThat( + dsl.execute( + "UPDATE world_design_publication_fence_owner SET owner_freeze_phase='PUBLISHED' " + + "WHERE current_publication_fence=?", + fence)) + .isEqualTo(1); + var contradictoryPhase = + readPublicationTerminalAs(terminalReader, wireReadRequest, NAMESPACE); + assertThat(contradictoryPhase.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + } finally { + dsl.execute( + "UPDATE world_design_publication_fence_owner SET owner_freeze_phase='FROZEN' " + + "WHERE current_publication_fence=?", + fence); + dsl.execute( + "ALTER TABLE world_design_publication_fence_owner " + + "ENABLE TRIGGER trg_world_publication_owner_protect"); + } + assertThat(publicationOwnerPhase(fence)).isEqualTo("FROZEN"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_design_publication_terminal " + + "WHERE publication_fence=?", + fence)) + .get(0, Long.class)) + .isZero(); + + var wrongPeer = + readPublicationTerminalAs( + terminalReader, wireReadRequest, "game-design-service", NAMESPACE); + var wrongNamespacePeer = + readPublicationTerminalAs(terminalReader, wireReadRequest, "account-service", "other"); + assertThat(wrongPeer.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongNamespacePeer.error).isEqualTo(Status.Code.PERMISSION_DENIED); + + new TransactionTemplate(manager) + .execute( + status -> { + assertThatThrownBy( + () -> + terminalRepository.readCommitted( + WorldPublicationTerminal.request(originalTerminal))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires no caller transaction"); + return null; + }); + + // The GD client double supplies isolated authenticated-owner evidence; this exercises the + // actual World owner transition, not the live GD producer or cross-service mTLS composition. + var completionRequest = + new WorldPublicationTerminalCompletionGrpcCodec.Request( + 1, NAMESPACE, terminal.operationBytes(), originalTerminal); + var completionService = + new WorldPublicationTerminalCompletionGrpcService( + terminalRepository, terminalReadClient(terminal), NAMESPACE); + var completionWireRequest = + WorldPublicationTerminalCompletionGrpcCodec.toRequest(completionRequest); + + var pendingClient = org.mockito.Mockito.mock(GameDesignPublicationTerminalClient.class); + org.mockito.Mockito.when(pendingClient.read(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> + new GameDesignPublicationTerminalReadEvidence.ReadResult( + invocation.getArgument( + 0, GameDesignPublicationTerminalReadEvidence.ReadRequest.class), + GameDesignPublicationTerminalReadEvidence.Status.UNKNOWN, + Optional.empty())); + var pendingService = + new WorldPublicationTerminalCompletionGrpcService( + terminalRepository, pendingClient, NAMESPACE); + var pending = completePublicationTerminalAs(pendingService, completionWireRequest, NAMESPACE); + assertThat(pending.error).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(publicationOwnerPhase(fence)).isEqualTo("FROZEN"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_design_publication_terminal " + + "WHERE publication_fence=?", + fence)) + .get(0, Long.class)) + .isZero(); + + var unavailableClient = org.mockito.Mockito.mock(GameDesignPublicationTerminalClient.class); + org.mockito.Mockito.when(unavailableClient.read(org.mockito.ArgumentMatchers.any())) + .thenThrow(Status.UNAVAILABLE.asRuntimeException()); + var unavailableService = + new WorldPublicationTerminalCompletionGrpcService( + terminalRepository, unavailableClient, NAMESPACE); + var unavailable = + completePublicationTerminalAs(unavailableService, completionWireRequest, NAMESPACE); + assertThat(unavailable.error).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(publicationOwnerPhase(fence)).isEqualTo("FROZEN"); + + for (Status permanentFailure : + List.of(Status.FAILED_PRECONDITION, Status.UNAUTHENTICATED, Status.PERMISSION_DENIED)) { + var permanentClient = org.mockito.Mockito.mock(GameDesignPublicationTerminalClient.class); + org.mockito.Mockito.when(permanentClient.read(org.mockito.ArgumentMatchers.any())) + .thenThrow(permanentFailure.asRuntimeException()); + var permanentService = + new WorldPublicationTerminalCompletionGrpcService( + terminalRepository, permanentClient, NAMESPACE); + var permanent = + completePublicationTerminalAs(permanentService, completionWireRequest, NAMESPACE); + assertThat(permanent.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(publicationOwnerPhase(fence)).isEqualTo("FROZEN"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_design_publication_terminal " + + "WHERE publication_fence=?", + fence)) + .get(0, Long.class)) + .isZero(); + } + + var invalidEvidenceClient = org.mockito.Mockito.mock(GameDesignPublicationTerminalClient.class); + org.mockito.Mockito.when(invalidEvidenceClient.read(org.mockito.ArgumentMatchers.any())) + .thenThrow(new IllegalStateException("invalid authenticated response")); + var invalidEvidenceService = + new WorldPublicationTerminalCompletionGrpcService( + terminalRepository, invalidEvidenceClient, NAMESPACE); + var invalidEvidence = + completePublicationTerminalAs(invalidEvidenceService, completionWireRequest, NAMESPACE); + assertThat(invalidEvidence.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(publicationOwnerPhase(fence)).isEqualTo("FROZEN"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_design_publication_terminal " + + "WHERE publication_fence=?", + fence)) + .get(0, Long.class)) + .isZero(); + + var missingResponseClient = org.mockito.Mockito.mock(GameDesignPublicationTerminalClient.class); + org.mockito.Mockito.when(missingResponseClient.read(org.mockito.ArgumentMatchers.any())) + .thenReturn(null); + var missingResponseService = + new WorldPublicationTerminalCompletionGrpcService( + terminalRepository, missingResponseClient, NAMESPACE); + var missingResponse = + completePublicationTerminalAs(missingResponseService, completionWireRequest, NAMESPACE); + assertThat(missingResponse.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(publicationOwnerPhase(fence)).isEqualTo("FROZEN"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_design_publication_terminal " + + "WHERE publication_fence=?", + fence)) + .get(0, Long.class)) + .isZero(); + + var completion = + completePublicationTerminalAs(completionService, completionWireRequest, NAMESPACE); + assertThat(completion.error).isNull(); + assertThat(completion.completed).isTrue(); + var completionResult = + WorldPublicationTerminalCompletionGrpcCodec.fromResponse( + completionRequest, completion.value); + assertThat(completionResult.request().canonicalBytes()) + .containsExactly(completionRequest.canonicalBytes()); + assertThat(completionResult.terminalEvidence().canonicalBytes()) .containsExactly(originalTerminal); assertThat(publicationOwnerPhase(fence)).isEqualTo("PUBLISHED"); assertThat(publicationTerminalBytes(fence)).containsExactly(originalTerminal); - assertThat(service.complete(terminal.operationBytes(), originalTerminal).canonicalBytes()) + + // The handler returns only the exact terminal bytes atomically retained with World PUBLISHED. + var committedRead = readPublicationTerminalAs(terminalReader, wireReadRequest, NAMESPACE); + assertThat(committedRead.error).isNull(); + assertThat(committedRead.completed).isTrue(); + var committedResult = + WorldPublicationTerminalReadGrpcCodec.fromResponse(readRequest, committedRead.value); + assertThat(committedResult.status()) + .isEqualTo(WorldPublicationTerminalReadEvidence.Status.PUBLISHED); + assertThat(committedResult.terminalEvidence()).isPresent(); + assertThat(committedResult.terminalEvidence().orElseThrow().canonicalBytes()) .containsExactly(originalTerminal); + assertThat(committedResult.request().canonicalBytes()) + .containsExactly(readRequest.canonicalBytes()); + + var retriedCompletion = + completePublicationTerminalAs(completionService, completionWireRequest, NAMESPACE); + assertThat(retriedCompletion.error).isNull(); + assertThat( + WorldPublicationTerminalCompletionGrpcCodec.fromResponse( + completionRequest, retriedCompletion.value) + .canonicalBytes()) + .containsExactly(completionResult.canonicalBytes()); + var retryRead = readPublicationTerminalAs(terminalReader, wireReadRequest, NAMESPACE); + assertThat( + WorldPublicationTerminalReadGrpcCodec.fromResponse(readRequest, retryRead.value) + .canonicalBytes()) + .containsExactly(committedResult.canonicalBytes()); var bundle = terminal.releaseContent(); var changedBundle = @@ -272,6 +587,28 @@ void publishedTerminalUsesExactOwnerEvidenceRetriesAndRejectsChangedReleaseConte Outcome.PUBLISHED, changedBundle, terminal.publicationVersionStateEpoch()); + var changedCompletionRequest = + new WorldPublicationTerminalCompletionGrpcCodec.Request( + 1, NAMESPACE, changedTerminal.operationBytes(), changedTerminal.canonicalBytes()); + var changedCompletionService = + new WorldPublicationTerminalCompletionGrpcService( + terminalRepository, terminalReadClient(terminal), NAMESPACE); + var changedCompletion = + completePublicationTerminalAs( + changedCompletionService, + WorldPublicationTerminalCompletionGrpcCodec.toRequest(changedCompletionRequest), + NAMESPACE); + assertThat(changedCompletion.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + var service = publicationTerminalComponent(terminal); + var changedReadRequest = + WorldPublicationTerminalReadEvidence.Request.create( + NAMESPACE, changedTerminal.canonicalBytes()); + var changedRead = + readPublicationTerminalAs( + terminalReader, + WorldPublicationTerminalReadGrpcCodec.toRequest(changedReadRequest), + NAMESPACE); + assertThat(changedRead.error).isEqualTo(Status.Code.FAILED_PRECONDITION); assertThatThrownBy( () -> service.complete( @@ -360,20 +697,49 @@ void onlyPositiveNoPublicationEvidenceCanSealWorldAsAbortedAndCannotPrepare() { new GameDesignPublicationTerminalEvidence( published.operationBytes(), Outcome.NO_PUBLICATION, null, null); UUID fence = selector.request().publicationFence(); - var service = publicationTerminalComponent(noPublication); - byte[] result = - service - .complete(noPublication.operationBytes(), noPublication.canonicalBytes()) - .canonicalBytes(); + var terminalRepository = new WorldPublicationTerminalRepository(dsl, manager); + var completionRequest = + new WorldPublicationTerminalCompletionGrpcCodec.Request( + 1, NAMESPACE, noPublication.operationBytes(), noPublication.canonicalBytes()); + var completionService = + new WorldPublicationTerminalCompletionGrpcService( + terminalRepository, terminalReadClient(noPublication), NAMESPACE); + var wireCompletionRequest = + WorldPublicationTerminalCompletionGrpcCodec.toRequest(completionRequest); + var completion = + completePublicationTerminalAs(completionService, wireCompletionRequest, NAMESPACE); + assertThat(completion.error).isNull(); + assertThat(completion.completed).isTrue(); + var completionResult = + WorldPublicationTerminalCompletionGrpcCodec.fromResponse( + completionRequest, completion.value); + byte[] result = completionResult.terminalEvidence().canonicalBytes(); assertThat(result).containsExactly(noPublication.canonicalBytes()); assertThat(publicationOwnerPhase(fence)).isEqualTo("ABORTED"); + var retry = completePublicationTerminalAs(completionService, wireCompletionRequest, NAMESPACE); + assertThat(retry.error).isNull(); assertThat( - service - .complete(noPublication.operationBytes(), noPublication.canonicalBytes()) + WorldPublicationTerminalCompletionGrpcCodec.fromResponse(completionRequest, retry.value) .canonicalBytes()) - .containsExactly(result); + .containsExactly(completionResult.canonicalBytes()); assertThat(publicationTerminalBytes(fence)).containsExactly(result); + var abortReadRequest = WorldPublicationTerminalReadEvidence.Request.create(NAMESPACE, result); + var abortRead = + readPublicationTerminalAs( + new WorldPublicationTerminalReadGrpcService( + new WorldPublicationTerminalRepository(dsl, manager), NAMESPACE), + WorldPublicationTerminalReadGrpcCodec.toRequest(abortReadRequest), + NAMESPACE); + assertThat(abortRead.error).isNull(); + var abortReadResult = + WorldPublicationTerminalReadGrpcCodec.fromResponse(abortReadRequest, abortRead.value); + assertThat(abortReadResult.status()) + .isEqualTo(WorldPublicationTerminalReadEvidence.Status.ABORTED); + assertThat(abortReadResult.terminalEvidence()).isPresent(); + assertThat(abortReadResult.terminalEvidence().orElseThrow().canonicalBytes()) + .containsExactly(result); + assertThatThrownBy(() -> preparationComponent(preparationRepository()).prepare(input)) .isInstanceOf( WorldPublicationTerminalRepository.PublicationTerminalConflictException.class); @@ -1423,6 +1789,23 @@ private WorldCanonicalInstancePreparation.Input preparationInput( Fixture f, WorldCanonicalFrozenTopology frozen, WorldPublishedStartLocationEvidence selector) { + return preparationInput(f, frozen, selector, 2L, List.of("LOOK")); + } + + private WorldCanonicalInstancePreparation.Input preparationInput( + Fixture f, + WorldCanonicalFrozenTopology frozen, + WorldPublishedStartLocationEvidence selector, + long descriptorVersionStateEpoch) { + return preparationInput(f, frozen, selector, descriptorVersionStateEpoch, List.of("LOOK")); + } + + private WorldCanonicalInstancePreparation.Input preparationInput( + Fixture f, + WorldCanonicalFrozenTopology frozen, + WorldPublishedStartLocationEvidence selector, + long descriptorVersionStateEpoch, + List commandDefinitions) { var source = f.intake().source(); String control = "prepare-" + UUID.randomUUID(); var descriptor = @@ -1449,7 +1832,7 @@ private WorldCanonicalInstancePreparation.Input preparationInput( null, "{}", "generation-free", - 2L, + descriptorVersionStateEpoch, 97L, "release-" + frozen.request().freeze().publicationRequestId(), false, @@ -1491,7 +1874,7 @@ private WorldCanonicalInstancePreparation.Input preparationInput( 1, List.of(), List.of(), - List.of("LOOK"), + commandDefinitions, descriptor.generationConfigRevision()) : AuthoredWorldReleaseAttestationEvidence.create( NAMESPACE, @@ -1511,7 +1894,7 @@ private WorldCanonicalInstancePreparation.Input preparationInput( 1, List.of(), List.of(), - List.of("LOOK"), + commandDefinitions, descriptor.generationConfigRevision(), selector); var evidence = new CompleteLaunchBindingEvidence(descriptor, release); @@ -1652,6 +2035,42 @@ public void close() { }); } + /** + * Isolated fixture verifier that preserves and independently reads an already committed V44 + * terminal instead of trying to reseal it from a later descriptor resolution. + */ + private WorldCanonicalInstancePreparationService preparationComponentWithRetainedTerminal( + WorldCanonicalInstancePreparationRepository repository, + GameDesignPublicationTerminalEvidence originalTerminal) { + byte[] expectedTerminal = originalTerminal.canonicalBytes(); + return new WorldCanonicalInstancePreparationService( + repository, + input -> { + var retained = + new WorldPublicationTerminalRepository(dsl, manager) + .readCommitted(WorldPublicationTerminal.request(expectedTerminal)) + .orElseThrow( + () -> + new IllegalStateException( + "isolated fixture lost its previously committed World terminal")); + if (!java.util.Arrays.equals(expectedTerminal, retained.canonicalBytes())) { + throw new IllegalStateException( + "isolated fixture World terminal differs from original publication result"); + } + return new WorldCanonicalInstancePreparationService.HeldCommitAuthority() { + private boolean open = true; + + public void requireHeld() { + if (!open) throw new IllegalStateException("closed fixture authority"); + } + + public void close() { + open = false; + } + }; + }); + } + private GameDesignPublicationTerminalEvidence isolatedTerminalEvidence( WorldCanonicalInstancePreparation.Input input) { var release = input.completeLaunchBinding().evidence().releaseAttestation(); @@ -1724,6 +2143,78 @@ private GameDesignPublicationTerminalEvidence isolatedTerminalEvidence( operation.canonicalBytes(), Outcome.PUBLISHED, content, release.versionStateEpoch()); } + private static GameDesignPublicationTerminalEvidence terminalWithWorldBinding( + GameDesignPublicationTerminalEvidence terminal, UUID publicationFence, String contentDigest) { + if (terminal.outcome() != Outcome.PUBLISHED) { + throw new IllegalArgumentException("Published terminal fixture required"); + } + var originalWorld = terminal.worldEvidence(); + var originalRequest = originalWorld.request(); + var request = + new WorldPublishedStartLocationEvidence.Request( + originalRequest.targetNamespace(), + originalRequest.canonicalTenantId(), + originalRequest.canonicalVersionId(), + originalRequest.intakeRequestId(), + publicationFence == null ? originalRequest.publicationFence() : publicationFence, + originalRequest.publicationRequestId(), + originalRequest.requestDigest(), + originalRequest.versionStateEpoch(), + originalRequest.publishWorkflowId(), + originalRequest.appliedCommitId(), + contentDigest == null ? originalRequest.contentDigest() : contentDigest, + originalRequest.digestSchemaVersion(), + originalRequest.worldAffectedTuples()); + var world = + new WorldPublishedStartLocationEvidence( + request, + originalWorld.selectorReceiptBytes(), + originalWorld.originalAccountBindingBytes(), + originalWorld.appliedResultBytes()); + var originalOperation = + GameDesignPublicationOperationBinding.fromStored(terminal.operationBytes()); + var operation = new GameDesignPublicationOperationBinding(originalOperation.account(), world); + ReleaseContent originalContent = terminal.releaseContent(); + var participants = + originalContent.participantDigests().stream() + .map( + participant -> + "WORLD_MANAGEMENT".equals(participant.participantKey()) + ? new Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId(), + participant.appliedCommitId(), + request.contentDigest(), + participant.digestSchemaVersion(), + participant.abilitySchemaDigest(), + participant.errorCode(), + participant.errorMessage()) + : participant) + .toList(); + var content = + new ReleaseContent( + originalContent.canonicalTenantId(), + originalContent.canonicalVersionId(), + originalContent.publishedReleaseBundleRef(), + originalContent.versionNumber(), + originalContent.attestationSchemaVersion(), + originalContent.publishWorkflowId(), + originalContent.manifestHash(), + originalContent.manifestSchemaVersion(), + originalContent.artifactDigests(), + originalContent.requiredManifestAssetKeys(), + participants, + originalContent.commandDefinitions(), + originalContent.generationConfigRevision(), + world); + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + Outcome.PUBLISHED, + content, + terminal.publicationVersionStateEpoch()); + } + private void completeIsolatedPublicationTerminal(WorldCanonicalInstancePreparation.Input input) { var evidence = isolatedTerminalEvidence(input); publicationTerminalComponent(evidence) @@ -1751,6 +2242,25 @@ public void close() {} }); } + private GameDesignPublicationTerminalClient terminalReadClient( + GameDesignPublicationTerminalEvidence evidence) { + var client = org.mockito.Mockito.mock(GameDesignPublicationTerminalClient.class); + org.mockito.Mockito.when(client.read(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + var request = + invocation.getArgument( + 0, GameDesignPublicationTerminalReadEvidence.ReadRequest.class); + var status = + evidence.outcome() == Outcome.PUBLISHED + ? GameDesignPublicationTerminalReadEvidence.Status.PUBLISHED + : GameDesignPublicationTerminalReadEvidence.Status.NO_PUBLICATION; + return new GameDesignPublicationTerminalReadEvidence.ReadResult( + request, status, Optional.of(evidence)); + }); + return client; + } + private AuthoredDraftPublishSelectionBinding publicationSelection( WorldDraftTopologyCommitPlan plan, String publicationRequest, long freezeEpoch) { var binding = plan.binding(); @@ -3633,6 +4143,106 @@ private static void await(CountDownLatch latch) { } } + private static TerminalReadCollector readPublicationTerminalAs( + WorldPublicationTerminalReadGrpcService service, + ReadWorldPublicationTerminalRequest request, + String peerNamespace) { + return readPublicationTerminalAs(service, request, "account-service", peerNamespace); + } + + private static TerminalReadCollector readPublicationTerminalAs( + WorldPublicationTerminalReadGrpcService service, + ReadWorldPublicationTerminalRequest request, + String peerService, + String peerNamespace) { + TerminalReadCollector response = new TerminalReadCollector(); + Context context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + peerNamespace + "/sa/" + peerService, + peerNamespace, + peerService)); + Context previous = context.attach(); + try { + service.readWorldPublicationTerminal(request, response); + } finally { + context.detach(previous); + } + return response; + } + + private static TerminalCompletionCollector completePublicationTerminalAs( + WorldPublicationTerminalCompletionGrpcService service, + net.firedevops.firemud.worldmanagement.v1.CompleteWorldPublicationTerminalRequest request, + String peerNamespace) { + TerminalCompletionCollector response = new TerminalCompletionCollector(); + Context context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + peerNamespace + "/sa/game-design-service", + peerNamespace, + "game-design-service")); + Context previous = context.attach(); + try { + service.completeWorldPublicationTerminal(request, response); + } finally { + context.detach(previous); + } + return response; + } + + private static final class TerminalReadCollector + implements StreamObserver { + private ReadWorldPublicationTerminalResponse value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(ReadWorldPublicationTerminalResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } + + private static final class TerminalCompletionCollector + implements StreamObserver< + net.firedevops.firemud.worldmanagement.v1.CompleteWorldPublicationTerminalResponse> { + private net.firedevops.firemud.worldmanagement.v1.CompleteWorldPublicationTerminalResponse + value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext( + net.firedevops.firemud.worldmanagement.v1.CompleteWorldPublicationTerminalResponse + response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } + private static final class LifecycleReadCollector implements StreamObserver< net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse> { diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalCompletionGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalCompletionGrpcServiceTest.java new file mode 100644 index 0000000000..30de40c7a5 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalCompletionGrpcServiceTest.java @@ -0,0 +1,136 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +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 net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalCompletionGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalRepository; +import net.firedevops.firemud.worldmanagement.v1.CompleteWorldPublicationTerminalRequest; +import net.firedevops.firemud.worldmanagement.v1.CompleteWorldPublicationTerminalResponse; +import org.junit.jupiter.api.Test; + +class WorldPublicationTerminalCompletionGrpcServiceTest { + @Test + void rejectsWrongOrMissingGameDesignPeerBeforeDecodeClientOrOwnerStorage() { + var repository = mock(WorldPublicationTerminalRepository.class); + var client = mock(GameDesignPublicationTerminalClient.class); + var service = new WorldPublicationTerminalCompletionGrpcService(repository, client, "test"); + var malformed = + CompleteWorldPublicationTerminalRequest.newBuilder() + .setCanonicalRequestBytes(ByteString.copyFromUtf8("malformed")) + .build(); + + Collector missing = call(service, malformed, null); + Collector wrongService = call(service, malformed, peer("account-service", "test")); + Collector wrongNamespace = call(service, malformed, peer("game-design-service", "other")); + + assertThat(missing.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongService.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(client, repository); + } + + @Test + void rejectsAuthenticatedEndUserBeforeDecodeClientOrOwnerStorage() { + var repository = mock(WorldPublicationTerminalRepository.class); + var client = mock(GameDesignPublicationTerminalClient.class); + var service = new WorldPublicationTerminalCompletionGrpcService(repository, client, "test"); + SessionContext.setContext("11111111-1111-4111-8111-111111111111", List.of(), Map.of()); + Collector result; + try { + result = + call( + service, + CompleteWorldPublicationTerminalRequest.getDefaultInstance(), + peer("game-design-service", "test")); + } finally { + SessionContext.clear(); + } + + assertThat(result.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(client, repository); + } + + @Test + void malformedRequestFromExactPeerFailsBeforeClientOrOwnerStorage() { + var repository = mock(WorldPublicationTerminalRepository.class); + var client = mock(GameDesignPublicationTerminalClient.class); + var service = new WorldPublicationTerminalCompletionGrpcService(repository, client, "test"); + var malformed = + CompleteWorldPublicationTerminalRequest.newBuilder() + .setCanonicalRequestBytes(ByteString.copyFromUtf8("malformed")) + .build(); + + Collector result = call(service, malformed, peer("game-design-service", "test")); + + assertThat(result.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(client, repository); + } + + @Test + void invalidConfiguredNamespaceIsRejected() { + var repository = mock(WorldPublicationTerminalRepository.class); + var client = mock(GameDesignPublicationTerminalClient.class); + + assertThatThrownBy( + () -> new WorldPublicationTerminalCompletionGrpcService(repository, client, "bad ns")) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(client, repository); + } + + private static Collector call( + WorldPublicationTerminalCompletionGrpcService service, + CompleteWorldPublicationTerminalRequest request, + GrpcPeerIdentity peer) { + Collector response = new Collector(); + Context context = Context.current(); + if (peer != null) context = context.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + service.completeWorldPublicationTerminal(request, response); + } finally { + context.detach(previous); + } + return response; + } + + 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 CompleteWorldPublicationTerminalResponse value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(CompleteWorldPublicationTerminalResponse 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/WorldPublicationTerminalReadGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadGrpcServiceTest.java new file mode 100644 index 0000000000..84188058e5 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadGrpcServiceTest.java @@ -0,0 +1,130 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +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 net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalReadGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalRepository; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublicationTerminalRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublicationTerminalResponse; +import org.junit.jupiter.api.Test; + +class WorldPublicationTerminalReadGrpcServiceTest { + @Test + void rejectsWrongOrMissingAccountPeerBeforeDecodingOrOwnerRead() { + var repository = mock(WorldPublicationTerminalRepository.class); + var service = new WorldPublicationTerminalReadGrpcService(repository, "test"); + var malformed = + ReadWorldPublicationTerminalRequest.newBuilder() + .setCanonicalRequestBytes(ByteString.copyFromUtf8("malformed")) + .build(); + + Collector missing = call(service, malformed, null); + Collector wrongService = call(service, malformed, peer("game-design-service", "test")); + Collector wrongNamespace = call(service, malformed, peer("account-service", "other")); + + assertThat(missing.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongService.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void rejectsAuthenticatedEndUserBeforeDecodingOrOwnerRead() { + var repository = mock(WorldPublicationTerminalRepository.class); + var service = new WorldPublicationTerminalReadGrpcService(repository, "test"); + SessionContext.setContext("11111111-1111-4111-8111-111111111111", List.of(), Map.of()); + Collector result; + try { + result = + call( + service, + ReadWorldPublicationTerminalRequest.getDefaultInstance(), + peer("account-service", "test")); + } finally { + SessionContext.clear(); + } + + assertThat(result.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void malformedRequestFromExactAccountPeerFailsBeforeOwnerRead() { + var repository = mock(WorldPublicationTerminalRepository.class); + var service = new WorldPublicationTerminalReadGrpcService(repository, "test"); + var malformed = + ReadWorldPublicationTerminalRequest.newBuilder() + .setCanonicalRequestBytes(ByteString.copyFromUtf8("malformed")) + .build(); + + Collector result = call(service, malformed, peer("account-service", "test")); + + assertThat(result.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(repository); + } + + @Test + void invalidConfiguredNamespaceIsRejected() { + var repository = mock(WorldPublicationTerminalRepository.class); + + assertThatThrownBy(() -> new WorldPublicationTerminalReadGrpcService(repository, "bad ns")) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(repository); + } + + private static Collector call( + WorldPublicationTerminalReadGrpcService service, + ReadWorldPublicationTerminalRequest request, + GrpcPeerIdentity peer) { + Collector response = new Collector(); + Context context = Context.current(); + if (peer != null) context = context.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + service.readWorldPublicationTerminal(request, response); + } finally { + context.detach(previous); + } + return response; + } + + 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 ReadWorldPublicationTerminalResponse value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(ReadWorldPublicationTerminalResponse 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; + } + } +} From f8ae1ad8d493cffdbb96a8a692f35e109582043b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 08:40:07 +1300 Subject: [PATCH 05/12] docs: distinguish terminal component proof from live publication delivery --- .../game-authoring-publishing-and-activation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 cb2c20d908..5a404c64b4 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 current local terminal-settlement candidate adds an unregistered Account reconciler and V80 immutable owner-result storage. It independently obtains exact definitive Game Design and World results outside Account transactions, requires their complete terminal bytes and outcome to match, then retains both immutable owner results before settling the original source fence in a short transaction. The source-lock ordering is aligned across result retention and source transitions. World now has unregistered, default-denied authenticated completion and Account read adapters: completion authenticates the exact same-namespace Game Design workload, rereads Game Design's sealed result, then commits the matching World `PUBLISHED`/`ABORTED` terminal through the existing owner transaction; the separate read adapter returns exact retained World evidence to Account. These candidates do not supply the current original publication-authorizing creator producer or separate lifecycle/serving authority, and no component is registered. All new definitions and validation are pending the parent gate; local Docker is unavailable, upstream inputs in World PostgreSQL definitions are isolated/mocked, and transport tests use a server double. No live publication, production readiness, or activation proof follows. A retained original publication epoch may precede a later launch-resolution epoch while the exact immutable release content remains bound. +The terminal-settlement candidate adds an unregistered Account reconciler and V80 immutable owner-result storage. It independently obtains exact definitive Game Design and World results outside Account transactions, requires their complete terminal bytes and outcome to match, then retains both immutable owner results before settling the original source fence in a short transaction. The source-lock ordering is aligned across result retention and source transitions. World now has unregistered, default-denied authenticated completion and Account read adapters: completion authenticates the exact same-namespace Game Design workload, rereads Game Design's sealed result, then commits the matching World `PUBLISHED`/`ABORTED` terminal through the existing owner transaction; the separate read adapter returns exact retained World evidence to Account. These candidates do not supply the current original publication-authorizing creator producer or separate lifecycle/serving authority, and no component is registered. Component unit, consumer-double and transport checks do not establish executed owner-database or cross-owner composition proof: local Docker is unavailable, upstream inputs in World PostgreSQL definitions are isolated/mocked, and transport tests use a server double. Corrected-state PostgreSQL execution and the complete authenticated producer/consumer composition remain required; exact checkpoint validation is recorded on #3035 and in FireController. No live publication, production readiness, or activation proof follows. A retained original publication epoch may precede a later launch-resolution epoch while the exact immutable release content remains bound. The #3035 terminal-read candidate adds a separate unregistered Game Design owner RPC and concrete reloading file-backed mTLS client for Account/World exact operation recovery. Closed request/response codecs preserve original operation and stored terminal bytes, explicit `UNKNOWN` is limited to absent/pending operations, and retained V50 terminal history without the captured extension fails precondition. Executed physical socket unit tests use an explicitly isolated owner double and are transport-only proof. Twelve PostgreSQL definitions include actual committed `PUBLISHED`/`NO_PUBLICATION` owner readback, absent/pending results, retained V50-to-V51 history without backfill, and physical mTLS against the actual owner service with exact lost-response recovery and wrong-peer rejection. Their upstream creator/source/World inputs remain explicitly isolated. Local component checks, proto generation, compilation, jOOQ and packaged builds pass; all 169 Game Design integration cases skip without Docker, including those twelve definitions. They are not executed PostgreSQL or live composition proof. The standalone components do not register or enable public publication, current creator authorization, runtime lifecycle/serving authority or activation. From fa3f3009456bd4ac2b4c2d0a1af667cc1cca227a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 11:46:05 +1300 Subject: [PATCH 06/12] fix: align publication owner proof with retained migrations and terminal epochs --- .../world-runtime-and-movement.md | 2 + ...orizationFencePostgresIntegrationTest.java | 98 +++- ...ationOperationPostgresIntegrationTest.java | 111 ++-- ...anonical_instance_activation_operation.sql | 4 +- ...nceAssociationPostgresIntegrationTest.java | 494 ++++++++++++++++-- ...aphApplicationPostgresIntegrationTest.java | 50 +- 6 files changed, 640 insertions(+), 119 deletions(-) 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 b2864e4c23..198606a529 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 +Exact #3035 source `db3d9487e555f94ae1124bdd1a095e098034f3a2` [CI37536968451](https://github.com/benhook1013/FireMUD/actions/runs/37536968451) executed 171 World integration cases and reported fourteen failures. These expose an owned V43 SQL reference to nonexistent association `version_id`, a fixture that constructs a new publication terminal at a later descriptor epoch, and six current association fixtures without V44's required original published v2 selector evidence. The correction must use the joined source-qualified Game Design version rather than a private World key, compare later immutable content without changing the original terminal, and preserve the current exact-PUBLISHED gate while updating its fixtures. Local schema generation or Docker-free skips cannot close these executed failures; corrected runner execution and genuine authenticated owner composition remain required. These failures do not authorize a compatibility fallback or any runtime activation. + The current local publication-handoff candidate adds unregistered, default-denied World completion and Account read adapters plus Account's two-owner terminal reconciliation. World completion authenticates the exact same-namespace Game Design workload, independently rereads Game Design's definitive terminal outside the World transaction, then commits the matching `PUBLISHED`/`ABORTED` terminal and owner phase atomically; the Account read adapter authenticates Account and independently returns exact retained World terminal evidence. Account reads Game Design and World outside its owner transaction, compares the complete original operation and terminal bytes, retains both immutable matching owner results, and only then settles the source fence under consistent source-lock ordering. V44 canonical preparation consumes that exact retained `PUBLISHED` terminal and original frozen capture. The components remain unregistered and default-denied; they do not supply the current original publication-authorizing creator producer or the distinct fresh lifecycle/serving authority needed for admission. New definitions and validation are pending the parent gate; local Docker is unavailable, upstream inputs in World PostgreSQL cases are isolated/mocked, and transport tests use a server double. This is not live publication, production readiness, or activation proof. The original publication epoch can precede a later launch-resolution epoch while retaining the exact immutable release content. The #3035 V44 World publication-terminal candidate adds an unregistered, default-denied owner operation with immutable exact-retry PUBLISHED/ABORTED readback. Its explicit verifier consumes the separate Game Design terminal read; the owner transaction checks and seals the original freeze, source, Account/APPLIED and selector evidence. The terminal receipt and matching original owner phase must commit together, and independent readback rechecks their complete binding. Fresh V35 preparation now requires that exact retained PUBLISHED terminal and original frozen capture rather than FROZEN alone; it does not capture new source after terminalization. New PostgreSQL definitions exercise the owner transitions and preparation using explicitly isolated upstream evidence. Local component checks, schema generation and packaged builds pass, but all 170 World integration cases skip without Docker. They are not executed proof of PostgreSQL constraints, the real Game Design producer, live mTLS/service composition, or production authorization. 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 index bf143232c5..0da16c1d77 100644 --- 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 @@ -993,27 +993,115 @@ void v79PublicationOrderAndWaitingSourceChangeSurviveV80WithoutInventedOwnerResu tx(context, () -> context.publication().reserve(binding)); tx(context, () -> context.publication().claimPublicationOrder(binding)); var change = change(binding); - assertThat(tx(context, () -> context.draft().requestSourceChange(change))).isFalse(); + + // V79 has no V80 owner-result table for the current repository settlement read. The failed + // request is not a historical retained source change, and its transaction must leave no rows. + assertThatThrownBy(() -> tx(context, () -> context.draft().requestSourceChange(change))) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("account_publication_authorization_owner_results"); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) + .isZero(); + assertThat( + context.dsl().fetchCount(DSL.table("account_draft_authorization_changed_scopes"))) + .isZero(); + var orderedBeforeHistory = tx(context, () -> context.publication().read(binding)); + assertThat(orderedBeforeHistory.ordering()).isEqualTo(Ordering.PUBLICATION_ORDER); + + // Seed a valid historical V79 WAITING journal through its existing owner tables. These bytes + // come from the exact source-change value and scopes; the SQL fixture does not claim owner + // authorization or publication settlement. + txRun( + context, + () -> { + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_changes" + + " (change_id, binding, status, requested_at)" + + " VALUES (?, ?, 'WAITING', TIMESTAMPTZ '2026-10-06 12:34:56+00')", + change.changeId(), + change.canonicalBytes()); + for (var source : change.sources()) { + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_changed_scopes" + + " (change_id, source_key) VALUES (?, ?)", + change.changeId(), + source.key()); + } + }); + + var retainedTables = + Map.of( + "account_draft_authorization_source_locks", + retainedRows(context, "account_draft_authorization_source_locks"), + "account_draft_authorization_source_changes", + retainedRows(context, "account_draft_authorization_source_changes"), + "account_draft_authorization_changed_scopes", + retainedRows(context, "account_draft_authorization_changed_scopes"), + "account_publication_authorization_fences", + retainedRows(context, "account_publication_authorization_fences"), + "account_publication_authorization_sources", + retainedRows(context, "account_publication_authorization_sources")); + var beforeChange = + context + .dsl() + .fetchOne( + "SELECT binding, status, requested_at, committed_at FROM" + + " account_draft_authorization_source_changes WHERE change_id = ?", + change.changeId()); + assertThat(beforeChange).isNotNull(); + assertThat(beforeChange.get("binding", byte[].class)).isEqualTo(change.canonicalBytes()); + assertThat(beforeChange.get("status", String.class)).isEqualTo("WAITING"); + assertThat( + context + .dsl() + .fetch( + "SELECT source_key FROM account_draft_authorization_changed_scopes" + + " WHERE change_id = ? ORDER BY source_key", + change.changeId()) + .getValues("source_key", String.class)) + .containsExactlyElementsOf(change.sources().stream().map(SourceEvidence::key).toList()); var before = tx(context, () -> context.publication().read(binding)); assertThat(before.ordering()).isEqualTo(Ordering.PUBLICATION_ORDER); - assertThat(tx(context, () -> context.draft().readSourceChange(change)).status()) - .isEqualTo("WAITING"); migrate(context.source(), "latest"); + for (var retainedTable : retainedTables.entrySet()) { + assertThat(retainedRows(context, retainedTable.getKey())) + .as("complete retained rows in %s", retainedTable.getKey()) + .isEqualTo(retainedTable.getValue()); + } + var after = tx(context, () -> context.publication().read(binding)); 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(tx(context, () -> context.draft().readSourceChange(change)).status()) - .isEqualTo("WAITING"); + var afterChange = tx(context, () -> context.draft().readSourceChange(change)); + assertThat(afterChange.binding()).isEqualTo(beforeChange.get("binding", byte[].class)); + assertThat(afterChange.status()).isEqualTo(beforeChange.get("status", String.class)); + assertThat(afterChange.requestedAt()) + .isEqualTo(beforeChange.get("requested_at", OffsetDateTime.class)); + assertThat(afterChange.committedAt()) + .isEqualTo(beforeChange.get("committed_at", OffsetDateTime.class)); assertThat( context.dsl().fetchCount(DSL.table("account_publication_authorization_owner_results"))) .isZero(); assertThat(tx(context, () -> context.draft().sourceMutationPermitted(change))).isFalse(); } + private static List retainedRows(Context context, String table) { + return context + .dsl() + .fetch( + "SELECT to_jsonb(retained)::text AS retained_row FROM " + + table + + " retained ORDER BY to_jsonb(retained)") + .getValues("retained_row", String.class); + } + private static AccountPublicationAuthorizationBinding binding() { var input = new AccountPublicationAuthorizationBinding.PreallocationInput( 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 12fe33e83d..3e450ad021 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 @@ -495,6 +495,7 @@ void authenticatedTerminalReadReturnsUnknownOnlyForAbsentOrPendingOperation() th void retainedV50TerminalReadFailsPreconditionWithoutBackfillingEvidenceOrEpoch() throws Exception { var fixture = fixture("50"); + assertThat(fixture.candidate()).isNull(); var op = fixture.operation(); var old = new ByteArrayOutputStream(); DraftAuthorizationFenceBinding.frame(old, "game-design-publication-owner-readback/v1"); @@ -1083,60 +1084,64 @@ private Fixture fixture(String migrationTarget) 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())); + ExportedAssetManifest readCandidate = null; + if (!"50".equals(migrationTarget)) { + 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); + readCandidate = + candidateService.readExportCandidate(game.getTenantId(), version.getVersionNumber()); + assertThat(committedCandidate).isEqualTo(requestedCandidate); + assertThat(readCandidate).isEqualTo(committedCandidate); + } 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, diff --git a/services/world-management-service/src/main/resources/db/migration/V43__canonical_instance_activation_operation.sql b/services/world-management-service/src/main/resources/db/migration/V43__canonical_instance_activation_operation.sql index 7ea2082cfe..cfa59140e2 100644 --- a/services/world-management-service/src/main/resources/db/migration/V43__canonical_instance_activation_operation.sql +++ b/services/world-management-service/src/main/resources/db/migration/V43__canonical_instance_activation_operation.sql @@ -178,7 +178,7 @@ BEGIN AND b.descriptor_result_digest=a.descriptor_result_digest AND b.release_attestation_digest=a.release_attestation_digest AND b.descriptor_json::JSONB->>'launchDescriptorId'=a.launch_descriptor_id - AND b.descriptor_json::JSONB->>'versionId'=a.version_id::TEXT + AND b.descriptor_json::JSONB->>'versionId'=v.game_design_version_id::TEXT AND b.descriptor_json::JSONB->>'gameTemplateId'=a.game_template_id::TEXT AND b.descriptor_json::JSONB->>'targetNamespace'=a.canonical_target_namespace AND b.descriptor_json::JSONB->>'canonicalTenantId'=a.canonical_tenant_id::TEXT @@ -232,7 +232,7 @@ BEGIN AND v.source_operation_id=a.source_operation_id AND v.source_evidence_digest=a.source_evidence_digest AND v.intake_receipt_digest=a.intake_receipt_digest - AND v.game_design_version_id=a.version_id + AND v.game_design_version_id::TEXT=b.descriptor_json::JSONB->>'versionId' AND v.version_state_epoch=a.version_state_epoch AND p.target_namespace=a.canonical_target_namespace AND p.canonical_tenant_id=a.canonical_tenant_id diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java index f4b9ba5e5b..19bb87599b 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java @@ -7,12 +7,16 @@ import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.util.JsonFormat; +import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; @@ -23,6 +27,7 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +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; @@ -30,8 +35,16 @@ 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.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Participant; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.ReleaseContent; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; 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; @@ -46,9 +59,12 @@ import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; import net.firedevops.firemud.worldmanagement.v1.RoomExitDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RoomTemplateRef; import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphDeclaration; +import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphFamilyCount; import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; @@ -76,12 +92,13 @@ * Focused PostgreSQL proof for guarded, immutable, non-authorizing canonical materialization and * World canonical-instance association. * - *

Upstream Game Design, Game Session, publication checkpoint, and held-authority evidence here - * is explicitly synthetic fixture evidence. World source intake, complete launch pair, Version - * identity, frozen graph, guarded V35 runtime materialization, association, migration, constraints, - * and independent committed readback use actual migrated PostgreSQL repositories and tables. This - * fixture does not claim authenticated producer/delivery evidence, Account commit authority, - * lifecycle transition success, actor authority, or gameplay admission. + *

Upstream Game Design and Game Session results, Account ordering, and held preparation + * authority remain explicitly isolated fixture evidence. World source intake, Version identity, + * APPLIED graph, frozen selector, PUBLISHED terminal storage, guarded runtime materialization, + * association, migration, constraints, and independent committed readback use actual migrated + * PostgreSQL repositories and tables. This fixture does not claim authenticated producer/delivery + * evidence, Account commit authority, lifecycle transition success, actor authority, or gameplay + * admission. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -587,7 +604,9 @@ void rejectsChangedRequestEchoDescriptorAttestationAndPlayableScopeWithoutMutati fixture.versionIdentity().canonicalVersionId(), VERSION_EPOCH, "substituted-descriptor", - "synthetic-alternate-descriptor"); + fixture.binding().evidence().releaseAttestation().commitId(), + Objects.requireNonNull( + fixture.binding().evidence().releaseAttestation().worldStartLocationEvidence())); UUID changedDescriptorReadId = UUID.randomUUID(); assertThatThrownBy( () -> @@ -610,7 +629,10 @@ void rejectsChangedRequestEchoDescriptorAttestationAndPlayableScopeWithoutMutati fixture.binding().descriptor(), fixture.source().source(), fixture.versionIdentity().canonicalVersionId(), - "synthetic-alternate-attestation"); + fixture.binding().evidence().releaseAttestation().commitId(), + Objects.requireNonNull( + fixture.binding().evidence().releaseAttestation().worldStartLocationEvidence()), + 'e'); CompleteLaunchBindingEvidence changedPair = new CompleteLaunchBindingEvidence(fixture.binding().descriptor(), changedAttestation); UUID changedAttestationReadId = UUID.randomUUID(); @@ -1160,7 +1182,12 @@ private Fixture fixture() { WorldAuthoredVersionIdentityReceipt identity = seedVersionIdentity(source, canonicalVersionId, gameDesignVersionId, VERSION_EPOCH); SeededPair pair = seedPair(source, identity, controlRequest(), "synthetic-launch-descriptor"); - return new Fixture(source, pair.binding(), pair.versionIdentity()); + Fixture fixture = new Fixture(source, pair.binding(), pair.versionIdentity()); + // Build and retain the original v2 publication terminal through World owner storage. Upstream + // Account and Game Design authority in this component fixture remains explicitly stipulated; + // STARTING is only the canonical storage-only Game Session observation carried by this input. + preparationInput(fixture, UUID.randomUUID(), UUID.randomUUID(), "STARTING", 1L); + return fixture; } private SourceFixture sourceFixture() { @@ -1197,10 +1224,15 @@ private SeededPair seedPair( identity == null ? seedVersionIdentity(source, canonicalVersionId, gameDesignVersionId, VERSION_EPOCH) : identity; - // The source and Draft authority remain synthetic, but this release's World checkpoint is - // taken from actual stored/frozen content rather than an unrelated fixture token or digest. - var frozen = frozenPlan(new Fixture(source, null, resolvedIdentity)); + // The source and Account authority remain synthetic, but the graph, frozen selector and + // immutable PUBLISHED terminal are written/read through the actual World owner stores. + Fixture sourceFixture = new Fixture(source, null, resolvedIdentity); + var frozen = frozenPlan(sourceFixture); var checkpoint = frozen.sourceBinding().freeze(); + var selector = + publishedEvidence( + publishedSelectors().readCommitted(checkpoint).orElseThrow( + () -> new IllegalStateException("Synthetic APPLIED-v2 selector was not retained"))); CompleteLaunchBindingEvidence evidence = completeEvidence( source.source(), @@ -1209,7 +1241,8 @@ private SeededPair seedPair( canonicalVersionId, VERSION_EPOCH, launchDescriptorId, - checkpoint.appliedCommitId()); + checkpoint.appliedCommitId(), + selector); evidence = new CompleteLaunchBindingEvidence( evidence.descriptor(), @@ -1302,8 +1335,11 @@ private WorldCanonicalInstancePreparation.Input preparationInput( request.readRequestId(), observedGameSessionStatus, observedGameSessionRowVersion); - return new WorldCanonicalInstancePreparation.Input( - request, response, fixture.binding(), fixture.versionIdentity(), frozenPlan(fixture)); + WorldCanonicalInstancePreparation.Input input = + new WorldCanonicalInstancePreparation.Input( + request, response, fixture.binding(), fixture.versionIdentity(), frozenPlan(fixture)); + completeIsolatedPublicationTerminal(input); + return input; } private WorldCanonicalInstancePreparationService preparationService(Runnable heldCheck) { @@ -1337,15 +1373,18 @@ private WorldCanonicalInstanceTopologyPlan frozenPlan(Fixture fixture) { fixture.versionIdentity().operationId(), ignored -> { WorldDraftTopologyCommitPlan draft = topologyPlan(fixture); - new WorldDraftTopologyCommitService( - new WorldDraftTopologyCommitRepository(dsl, publicationFence, objectMapper), - transactionManager, - plan -> { - // Synthetic local storage permission only; no Account or Entity proof. - }) - .store(draft); + appliedComponent().apply(draftApplication(draft)); var owner = draft.ownerBinding(); String publicationRequest = "preparation-capture-" + UUID.randomUUID(); + // V27/release evidence retains the post-publication epoch; the original Draft freeze + // selection is exactly the preceding epoch. + long freezeEpoch = + Math.subtractExact( + fixture.versionIdentity().versionStateEvidence().versionStateEpoch(), 1L); + String requestDigest = + publicationSelection(draft, publicationRequest, freezeEpoch) + .digest() + .substring("sha256:".length()); WorldDesignPublicationFenceEvidence evidence = new WorldDesignPublicationFenceEvidence( owner.targetNamespace(), @@ -1360,8 +1399,8 @@ private WorldCanonicalInstanceTopologyPlan frozenPlan(Fixture fixture) { owner.sourceEvidenceDigest(), owner.intakeReceiptDigest(), publicationRequest, - "a".repeat(64), - fixture.versionIdentity().versionStateEvidence().versionStateEpoch(), + requestDigest, + freezeEpoch, "publish:" + owner.canonicalTenantId() + ":publish-request:" @@ -1414,27 +1453,265 @@ private WorldCanonicalInstanceTopologyPlan frozenPlan(Fixture fixture) { attempt.checkpoint().digestSchemaVersion(), tuples); WorldCanonicalFrozenTopology frozen = - new WorldCanonicalFrozenTopologyService( - new WorldCanonicalFrozenTopologyRepository( - dsl, - graphSnapshots, - new WorldDraftTopologyCommitRepository( - dsl, publicationFence, objectMapper), - digestService), - transactionManager) + new WorldCanonicalFrozenTopologyService(frozenRepository(), transactionManager) .capture(new WorldCanonicalFrozenTopology.Request(draft, captureRequest)); return WorldCanonicalInstanceTopologyPlan.create(frozen); }); } + private WorldDraftGraphApplicationRepository appliedRepository() { + return new WorldDraftGraphApplicationRepository(dsl, publicationFence, objectMapper); + } + + private WorldDraftGraphApplicationService appliedComponent() { + return new WorldDraftGraphApplicationService( + appliedRepository(), + transactionManager, + operation -> { + // Explicitly isolated Account COMMIT_ORDER authority; this is not producer proof. + return new WorldDraftGraphApplicationService.CommitOrderProof(operation); + }); + } + + private WorldDraftGraphApplication draftApplication(WorldDraftTopologyCommitPlan plan) { + var binding = plan.binding(); + var account = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + binding.requestId(), + binding.commitId(), + UUID.randomUUID(), + UUID.randomUUID(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.baseCommitId(), + "0", + binding.canonicalBytes(), + binding.canonicalBytes(), + binding.digest(), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.TENANT, + binding.target().canonicalTenantId().toString(), + null, + "1", + null, + null, + new byte[] {1, 2, 3}))); + var operation = + new WorldDraftTerminalOperation( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId(), + binding, + plan.ownerBinding(), + account.canonicalBytes()); + return new WorldDraftGraphApplication(operation, plan); + } + + private WorldCanonicalFrozenTopologyRepository frozenRepository() { + return new WorldCanonicalFrozenTopologyRepository( + dsl, + graphSnapshots, + new WorldDraftTopologyCommitRepository(dsl, publicationFence, objectMapper), + digestService); + } + + private WorldPublishedStartLocationRepository publishedSelectors() { + return new WorldPublishedStartLocationRepository(dsl, frozenRepository(), appliedRepository()); + } + + 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 AuthoredDraftPublishSelectionBinding publicationSelection( + WorldDraftTopologyCommitPlan plan, String publicationRequest, long freezeEpoch) { + var binding = plan.binding(); + var intent = + new AuthoredDraftPublishSelectionBinding.PublishIntent( + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + publicationRequest, + Long.toString(freezeEpoch), + "isolated-association-publication-fixture", + binding.requestId(), + binding.commitId(), + binding.digest()); + return AuthoredDraftPublishSelectionBinding.capture( + intent, + binding.target(), + binding, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + binding.target(), + binding.requestId(), + binding.commitId(), + binding.digest(), + "[]", + OffsetDateTime.parse("2026-01-01T00:00:00Z"))); + } + + private GameDesignPublicationTerminalEvidence isolatedTerminalEvidence( + WorldCanonicalInstancePreparation.Input input) { + var release = input.completeLaunchBinding().evidence().releaseAttestation(); + var world = Objects.requireNonNull(release.worldStartLocationEvidence()); + if (release.versionStateEpoch() + != Math.addExact(world.request().versionStateEpoch(), 1L)) { + throw new IllegalStateException( + "Isolated PUBLISHED terminal must retain the next publication epoch after its World freeze"); + } + var originalAccount = + DraftAuthorizationFenceBinding.fromStored(world.originalAccountBindingBytes()); + var selection = + publicationSelection( + input.topologyPlan().sourceBinding().plan(), + world.request().publicationRequestId(), + world.request().versionStateEpoch()); + if (!selection.digest().equals("sha256:" + world.request().requestDigest())) { + throw new IllegalStateException( + "Isolated publication selection differs from the retained World request digest"); + } + var account = + new AccountPublicationAuthorizationBinding( + UUID.nameUUIDFromBytes( + (world.request().publicationFence() + "/account-operation") + .getBytes(StandardCharsets.UTF_8)), + UUID.nameUUIDFromBytes( + (world.request().publicationFence() + "/account-fence") + .getBytes(StandardCharsets.UTF_8)), + new AccountPublicationAuthorizationBinding.PreallocationInput( + originalAccount.actorAccountId(), selection), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + originalAccount.actorAccountId().toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + var operation = new GameDesignPublicationOperationBinding(account, world); + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + Outcome.PUBLISHED, + isolatedReleaseContent(input), + release.versionStateEpoch()); + } + + private ReleaseContent isolatedReleaseContent( + WorldCanonicalInstancePreparation.Input input) { + var release = input.completeLaunchBinding().evidence().releaseAttestation(); + var world = Objects.requireNonNull(release.worldStartLocationEvidence()); + var participants = + release.participantDigests().stream() + .map( + participant -> + new Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionIdPresent() ? participant.baseVersionId() : null, + participant.appliedCommitId(), + participant.contentDigest(), + participant.digestSchemaVersion(), + participant.abilitySchemaDigestPresent() + ? participant.abilitySchemaDigest() + : null, + null, + null)) + .toList(); + return new ReleaseContent( + release.canonicalTenantId(), + release.canonicalVersionId(), + release.publishedReleaseBundleRef(), + 1, + "v2", + release.publishWorkflowId(), + release.manifestHash(), + release.manifestSchemaVersion(), + release.artifactDigests(), + release.requiredManifestAssetKeys(), + participants, + release.commandDefinitions(), + release.generationConfigRevision(), + world); + } + + private void completeIsolatedPublicationTerminal( + WorldCanonicalInstancePreparation.Input input) { + var evidence = isolatedTerminalEvidence(input); + GameDesignPublicationTerminalEvidence retained = + publicationTerminalComponent(evidence) + .complete(evidence.operationBytes(), evidence.canonicalBytes()); + if (!Arrays.equals(evidence.canonicalBytes(), retained.canonicalBytes())) { + throw new IllegalStateException( + "Isolated World terminal readback differs from original PUBLISHED v2 evidence"); + } + } + + private WorldPublicationTerminalService publicationTerminalComponent( + GameDesignPublicationTerminalEvidence evidence) { + byte[] operationBytes = evidence.operationBytes(); + return new WorldPublicationTerminalService( + new WorldPublicationTerminalRepository(dsl, transactionManager), + (suppliedOperation, terminalBytes) -> { + GameDesignPublicationTerminalEvidence upstream = + GameDesignPublicationTerminalEvidence.fromStored(terminalBytes); + if (!Arrays.equals(operationBytes, suppliedOperation) + || !Arrays.equals(upstream.operationBytes(), suppliedOperation)) { + throw new IllegalArgumentException("isolated terminal operation mismatch"); + } + return new WorldPublicationTerminalService.VerifiedTerminal( + WorldPublicationTerminal.Request.fromStored(terminalBytes), + new WorldPublicationTerminalService.HeldTerminalAuthority() { + public void requireHeld() {} + + public void close() {} + }); + }); + } + private WorldDraftTopologyCommitPlan topologyPlan(Fixture fixture) { UUID commitId = UUID.randomUUID(); UUID regionId = UUID.randomUUID(); UUID zoneId = UUID.randomUUID(); UUID roomId = UUID.randomUUID(); UUID destinationRoomId = UUID.randomUUID(); + UUID entityId = UUID.randomUUID(); List mutations = - List.of( + new ArrayList<>( + List.of( mutation( commitId, regionId, @@ -1492,9 +1769,63 @@ private WorldDraftTopologyCommitPlan topologyPlan(Fixture fixture) { .setToRoomId(destinationRoomId.toString()) .setDirection("EAST") .setCost(3)) - .build()); + .build())); + WorldFreshGraphDeclaration declaration = + WorldFreshGraphDeclaration.newBuilder() + .setTenantId(fixture.versionIdentity().canonicalTenantId().toString()) + .setVersionId(fixture.versionIdentity().canonicalVersionId().toString()) + .setStartLocation( + RoomTemplateRef.newBuilder() + .setTenantId(fixture.versionIdentity().canonicalTenantId().toString()) + .setVersionId(fixture.versionIdentity().canonicalVersionId().toString()) + .setRoomTemplateId(roomId.toString())) + .addFamilyCounts( + familyCount( + mutations, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION)) + .addFamilyCounts( + familyCount(mutations, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE)) + .addFamilyCounts( + familyCount(mutations, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM)) + .addFamilyCounts( + familyCount( + mutations, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT)) + .addFamilyCounts( + familyCount( + mutations, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE)) + .addFamilyCounts( + familyCount( + mutations, + WorldDesignAggregateType + .WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING)) + .build(); + mutations.set(0, mutations.getFirst().toBuilder().setFreshGraphDeclaration(declaration).build()); List revisions = new java.util.ArrayList<>(); List units = new java.util.ArrayList<>(); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), Owner.ENTITY_MANAGEMENT, "isolated Entity fixture evidence")); + units.add( + new AffectedUnit( + Owner.ENTITY_MANAGEMENT, + "NPC", + entityId.toString(), + "AGGREGATE", + entityId.toString(), + "0")); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "1", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + "isolated Game Design control-plane fixture evidence")); + units.add( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "VERSION", + fixture.versionIdentity().canonicalVersionId().toString(), + "AGGREGATE", + fixture.versionIdentity().canonicalVersionId().toString(), + "0")); for (WorldDesignMutationRevision mutation : mutations) { revisions.add( new DraftCommitBinding.RevisionPayload( @@ -1550,6 +1881,13 @@ private WorldDraftTopologyCommitPlan topologyPlan(Fixture fixture) { owner); } + private static WorldFreshGraphFamilyCount familyCount( + List mutations, WorldDesignAggregateType family) { + int count = + (int) mutations.stream().filter(mutation -> mutation.getAggregateType() == family).count(); + return WorldFreshGraphFamilyCount.newBuilder().setFamily(family).setCount(count).build(); + } + private static WorldDesignMutationRevision.Builder mutation( UUID commit, UUID aggregateId, WorldDesignAggregateType type, UUID containingRegionId) { return WorldDesignMutationRevision.newBuilder() @@ -1754,6 +2092,26 @@ private static CompleteLaunchBindingEvidence completeEvidence( long epoch, String launchDescriptorId, String attestationCommit) { + return completeEvidence( + source, + controlPlaneRequestId, + gameDesignVersionId, + canonicalVersionId, + epoch, + launchDescriptorId, + attestationCommit, + null); + } + + private static CompleteLaunchBindingEvidence completeEvidence( + AuthoredWorldSourceEvidence source, + String controlPlaneRequestId, + long gameDesignVersionId, + UUID canonicalVersionId, + long epoch, + String launchDescriptorId, + String attestationCommit, + WorldPublishedStartLocationEvidence selector) { AuthoredWorldLaunchDescriptorEvidence.Request request = new AuthoredWorldLaunchDescriptorEvidence.Request( NAMESPACE, @@ -1786,14 +2144,26 @@ private static CompleteLaunchBindingEvidence completeEvidence( false, null); return new CompleteLaunchBindingEvidence( - descriptor, attestation(descriptor, source, canonicalVersionId, attestationCommit)); + descriptor, + attestation(descriptor, source, canonicalVersionId, attestationCommit, selector)); } private static AuthoredWorldReleaseAttestationEvidence attestation( AuthoredWorldLaunchDescriptorEvidence descriptor, AuthoredWorldSourceEvidence source, UUID canonicalVersionId, - String commit) { + String commit, + WorldPublishedStartLocationEvidence selector) { + return attestation(descriptor, source, canonicalVersionId, commit, selector, 'f'); + } + + private static AuthoredWorldReleaseAttestationEvidence attestation( + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldSourceEvidence source, + UUID canonicalVersionId, + String commit, + WorldPublishedStartLocationEvidence selector, + char manifestHashDigit) { List participants = List.of( participant("WORLD_MANAGEMENT", 3, "a", false, descriptor.versionId(), commit), @@ -1802,6 +2172,28 @@ private static AuthoredWorldReleaseAttestationEvidence attestation( participant("AUTOMATION_SCRIPTING", 5, "d", false, descriptor.versionId(), commit), participant( "GAME_DESIGN_CONTROL_PLANE", 1, "e", false, descriptor.versionId(), commit)); + if (selector == null) { + return AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + source.canonicalTenantId(), + canonicalVersionId, + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish:synthetic:association-fixture", + commit, + participants, + digest(manifestHashDigit), + 1, + List.of(), + List.of(), + List.of("look"), + descriptor.generationConfigRevision()); + } return AuthoredWorldReleaseAttestationEvidence.create( NAMESPACE, descriptor.resultDigest(), @@ -1816,12 +2208,13 @@ private static AuthoredWorldReleaseAttestationEvidence attestation( "publish:synthetic:association-fixture", commit, participants, - digest('f'), + digest(manifestHashDigit), 1, List.of(), List.of(), List.of("look"), - descriptor.generationConfigRevision()); + descriptor.generationConfigRevision(), + selector); } private static AuthoredWorldReleaseAttestationEvidence releaseWithWorldCheckpoint( @@ -1845,6 +2238,28 @@ private static AuthoredWorldReleaseAttestationEvidence releaseWithWorldCheckpoin participant.abilitySchemaDigestPresent(), participant.abilitySchemaDigest())) .toList(); + if (release.worldStartLocationEvidence() == null) { + return AuthoredWorldReleaseAttestationEvidence.create( + release.targetNamespace(), + release.descriptorResultDigest(), + release.canonicalTenantId(), + release.canonicalVersionId(), + release.worldSlug(), + release.authoredWorldSourceOperationId(), + release.authoredWorldSourceEvidenceDigest(), + release.launchDescriptorId(), + release.publishedReleaseBundleRef(), + release.versionStateEpoch(), + checkpoint.publishWorkflowId(), + checkpoint.appliedCommitId(), + participants, + release.manifestHash(), + release.manifestSchemaVersion(), + release.requiredManifestAssetKeys(), + release.artifactDigests(), + release.commandDefinitions(), + release.generationConfigRevision()); + } return AuthoredWorldReleaseAttestationEvidence.create( release.targetNamespace(), release.descriptorResultDigest(), @@ -1864,7 +2279,8 @@ private static AuthoredWorldReleaseAttestationEvidence releaseWithWorldCheckpoin release.requiredManifestAssetKeys(), release.artifactDigests(), release.commandDefinitions(), - release.generationConfigRevision()); + release.generationConfigRevision(), + release.worldStartLocationEvidence()); } private static AuthoredWorldReleaseAttestationEvidence.Participant participant( 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 99448bd122..2c4d474693 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 @@ -265,9 +265,12 @@ void canonicalPreparationKeepsOriginalPublicationEpochForLaterReleaseResolution( preparationInput(f, frozen, selector, publicationEpoch + 1, List.of("LOOK", "CHANGED")); var laterRelease = laterInput.completeLaunchBinding().evidence().releaseAttestation(); assertThat(laterRelease.versionStateEpoch()).isEqualTo(publicationEpoch + 1); - assertThat(isolatedTerminalEvidence(laterInput).releaseContent().canonicalBytes()) + // Compare the later descriptor's immutable content directly. Its later resolution epoch + // cannot be wrapped in a new publication terminal because the terminal keeps the original + // publication operation epoch. + assertThat(isolatedReleaseContent(laterInput).canonicalBytes()) .containsExactly(originalTerminal.releaseContent().canonicalBytes()); - assertThat(isolatedTerminalEvidence(changedReleaseInput).releaseContent().canonicalBytes()) + assertThat(isolatedReleaseContent(changedReleaseInput).canonicalBytes()) .isNotEqualTo(originalTerminal.releaseContent().canonicalBytes()); var repository = preparationRepository(); @@ -2106,6 +2109,16 @@ private GameDesignPublicationTerminalEvidence isolatedTerminalEvidence( null, new byte[] {1}))); var operation = new GameDesignPublicationOperationBinding(account, world); + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + Outcome.PUBLISHED, + isolatedReleaseContent(input), + release.versionStateEpoch()); + } + + private ReleaseContent isolatedReleaseContent(WorldCanonicalInstancePreparation.Input input) { + var release = input.completeLaunchBinding().evidence().releaseAttestation(); + var world = Objects.requireNonNull(release.worldStartLocationEvidence()); var participants = release.participantDigests().stream() .map( @@ -2123,24 +2136,21 @@ private GameDesignPublicationTerminalEvidence isolatedTerminalEvidence( null, null)) .toList(); - var content = - new ReleaseContent( - release.canonicalTenantId(), - release.canonicalVersionId(), - release.publishedReleaseBundleRef(), - 1, - "v2", - release.publishWorkflowId(), - release.manifestHash(), - release.manifestSchemaVersion(), - release.artifactDigests(), - release.requiredManifestAssetKeys(), - participants, - release.commandDefinitions(), - release.generationConfigRevision(), - world); - return new GameDesignPublicationTerminalEvidence( - operation.canonicalBytes(), Outcome.PUBLISHED, content, release.versionStateEpoch()); + return new ReleaseContent( + release.canonicalTenantId(), + release.canonicalVersionId(), + release.publishedReleaseBundleRef(), + 1, + "v2", + release.publishWorkflowId(), + release.manifestHash(), + release.manifestSchemaVersion(), + release.artifactDigests(), + release.requiredManifestAssetKeys(), + participants, + release.commandDefinitions(), + release.generationConfigRevision(), + world); } private static GameDesignPublicationTerminalEvidence terminalWithWorldBinding( From e7517a874d55242e373a3e2083d709ee4e0242e7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 11:49:14 +1300 Subject: [PATCH 07/12] style: format publication migration proof fixtures --- ...orizationFencePostgresIntegrationTest.java | 3 +- ...nceAssociationPostgresIntegrationTest.java | 142 +++++++++--------- 2 files changed, 73 insertions(+), 72 deletions(-) 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 index 0da16c1d77..27b9c67e39 100644 --- 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 @@ -1001,8 +1001,7 @@ void v79PublicationOrderAndWaitingSourceChangeSurviveV80WithoutInventedOwnerResu .hasStackTraceContaining("account_publication_authorization_owner_results"); assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) .isZero(); - assertThat( - context.dsl().fetchCount(DSL.table("account_draft_authorization_changed_scopes"))) + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_changed_scopes"))) .isZero(); var orderedBeforeHistory = tx(context, () -> context.publication().read(binding)); assertThat(orderedBeforeHistory.ordering()).isEqualTo(Ordering.PUBLICATION_ORDER); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java index 19bb87599b..c31a4fea55 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java @@ -1231,8 +1231,12 @@ private SeededPair seedPair( var checkpoint = frozen.sourceBinding().freeze(); var selector = publishedEvidence( - publishedSelectors().readCommitted(checkpoint).orElseThrow( - () -> new IllegalStateException("Synthetic APPLIED-v2 selector was not retained"))); + publishedSelectors() + .readCommitted(checkpoint) + .orElseThrow( + () -> + new IllegalStateException( + "Synthetic APPLIED-v2 selector was not retained"))); CompleteLaunchBindingEvidence evidence = completeEvidence( source.source(), @@ -1587,8 +1591,7 @@ private GameDesignPublicationTerminalEvidence isolatedTerminalEvidence( WorldCanonicalInstancePreparation.Input input) { var release = input.completeLaunchBinding().evidence().releaseAttestation(); var world = Objects.requireNonNull(release.worldStartLocationEvidence()); - if (release.versionStateEpoch() - != Math.addExact(world.request().versionStateEpoch(), 1L)) { + if (release.versionStateEpoch() != Math.addExact(world.request().versionStateEpoch(), 1L)) { throw new IllegalStateException( "Isolated PUBLISHED terminal must retain the next publication epoch after its World freeze"); } @@ -1630,8 +1633,7 @@ private GameDesignPublicationTerminalEvidence isolatedTerminalEvidence( release.versionStateEpoch()); } - private ReleaseContent isolatedReleaseContent( - WorldCanonicalInstancePreparation.Input input) { + private ReleaseContent isolatedReleaseContent(WorldCanonicalInstancePreparation.Input input) { var release = input.completeLaunchBinding().evidence().releaseAttestation(); var world = Objects.requireNonNull(release.worldStartLocationEvidence()); var participants = @@ -1668,8 +1670,7 @@ private ReleaseContent isolatedReleaseContent( world); } - private void completeIsolatedPublicationTerminal( - WorldCanonicalInstancePreparation.Input input) { + private void completeIsolatedPublicationTerminal(WorldCanonicalInstancePreparation.Input input) { var evidence = isolatedTerminalEvidence(input); GameDesignPublicationTerminalEvidence retained = publicationTerminalComponent(evidence) @@ -1712,64 +1713,64 @@ private WorldDraftTopologyCommitPlan topologyPlan(Fixture fixture) { List mutations = new ArrayList<>( List.of( - mutation( - commitId, - regionId, - WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, - regionId) - .setRegion( - RegionDesignMutation.newBuilder() - .setName("synthetic region") - .setWeather("rain") - .setShardId(7) - .setGenerationSeed(9001) - .setGeneratorType("synthetic") - .setGeneratorParams("{}")) - .build(), - mutation( - commitId, - zoneId, - WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, - regionId) - .setZone( - ZoneDesignMutation.newBuilder() - .setName("synthetic zone") - .setRegionId(regionId.toString())) - .build(), - mutation( - commitId, - destinationRoomId, - WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, - regionId) - .setRoom( - RoomDesignMutation.newBuilder() - .setName("synthetic destination") - .setZoneId(zoneId.toString()) - .setDescription("synthetic destination room")) - .build(), - mutation( - commitId, - roomId, - WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, - regionId) - .setRoom( - RoomDesignMutation.newBuilder() - .setName("synthetic room") - .setZoneId(zoneId.toString()) - .setDescription("synthetic materialization proof")) - .build(), - mutation( - commitId, - UUID.randomUUID(), - WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT, - regionId) - .setRoomExit( - RoomExitDesignMutation.newBuilder() - .setFromRoomId(roomId.toString()) - .setToRoomId(destinationRoomId.toString()) - .setDirection("EAST") - .setCost(3)) - .build())); + mutation( + commitId, + regionId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, + regionId) + .setRegion( + RegionDesignMutation.newBuilder() + .setName("synthetic region") + .setWeather("rain") + .setShardId(7) + .setGenerationSeed(9001) + .setGeneratorType("synthetic") + .setGeneratorParams("{}")) + .build(), + mutation( + commitId, + zoneId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + regionId) + .setZone( + ZoneDesignMutation.newBuilder() + .setName("synthetic zone") + .setRegionId(regionId.toString())) + .build(), + mutation( + commitId, + destinationRoomId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, + regionId) + .setRoom( + RoomDesignMutation.newBuilder() + .setName("synthetic destination") + .setZoneId(zoneId.toString()) + .setDescription("synthetic destination room")) + .build(), + mutation( + commitId, + roomId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, + regionId) + .setRoom( + RoomDesignMutation.newBuilder() + .setName("synthetic room") + .setZoneId(zoneId.toString()) + .setDescription("synthetic materialization proof")) + .build(), + mutation( + commitId, + UUID.randomUUID(), + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT, + regionId) + .setRoomExit( + RoomExitDesignMutation.newBuilder() + .setFromRoomId(roomId.toString()) + .setToRoomId(destinationRoomId.toString()) + .setDirection("EAST") + .setCost(3)) + .build())); WorldFreshGraphDeclaration declaration = WorldFreshGraphDeclaration.newBuilder() .setTenantId(fixture.versionIdentity().canonicalTenantId().toString()) @@ -1780,8 +1781,7 @@ private WorldDraftTopologyCommitPlan topologyPlan(Fixture fixture) { .setVersionId(fixture.versionIdentity().canonicalVersionId().toString()) .setRoomTemplateId(roomId.toString())) .addFamilyCounts( - familyCount( - mutations, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION)) + familyCount(mutations, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION)) .addFamilyCounts( familyCount(mutations, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE)) .addFamilyCounts( @@ -1791,14 +1791,16 @@ private WorldDraftTopologyCommitPlan topologyPlan(Fixture fixture) { mutations, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT)) .addFamilyCounts( familyCount( - mutations, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE)) + mutations, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE)) .addFamilyCounts( familyCount( mutations, WorldDesignAggregateType .WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING)) .build(); - mutations.set(0, mutations.getFirst().toBuilder().setFreshGraphDeclaration(declaration).build()); + mutations.set( + 0, mutations.getFirst().toBuilder().setFreshGraphDeclaration(declaration).build()); List revisions = new java.util.ArrayList<>(); List units = new java.util.ArrayList<>(); revisions.add( From 2b5dbed435d6fe1632d149f8b42282b59e9b1a84 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 14:02:58 +1300 Subject: [PATCH 08/12] Fix canonical World activation guards and exact owner proof --- .github/workflows/ci.yml | 2 +- .../world-runtime-and-movement.md | 4 + ...ationOperationPostgresIntegrationTest.java | 5 +- ...anonical_instance_activation_operation.sql | 109 +++- ...nceAssociationPostgresIntegrationTest.java | 19 +- ...aphApplicationPostgresIntegrationTest.java | 503 ++++++++++++------ 6 files changed, 486 insertions(+), 156 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5111231cb1..b6aba3335c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2288,7 +2288,7 @@ jobs: --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#rawTerminalReceiptCannotCommitWithoutMatchingOwnerPhaseCas()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#onlyPositiveNoPublicationEvidenceCanSealWorldAsAbortedAndCannotPrepare()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#lifecycleReadPreservesPreparingStateAndDeniesLegacyNumericFailureWithExactCanonicalServiceEcho()' \ - --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#canonicalActivationCommitsOneOwnerCasAndReplaysItsImmutableResultAfterLaterLifecycleMove()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#canonicalActivationCommitsOneOwnerCasAndReplaysWhileLegacyTerminationIsDenied()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#canonicalActivationStoresStaleFailedOutcomeAndFreshLifecycleReadRemainsCurrent()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#canonicalActivationRejectsSelfConsistentForgedOwnerBindingsBeforeActiveCas()' \ --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationPostgresIntegrationTest#lostHeldAuthorityAfterOperationInsertRollsBackActivationAndLedger()' \ 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 198606a529..3ed6897edb 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +The exact #3035 e751 runner exposed a V43 activation guard defect: it equated the immutable original version-intake epoch with the later published launch epoch. Those are separately authenticated captures, not interchangeable counters. The correction removes only that cross-stage equality and preserves descriptor/release-to-association, original preparation-input-to-version, exact source/graph/ROOM, held authority and lifecycle CAS checks. Follow-on inspection also found that the reserved-tenant guard had no activation execution manifest, so it would reject the legitimate canonical CAS. The owner-local correction creates a single-use, complete-row, transaction-bound execution manifest only after validating the exact COMMITTED operation and consumes it at the reserved-tenant guard; the existing deferred CAS guard also rejects unconsumed manifests. Focused definitions cover distinct original and published epochs, successful consumption, wrong transaction/instance/full-row/next-counter denial, no-ledger and ABORTED denial, and complete ledger/manifest/lifecycle rollback after authority loss. Direct runtime writes to the protected manifest must not be granted. Corrected PostgreSQL execution remains required; local compilation or skipped cases do not close either defect or authorize activation. + +The activation proof is scoped to genuine PREPARING-to-ACTIVE CAS, concurrent COMMITTED/ABORTED outcomes, immutable same-ACTIVE retry and denial of legacy numeric termination. Canonical termination is not implemented in this slice; replay after a genuine later canonical TERMINATED transition remains an explicit World lifecycle capability/proof obligation. The fixture must not invent that transition or imply its legacy numeric denial proves the target path. + Exact #3035 source `db3d9487e555f94ae1124bdd1a095e098034f3a2` [CI37536968451](https://github.com/benhook1013/FireMUD/actions/runs/37536968451) executed 171 World integration cases and reported fourteen failures. These expose an owned V43 SQL reference to nonexistent association `version_id`, a fixture that constructs a new publication terminal at a later descriptor epoch, and six current association fixtures without V44's required original published v2 selector evidence. The correction must use the joined source-qualified Game Design version rather than a private World key, compare later immutable content without changing the original terminal, and preserve the current exact-PUBLISHED gate while updating its fixtures. Local schema generation or Docker-free skips cannot close these executed failures; corrected runner execution and genuine authenticated owner composition remain required. These failures do not authorize a compatibility fallback or any runtime activation. The current local publication-handoff candidate adds unregistered, default-denied World completion and Account read adapters plus Account's two-owner terminal reconciliation. World completion authenticates the exact same-namespace Game Design workload, independently rereads Game Design's definitive terminal outside the World transaction, then commits the matching `PUBLISHED`/`ABORTED` terminal and owner phase atomically; the Account read adapter authenticates Account and independently returns exact retained World terminal evidence. Account reads Game Design and World outside its owner transaction, compares the complete original operation and terminal bytes, retains both immutable matching owner results, and only then settles the source fence under consistent source-lock ordering. V44 canonical preparation consumes that exact retained `PUBLISHED` terminal and original frozen capture. The components remain unregistered and default-denied; they do not supply the current original publication-authorizing creator producer or the distinct fresh lifecycle/serving authority needed for admission. New definitions and validation are pending the parent gate; local Docker is unavailable, upstream inputs in World PostgreSQL cases are isolated/mocked, and transport tests use a server double. This is not live publication, production readiness, or activation proof. The original publication epoch can precede a later launch-resolution epoch while retaining the exact immutable release content. 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 3e450ad021..47f46ff09e 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 @@ -501,7 +501,10 @@ void retainedV50TerminalReadFailsPreconditionWithoutBackfillingEvidenceOrEpoch() DraftAuthorizationFenceBinding.frame(old, "game-design-publication-owner-readback/v1"); DraftAuthorizationFenceBinding.frame(old, op.canonicalBytes()); DraftAuthorizationFenceBinding.frame(old, "NO_PUBLICATION"); - DraftAuthorizationFenceBinding.frame(old, ""); + // V50 framed nullable release_row_json as a present, zero-byte fourth frame for + // NO_PUBLICATION. Preserve that historical encoding exactly without routing an empty value + // through the nonempty canonical-text helper. + DraftAuthorizationFenceBinding.frame(old, new byte[0]); fixture .write() .executeWithoutResult( diff --git a/services/world-management-service/src/main/resources/db/migration/V43__canonical_instance_activation_operation.sql b/services/world-management-service/src/main/resources/db/migration/V43__canonical_instance_activation_operation.sql index cfa59140e2..ce4cd82159 100644 --- a/services/world-management-service/src/main/resources/db/migration/V43__canonical_instance_activation_operation.sql +++ b/services/world-management-service/src/main/resources/db/migration/V43__canonical_instance_activation_operation.sql @@ -36,8 +36,28 @@ CREATE UNIQUE INDEX uq_world_activation_one_commit_per_instance CREATE INDEX idx_world_activation_world_row ON world_canonical_instance_activation_operation(world_instance_id, activation_request_id); +-- Only the validated operation insert may mint this exact, transaction-local UPDATE capability. +CREATE TABLE world_canonical_activation_execution_manifest ( + transaction_id BIGINT NOT NULL, + activation_request_id UUID NOT NULL, + request_digest VARCHAR(71) NOT NULL, + result_digest VARCHAR(71) NOT NULL, + canonical_game_instance_id UUID NOT NULL, + world_instance_id BIGINT NOT NULL, + local_tenant_key BIGINT NOT NULL, + private_game_instance_key BIGINT NOT NULL, + expected_old JSONB NOT NULL, + expected_new JSONB NOT NULL, + PRIMARY KEY (transaction_id, activation_request_id), + UNIQUE (transaction_id, world_instance_id), + FOREIGN KEY (activation_request_id) + REFERENCES world_canonical_instance_activation_operation(activation_request_id) + ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED +); + -- [jooq ignore start] REVOKE ALL ON world_canonical_instance_activation_operation FROM PUBLIC; +REVOKE ALL ON world_canonical_activation_execution_manifest FROM PUBLIC; CREATE FUNCTION world_validate_canonical_activation_operation() RETURNS TRIGGER @@ -46,6 +66,7 @@ AS $$ DECLARE association_row "${serviceSchema}".world_canonical_instance_association%ROWTYPE; instance "${serviceSchema}".world_instance%ROWTYPE; + activated_instance "${serviceSchema}".world_instance%ROWTYPE; preparing JSONB; normalized_request JSONB; result JSONB; @@ -233,7 +254,8 @@ BEGIN AND v.source_evidence_digest=a.source_evidence_digest AND v.intake_receipt_digest=a.intake_receipt_digest AND v.game_design_version_id::TEXT=b.descriptor_json::JSONB->>'versionId' - AND v.version_state_epoch=a.version_state_epoch + -- Original version intake and later published launch are distinct captures. + -- Each epoch remains bound to its own retained evidence below and above. AND p.target_namespace=a.canonical_target_namespace AND p.canonical_tenant_id=a.canonical_tenant_id AND p.world_slug=a.canonical_world_slug @@ -356,6 +378,18 @@ BEGIN RAISE EXCEPTION 'Committed canonical activation lacks the exact current PREPARING CAS' USING ERRCODE = '23514'; END IF; + activated_instance := instance; + activated_instance.status := 'ACTIVE'; + activated_instance.lifecycle_epoch := NEW.result_lifecycle_epoch; + activated_instance.row_version := NEW.result_row_version; + activated_instance.updated_at := CURRENT_TIMESTAMP; + INSERT INTO "${serviceSchema}".world_canonical_activation_execution_manifest + (transaction_id, activation_request_id, request_digest, result_digest, + canonical_game_instance_id, world_instance_id, local_tenant_key, + private_game_instance_key, expected_old, expected_new) + VALUES (txid_current(), NEW.activation_request_id, NEW.request_digest, NEW.result_digest, + NEW.canonical_game_instance_id, NEW.world_instance_id, association_row.local_tenant_key, + association_row.private_game_instance_key, to_jsonb(instance), to_jsonb(activated_instance)); ELSIF lifecycle->>'lifecycleStatus' IS DISTINCT FROM instance.status OR lifecycle->>'lifecycleEpoch' IS DISTINCT FROM instance.lifecycle_epoch::TEXT OR lifecycle->>'rowVersion' IS DISTINCT FROM instance.row_version::TEXT THEN @@ -385,6 +419,77 @@ CREATE TRIGGER trg_world_canonical_activation_operation_no_truncate BEFORE TRUNCATE ON world_canonical_instance_activation_operation FOR EACH STATEMENT EXECUTE FUNCTION world_reject_canonical_activation_truncate(); +CREATE FUNCTION world_consume_canonical_activation_execution_manifest( + actual_schema TEXT, actual_table TEXT, actual_operation TEXT, + actual_old JSONB, actual_new JSONB +) RETURNS BOOLEAN +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + consumed UUID; +BEGIN + IF actual_schema IS DISTINCT FROM '${serviceSchema}' + OR actual_table IS DISTINCT FROM 'world_instance' + OR actual_operation IS DISTINCT FROM 'UPDATE' + OR actual_old IS NULL OR actual_new IS NULL THEN + RETURN FALSE; + END IF; + DELETE FROM "${serviceSchema}".world_canonical_activation_execution_manifest m + USING "${serviceSchema}".world_canonical_instance_activation_operation o, + "${serviceSchema}".world_canonical_instance_association a + WHERE m.transaction_id = txid_current() + AND m.expected_old = actual_old AND m.expected_new = actual_new + AND m.world_instance_id = (actual_old->>'id')::BIGINT + AND m.world_instance_id = (actual_new->>'id')::BIGINT + AND m.canonical_game_instance_id::TEXT = actual_old->>'canonical_game_instance_id' + AND m.canonical_game_instance_id::TEXT = actual_new->>'canonical_game_instance_id' + AND m.local_tenant_key = (actual_old->>'tenant_id')::BIGINT + AND m.local_tenant_key = (actual_new->>'tenant_id')::BIGINT + AND m.private_game_instance_key = (actual_old->>'game_instance_id')::BIGINT + AND m.private_game_instance_key = (actual_new->>'game_instance_id')::BIGINT + AND o.activation_request_id = m.activation_request_id + AND o.request_digest = m.request_digest AND o.result_digest = m.result_digest + AND o.canonical_game_instance_id = m.canonical_game_instance_id + AND o.world_instance_id = m.world_instance_id AND o.outcome = 'COMMITTED' + AND actual_old->>'status' = 'PREPARING' AND actual_new->>'status' = 'ACTIVE' + AND o.expected_lifecycle_epoch = (actual_old->>'lifecycle_epoch')::BIGINT + AND o.expected_row_version = (actual_old->>'row_version')::BIGINT + AND o.result_lifecycle_epoch = (actual_new->>'lifecycle_epoch')::BIGINT + AND o.result_row_version = (actual_new->>'row_version')::BIGINT + AND convert_from(o.result_bytes, 'UTF8')::JSONB->>'outcome' = 'COMMITTED' + AND convert_from(o.result_bytes, 'UTF8')::JSONB->>'requestDigest' = m.request_digest + AND a.canonical_game_instance_id = m.canonical_game_instance_id + AND a.world_instance_id = m.world_instance_id + AND a.local_tenant_key = m.local_tenant_key + AND a.private_game_instance_key = m.private_game_instance_key + RETURNING m.activation_request_id INTO consumed; + RETURN consumed IS NOT NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_consume_canonical_activation_execution_manifest(TEXT, TEXT, TEXT, JSONB, JSONB) + FROM PUBLIC; + +-- Extend V35's guard at one exact anchor, retaining its region/preparation paths and legacy denial. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ RAISE EXCEPTION + 'World tenant key is reserved for a canonical authored source; no exact transaction execution manifest'$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_claim_legacy_numeric_tenant_key()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,anchor,'')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one reserved-tenant execution denial guard'; + END IF; + original := replace(original,anchor,$replacement$ IF "${serviceSchema}".world_consume_canonical_activation_execution_manifest( + TG_TABLE_SCHEMA, TG_TABLE_NAME, TG_OP, old_row, new_row) THEN + RETURN NEW; + END IF; +$replacement$ || anchor); + EXECUTE original; +END; +$migration$; + CREATE FUNCTION world_require_committed_activation_at_commit() RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" @@ -403,6 +508,8 @@ BEGIN OR instance.row_version IS DISTINCT FROM NEW.result_row_version OR result->>'outcome' IS DISTINCT FROM 'COMMITTED' OR result->>'requestDigest' IS DISTINCT FROM NEW.request_digest + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_activation_execution_manifest m + WHERE m.transaction_id = txid_current() AND m.activation_request_id = NEW.activation_request_id) OR convert_from(decode(result->>'lifecycleEvidenceBytesBase64','base64'),'UTF8')::JSONB->>'lifecycleStatus' IS DISTINCT FROM 'ACTIVE' THEN RAISE EXCEPTION 'Committed canonical activation must include its exact ACTIVE lifecycle CAS before commit' diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java index c31a4fea55..1895de7da7 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java @@ -2166,9 +2166,22 @@ private static AuthoredWorldReleaseAttestationEvidence attestation( String commit, WorldPublishedStartLocationEvidence selector, char manifestHashDigit) { + AuthoredWorldReleaseAttestationEvidence.Participant worldParticipant = + selector == null + ? participant("WORLD_MANAGEMENT", 3, "a", false, descriptor.versionId(), commit) + : new AuthoredWorldReleaseAttestationEvidence.Participant( + "WORLD_MANAGEMENT", + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + selector.request().contentDigest(), + selector.request().digestSchemaVersion(), + false, + null); List participants = List.of( - participant("WORLD_MANAGEMENT", 3, "a", false, descriptor.versionId(), commit), + worldParticipant, participant("ENTITY_MANAGEMENT", 2, "b", false, descriptor.versionId(), commit), participant("GAME_LOGIC", 1, "c", true, descriptor.versionId(), commit), participant("AUTOMATION_SCRIPTING", 5, "d", false, descriptor.versionId(), commit), @@ -2207,8 +2220,8 @@ private static AuthoredWorldReleaseAttestationEvidence attestation( descriptor.launchDescriptorId(), descriptor.publishedReleaseBundleRef(), descriptor.versionStateEpoch(), - "publish:synthetic:association-fixture", - commit, + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), participants, digest(manifestHashDigit), 1, 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 2c4d474693..87f91fdfe9 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 @@ -969,11 +969,10 @@ private void insertPublicationTerminal(WorldPublicationTerminal.Request request) .isTrue(); var prepareFields = materialized.association().worldPrepareFields(); - // 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. + // Successful ACTIVE epoch movement and replay while ACTIVE belong to + // canonicalActivationCommitsOneOwnerCasAndReplaysWhileLegacyTerminationIsDenied. Replay after + // canonical termination remains unavailable until this slice has a canonical termination + // owner operation. This front's legacy numeric writer remains denied for reserved tenants. assertThatThrownBy( () -> lifecycleCommandService.failPreparedWorldInstance( @@ -1017,57 +1016,38 @@ private void insertPublicationTerminal(WorldPublicationTerminal.Request request) } @Test - void canonicalActivationCommitsOneOwnerCasAndReplaysItsImmutableResultAfterLaterLifecycleMove() + void canonicalActivationCommitsOneOwnerCasAndReplaysWhileLegacyTerminationIsDenied() throws Exception { PreparedLifecycleFixture fixture = materializedLifecycleFixture(); + var retainedEpochs = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT v.version_state_epoch AS source_version_state_epoch, " + + "p.input_json::JSONB->'versionIdentity'->>'versionStateEpoch' AS input_version_state_epoch, " + + "b.descriptor_json::JSONB->>'versionStateEpoch' AS descriptor_version_state_epoch, " + + "b.release_attestation_json::JSONB->>'versionStateEpoch' AS release_version_state_epoch, " + + "a.version_state_epoch AS association_version_state_epoch " + + "FROM world_canonical_instance_association a " + + "JOIN world_authored_version_identity v ON v.operation_id=a.version_identity_operation_id " + + "JOIN world_complete_launch_binding b ON b.binding_operation_id=a.canonical_launch_binding_operation_id " + + "JOIN world_canonical_instance_preparation p ON p.canonical_game_instance_id=a.canonical_game_instance_id " + + "WHERE a.canonical_game_instance_id=?", + fixture.input().canonicalGameInstanceId())); + assertThat(retainedEpochs.get("source_version_state_epoch", Long.class)).isEqualTo(1L); + assertThat(retainedEpochs.get("input_version_state_epoch", String.class)).isEqualTo("1"); + assertThat(retainedEpochs.get("descriptor_version_state_epoch", String.class)).isEqualTo("2"); + assertThat(retainedEpochs.get("release_version_state_epoch", String.class)).isEqualTo("2"); + assertThat(retainedEpochs.get("association_version_state_epoch", Long.class)).isEqualTo(2L); byte[] preparationBefore = preparationRows(fixture.input().canonicalGameInstanceId()); - var rawCommitRequest = - new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); - var rawPredictedActive = - new WorldCanonicalInstanceLifecycleEvidence( - fixture.preparing().request(), - fixture.preparing().launchBinding(), - fixture.preparing().startLocation(), - fixture.preparing().runtimeRoomInstanceId(), - "ACTIVE", - fixture.preparing().lifecycleEpoch() + 1L, - fixture.preparing().rowVersion() + 1L, - fixture.preparing().captureId(), - fixture.preparing().graphSha256(), - fixture.preparing().preparationInputDigest()); - var rawCommittedResult = - new WorldCanonicalInstanceActivation.Result( - rawCommitRequest, - WorldCanonicalInstanceActivation.Outcome.COMMITTED, - null, - rawPredictedActive); - byte[] rawRequestBytes = rawCommitRequest.canonicalRequestBytes(); - byte[] rawResultBytes = rawCommittedResult.canonicalBytes(); + var rawCommitProof = rawCommittedActivationProof(fixture); assertThatThrownBy( () -> ownerTransaction() .execute( status -> { - dsl.execute( - "INSERT INTO world_canonical_instance_activation_operation " - + "(activation_request_id,request_digest,request_bytes,preparing_evidence_bytes," - + "canonical_game_instance_id,world_instance_id,expected_lifecycle_epoch,expected_row_version," - + "outcome,terminal_code,result_lifecycle_epoch,result_row_version,result_bytes,result_digest) " - + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", - rawCommitRequest.activationRequestId(), - rawCommitRequest.requestDigest(), - rawRequestBytes, - rawCommitRequest.preparingEvidenceBytes(), - rawCommitRequest.canonicalGameInstanceId(), - fixture.materialized().association().worldInstanceId(), - rawCommitRequest.expectedLifecycleEpoch(), - rawCommitRequest.expectedRowVersion(), - "COMMITTED", - null, - rawCommittedResult.lifecycleEvidence().lifecycleEpoch(), - rawCommittedResult.lifecycleEvidence().rowVersion(), - rawResultBytes, - sha256Digest(rawResultBytes)); + insertRawActivationOperation( + rawCommitProof, + fixture.materialized().association().worldInstanceId()); return null; })) .hasMessageContaining("must include its exact ACTIVE lifecycle CAS before commit"); @@ -1075,9 +1055,11 @@ void canonicalActivationCommitsOneOwnerCasAndReplaysItsImmutableResultAfterLater Objects.requireNonNull( dsl.fetchOne( "SELECT count(*) FROM world_canonical_instance_activation_operation WHERE activation_request_id=?", - rawCommitRequest.activationRequestId())) + rawCommitProof.request().activationRequestId())) .get(0, Long.class)) .isZero(); + assertThat(activationManifestCountForRequest(rawCommitProof.request().activationRequestId())) + .isZero(); var first = new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); @@ -1129,6 +1111,7 @@ void canonicalActivationCommitsOneOwnerCasAndReplaysItsImmutableResultAfterLater assertThat(active.lifecycleStatus()).isEqualTo("ACTIVE"); assertThat(active.lifecycleEpoch()).isEqualTo(committed.lifecycleEvidence().lifecycleEpoch()); assertThat(active.rowVersion()).isEqualTo(committed.lifecycleEvidence().rowVersion()); + assertThat(activationManifestCount(fixture.input().canonicalGameInstanceId())).isZero(); var repository = new WorldCanonicalInstanceActivationRepository(dsl, manager, fixture.lifecycleRepository()); @@ -1158,28 +1141,29 @@ void canonicalActivationCommitsOneOwnerCasAndReplaysItsImmutableResultAfterLater .hasMessageContaining("reused with changed immutable bindings"); assertThat(verifierCalls).hasValue(callsAfterFirstAttempt); - // A raw ACTIVE write cannot manufacture the committed operation that guards this CAS. + // The single-use activation capability was consumed; its retained ledger cannot authorize a + // second raw lifecycle update. assertThatThrownBy( () -> dsl.execute( "UPDATE world_instance SET status='ACTIVE',lifecycle_epoch=lifecycle_epoch+1," + "row_version=row_version+1 WHERE id=?", fixture.materialized().association().worldInstanceId())) - .hasMessageContaining("requires its exact activation operation"); + .hasMessageContaining("no exact transaction execution manifest"); + assertThat(activationManifestCount(fixture.input().canonicalGameInstanceId())).isZero(); var privateKeys = fixture.materialized().association().worldPrepareFields(); - lifecycleCommandService.terminateWorldInstance( - privateKeys.privateTenantKey(), - privateKeys.privateGameInstanceKey(), - active.lifecycleEpoch(), - "activation-replay-terminal-move", - "integration lifecycle movement"); - var terminalRow = - Objects.requireNonNull( - dsl.fetchOne( - "SELECT status,lifecycle_epoch FROM world_instance WHERE id=?", - fixture.materialized().association().worldInstanceId())); - assertThat(terminalRow.get("status", String.class)).isEqualTo("TERMINATED"); + assertThatThrownBy( + () -> + lifecycleCommandService.terminateWorldInstance( + privateKeys.privateTenantKey(), + privateKeys.privateGameInstanceKey(), + active.lifecycleEpoch(), + "activation-replay-terminal-move", + "integration lifecycle movement")) + .hasMessageContaining("no exact transaction execution manifest"); + assertThat(fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow()) + .isEqualTo(active); assertThat(service.activate(committed.request()).canonicalBytes()) .containsExactly(committed.canonicalBytes()); assertThat(verifierCalls).hasValue(callsAfterFirstAttempt); @@ -1191,28 +1175,28 @@ void canonicalActivationCommitsOneOwnerCasAndReplaysItsImmutableResultAfterLater @Test void canonicalActivationStoresStaleFailedOutcomeAndFreshLifecycleReadRemainsCurrent() { PreparedLifecycleFixture fixture = materializedLifecycleFixture(); + var service = canonicalActivationService(fixture, ignored -> stipulatedActivationAuthority()); + var firstRequest = + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); + var current = service.activate(firstRequest); + assertThat(current.outcome()).isEqualTo(WorldCanonicalInstanceActivation.Outcome.COMMITTED); + assertThat(current.lifecycleEvidence().lifecycleStatus()).isEqualTo("ACTIVE"); var staleRequest = new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); - var privateKeys = fixture.materialized().association().worldPrepareFields(); - lifecycleCommandService.failPreparedWorldInstance( - privateKeys.privateTenantKey(), - privateKeys.privateGameInstanceKey(), - fixture.preparing().lifecycleEpoch(), - "stale activation proof"); - var failed = fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow(); - assertThat(failed.lifecycleStatus()).isEqualTo("FAILED_PRE_ACTIVATION"); - var service = canonicalActivationService(fixture, ignored -> stipulatedActivationAuthority()); var aborted = service.activate(staleRequest); assertThat(aborted.outcome()).isEqualTo(WorldCanonicalInstanceActivation.Outcome.ABORTED); assertThat(aborted.terminalCode()).isEqualTo("PRECONDITION_FAILED"); assertThat(aborted.lifecycleEvidence().canonicalBytes()) - .containsExactly(failed.canonicalBytes()); + .containsExactly(current.lifecycleEvidence().canonicalBytes()); assertThat(fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow()) - .isEqualTo(failed); + .isEqualTo(current.lifecycleEvidence()); assertThat(service.activate(staleRequest).canonicalBytes()) .containsExactly(aborted.canonicalBytes()); + assertThat(activationOperationCountForRequest(staleRequest.activationRequestId())) + .isEqualTo(1L); + assertThat(activationManifestCountForRequest(staleRequest.activationRequestId())).isZero(); assertOrigin(); } @@ -1300,6 +1284,7 @@ void canonicalActivationRejectsSelfConsistentForgedOwnerBindingsBeforeActiveCas( sha256Digest(forgedResultBytes))) .hasMessageContaining("differs from immutable World association"); dsl.execute("ROLLBACK TO SAVEPOINT forged_world_activation"); + // V35's reserved-tenant guard denies a raw write without an activation manifest. dsl.execute("SAVEPOINT forged_active_cas"); assertThatThrownBy( () -> @@ -1307,7 +1292,7 @@ void canonicalActivationRejectsSelfConsistentForgedOwnerBindingsBeforeActiveCas( "UPDATE world_instance SET status='ACTIVE',lifecycle_epoch=lifecycle_epoch+1," + "row_version=row_version+1 WHERE id=?", fixture.materialized().association().worldInstanceId())) - .hasMessageContaining("requires its exact activation operation"); + .hasMessageContaining("no exact transaction execution manifest"); dsl.execute("ROLLBACK TO SAVEPOINT forged_active_cas"); return null; }); @@ -1319,6 +1304,7 @@ void canonicalActivationRejectsSelfConsistentForgedOwnerBindingsBeforeActiveCas( activationRequest.activationRequestId())) .get(0, Long.class)) .isZero(); + assertThat(activationManifestCountForRequest(activationRequest.activationRequestId())).isZero(); var lifecycle = fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow(); assertThat(lifecycle.lifecycleStatus()).isEqualTo("PREPARING"); assertThat(lifecycle.lifecycleEpoch()).isEqualTo(activationRequest.expectedLifecycleEpoch()); @@ -1350,6 +1336,8 @@ public void requireHeld() { request.activationRequestId())) .get(0, Long.class)) .isEqualTo(1L); + assertThat(activationManifestCountForRequest(request.activationRequestId())) + .isEqualTo(1L); throw new IllegalStateException("stipulated activation authority loss"); } } @@ -1371,6 +1359,58 @@ public void close() {} request.activationRequestId())) .get(0, Long.class)) .isZero(); + assertThat(activationManifestCountForRequest(request.activationRequestId())).isZero(); + assertThat(activationManifestCount(fixture.input().canonicalGameInstanceId())).isZero(); + assertOrigin(); + } + + @Test + void activationExecutionManifestRequiresExactTransactionInstanceAndRowSnapshots() { + PreparedLifecycleFixture fixture = materializedLifecycleFixture(); + String exactUpdate = + "UPDATE world_instance SET status='ACTIVE',lifecycle_epoch=lifecycle_epoch+1," + + "row_version=row_version+1,updated_at=CURRENT_TIMESTAMP WHERE id=?"; + + assertActivationManifestMismatch( + fixture, + "activation_manifest_wrong_tx", + "UPDATE world_canonical_activation_execution_manifest SET transaction_id=transaction_id+1 " + + "WHERE activation_request_id=?", + exactUpdate); + assertActivationManifestMismatch( + fixture, + "activation_manifest_wrong_instance", + "UPDATE world_canonical_activation_execution_manifest SET world_instance_id=world_instance_id+1 " + + "WHERE activation_request_id=?", + exactUpdate); + assertActivationManifestMismatch( + fixture, + "activation_manifest_extra_old_field", + "UPDATE world_canonical_activation_execution_manifest SET expected_old=expected_old || '{\"extra\":true}'::JSONB " + + "WHERE activation_request_id=?", + exactUpdate); + assertActivationManifestMismatch( + fixture, + "activation_manifest_extra_new_field", + "UPDATE world_canonical_activation_execution_manifest SET expected_new=expected_new || '{\"extra\":true}'::JSONB " + + "WHERE activation_request_id=?", + exactUpdate); + assertActivationManifestMismatch( + fixture, + "activation_manifest_wrong_next_epoch", + null, + "UPDATE world_instance SET status='ACTIVE',lifecycle_epoch=lifecycle_epoch+2," + + "row_version=row_version+1,updated_at=CURRENT_TIMESTAMP WHERE id=?"); + assertActivationManifestMismatch( + fixture, + "activation_manifest_wrong_next_version", + null, + "UPDATE world_instance SET status='ACTIVE',lifecycle_epoch=lifecycle_epoch+1," + + "row_version=row_version+2,updated_at=CURRENT_TIMESTAMP WHERE id=?"); + + var current = fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow(); + assertThat(current).isEqualTo(fixture.preparing()); + assertThat(activationManifestCount(fixture.input().canonicalGameInstanceId())).isZero(); assertOrigin(); } @@ -1474,51 +1514,61 @@ void releaseSelectorRejectsChangedFrozenRequestAndSqlSubstitutionWithoutRuntimeW } @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); + void inertV1PreparationRetainsOriginalBytesAndCannotGainSelectorOnRetry() throws Exception { + HistoricalSchemaFixture schema = historicalSchemaAt("world_v42_inert_v1", "42"); + WorldDraftGraphApplicationPostgresIntegrationTest historical = schema.database(); + Fixture f = historical.fixture(); + var application = historical.application(historical.generationFreePlan(f)); + historical.appliedComponent().apply(application); + var frozen = historical.capture(application.plan()); + var input = historical.preparationInput(f, frozen, null); + var first = historical.prepareV1ThroughOwnerFunction(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"); + byte[] before = historical.preparationRows(input.canonicalGameInstanceId()); + assertThat(historical.prepareV1ThroughOwnerFunction(input)).isEqualTo(first); + assertThat(historical.preparationRows(input.canonicalGameInstanceId())).containsExactly(before); + String originalInputJson = WorldCanonicalInstancePreparationRepository.inputJson(input); + assertThat(originalInputJson).doesNotContain("worldStartLocationEvidence"); assertThat( Objects.requireNonNull( - dsl.fetchOne( + historical.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(); + // V42 cannot reinterpret the immutable selector-null V1 preparation as a V2 materialization. + var selector = + historical.publishedEvidence( + historical.publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + var promotedInput = + (tools.jackson.databind.node.ObjectNode) historical.mapper.readTree(originalInputJson); + promotedInput.put("schemaVersion", 2); + promotedInput.put( + "worldStartLocationEvidenceBase64", + java.util.Base64.getEncoder().encodeToString(selector.canonicalBytes())); + String promotedInputJson = historical.mapper.writeValueAsString(promotedInput); + byte[] promotedInputBytes = promotedInputJson.getBytes(StandardCharsets.UTF_8); 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(); + historical + .ownerTransaction() + .execute( + status -> + historical.dsl.fetchOne( + "SELECT * FROM world_prepare_canonical_instance(?,?)", + promotedInputJson, + sha256Digest(promotedInputBytes)))) + .hasMessageContaining("V2 preparation requires original complete World selector evidence"); + assertThat(historical.preparationRows(input.canonicalGameInstanceId())).containsExactly(before); + assertThat( + Objects.requireNonNull( + historical.dsl.fetchOne( + "SELECT count(*) FROM world_canonical_preparation_start_location WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId())) + .get(0, Long.class)) + .isZero(); + historical.assertOrigin(); } @Test @@ -1531,6 +1581,7 @@ void selectorPreparationLateFenceLossRollsBackSelectorRuntimeAndAssociationToget publishedEvidence( publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); var input = preparationInput(f, frozen, selector); + completeIsolatedPublicationTerminal(input); var component = new WorldCanonicalInstancePreparationService( preparationRepository(), @@ -1643,23 +1694,46 @@ private WorldDraftTopologyCommitPlan generationFreePlan(Fixture f) { @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(); + HistoricalSchemaFixture schema = historicalSchemaAt("world_v41_preparation", "41"); + WorldDraftGraphApplicationPostgresIntegrationTest historical = schema.database(); + 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.prepareV1ThroughOwnerFunction(input); + Map before = historical.preparationHistoryRows(); + byte[] originalApplied = applied.canonicalBytes(); + historical.migrateHistoricalSchema(schema.schema(), "42"); + assertThat(historical.preparationHistoryRows()).isEqualTo(before); + assertThat(historical.prepareV1ThroughOwnerFunction(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 HistoricalSchemaFixture historicalSchemaAt(String schemaPrefix, String version) { + String schema = schemaPrefix + "_" + UUID.randomUUID().toString().replace("-", ""); + migrateHistoricalSchema(schema, version); 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( @@ -1684,14 +1758,10 @@ void v41MaterializedV1HistoryRemainsByteExactAndRetryableAfterV42WithoutSelector 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(); + return new HistoricalSchemaFixture(schema, historical); + } + + private void migrateHistoricalSchema(String schema, String version) { Flyway.configure() .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) .schemas(schema) @@ -1699,28 +1769,52 @@ void v41MaterializedV1HistoryRemainsByteExactAndRetryableAfterV42WithoutSelector .table("flyway_schema_history_world_management_service") .placeholders(Map.of("serviceSchema", schema)) .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion(version)) .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(); + } + + /** Executes the real V35/V42 owner SQL path for selector-null V1 migration history. */ + private WorldCanonicalInstancePreparation.Result prepareV1ThroughOwnerFunction( + WorldCanonicalInstancePreparation.Input input) { + String inputJson = WorldCanonicalInstancePreparationRepository.inputJson(input); + byte[] inputBytes = inputJson.getBytes(StandardCharsets.UTF_8); + Long worldInstanceId = + Objects.requireNonNull( + ownerTransaction() + .execute( + status -> { + var row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM world_prepare_canonical_instance(?, ?)", + inputJson, + sha256Digest(inputBytes)), + "V35/V42 owner preparation function returned no row"); + Long allocatedWorldInstanceId = + Objects.requireNonNull( + row.get("world_instance_id", Long.class), + "V35/V42 owner preparation result omitted world_instance_id"); + var claim = + new WorldCanonicalInstanceAssociation.Claim( + input.gameSessionReadRequest(), + input.gameSessionReadEvidence(), + allocatedWorldInstanceId.longValue(), + input.completeLaunchBinding(), + input.versionIdentity()); + associationRepository().retainClaimInOwnerTransaction(claim); + return allocatedWorldInstanceId; + }), + "V35/V42 owner transaction returned no allocated world_instance_id"); + var result = + preparationRepository() + .readOwnerPreparation(input) + .orElseThrow( + () -> + new IllegalStateException( + "V35/V42 owner preparation has no exact committed readback")); + assertThat(result.association().worldInstanceId()).isEqualTo(worldInstanceId.longValue()); + return result; } private Map preparationHistoryRows() { @@ -2336,6 +2430,108 @@ private WorldCanonicalInstanceActivationService canonicalActivationService( verifier); } + private void assertActivationManifestMismatch( + PreparedLifecycleFixture fixture, + String savepoint, + String manifestTamperSql, + String attemptedUpdateSql) { + ownerTransaction() + .execute( + status -> { + dsl.execute("SAVEPOINT " + savepoint); + var proof = rawCommittedActivationProof(fixture); + insertRawActivationOperation( + proof, fixture.materialized().association().worldInstanceId()); + if (manifestTamperSql != null) { + dsl.execute(manifestTamperSql, proof.request().activationRequestId()); + } + assertThatThrownBy( + () -> + dsl.execute( + attemptedUpdateSql, + fixture.materialized().association().worldInstanceId())) + .hasMessageContaining("no exact transaction execution manifest"); + dsl.execute("ROLLBACK TO SAVEPOINT " + savepoint); + assertThat(activationOperationCountForRequest(proof.request().activationRequestId())) + .isZero(); + assertThat(activationManifestCountForRequest(proof.request().activationRequestId())) + .isZero(); + return null; + }); + } + + private ActivationProof rawCommittedActivationProof(PreparedLifecycleFixture fixture) { + var request = + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); + var predictedActive = + new WorldCanonicalInstanceLifecycleEvidence( + fixture.preparing().request(), + fixture.preparing().launchBinding(), + fixture.preparing().startLocation(), + fixture.preparing().runtimeRoomInstanceId(), + "ACTIVE", + fixture.preparing().lifecycleEpoch() + 1L, + fixture.preparing().rowVersion() + 1L, + fixture.preparing().captureId(), + fixture.preparing().graphSha256(), + fixture.preparing().preparationInputDigest()); + return new ActivationProof( + request, + new WorldCanonicalInstanceActivation.Result( + request, WorldCanonicalInstanceActivation.Outcome.COMMITTED, null, predictedActive)); + } + + private void insertRawActivationOperation(ActivationProof proof, long worldInstanceId) { + var request = proof.request(); + var result = proof.result(); + byte[] requestBytes = request.canonicalRequestBytes(); + byte[] resultBytes = result.canonicalBytes(); + dsl.execute( + "INSERT INTO world_canonical_instance_activation_operation " + + "(activation_request_id,request_digest,request_bytes,preparing_evidence_bytes," + + "canonical_game_instance_id,world_instance_id,expected_lifecycle_epoch,expected_row_version," + + "outcome,terminal_code,result_lifecycle_epoch,result_row_version,result_bytes,result_digest) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + request.activationRequestId(), + request.requestDigest(), + requestBytes, + request.preparingEvidenceBytes(), + request.canonicalGameInstanceId(), + worldInstanceId, + request.expectedLifecycleEpoch(), + request.expectedRowVersion(), + "COMMITTED", + null, + result.lifecycleEvidence().lifecycleEpoch(), + result.lifecycleEvidence().rowVersion(), + resultBytes, + sha256Digest(resultBytes)); + } + + private long activationOperationCountForRequest(UUID requestId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_instance_activation_operation WHERE activation_request_id=?", + requestId)) + .get(0, Long.class); + } + + private long activationManifestCount(UUID canonicalGameInstanceId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_activation_execution_manifest WHERE canonical_game_instance_id=?", + canonicalGameInstanceId)) + .get(0, Long.class); + } + + private long activationManifestCountForRequest(UUID requestId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_activation_execution_manifest WHERE activation_request_id=?", + requestId)) + .get(0, Long.class); + } + /** * Synthetic fixture fence only; it does not authenticate live source, release, or Account state. */ @@ -4284,6 +4480,13 @@ private record Fixture( WorldAuthoredVersionIdentityReceipt version, OwnerBinding owner) {} + private record HistoricalSchemaFixture( + String schema, WorldDraftGraphApplicationPostgresIntegrationTest database) {} + + private record ActivationProof( + WorldCanonicalInstanceActivation.Request request, + WorldCanonicalInstanceActivation.Result result) {} + private record PreparedLifecycleFixture( WorldCanonicalInstancePreparation.Input input, WorldCanonicalInstancePreparation.Result materialized, From 4366be3038b04c13437ccfa1dda7c24b773a76cb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 15:23:16 +1300 Subject: [PATCH 09/12] Match canonical activation evidence to closed lifecycle token encoding --- .../implementation-tracking/world-runtime-and-movement.md | 2 ++ .../V43__canonical_instance_activation_operation.sql | 7 ++++++- .../WorldDraftGraphApplicationPostgresIntegrationTest.java | 7 ++++++- 3 files changed, 14 insertions(+), 2 deletions(-) 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 3ed6897edb..9b38273a9e 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 +Exact-source #3035 [CI 37555140377](https://github.com/benhook1013/FireMUD/actions/runs/37555140377) ran 34 graph/application cases without skips: 30 passed and four activation cases failed the immutable-binding predicate. Association 12, Draft-abort seven and publication-fence eight cases executed cleanly. The remaining activation mismatch is between the retained source row's normalized `DRAFT` token and the preparation producer's intentional `VERSION_LIFECYCLE_STATE_DRAFT` spelling; the guarded SQL now uses an explicit closed DRAFT/PUBLISHED/ACTIVE mapping, preserving original bytes, exact source epochs and every source/association/release/ROOM and one-use execution-manifest check. The existing real-store fixture asserts both retained representations. The corrected World full check, formatting/static analysis, jOOQ generation, boot JAR and documentation gate passed with 392 clean unit executions; all 172 integration cases compiled/discovered but skipped without Docker. Corrected PostgreSQL execution remains required; the broad World task's later connection failures and missing strict Account captures are separate proof gaps, not waived successes. + The exact #3035 e751 runner exposed a V43 activation guard defect: it equated the immutable original version-intake epoch with the later published launch epoch. Those are separately authenticated captures, not interchangeable counters. The correction removes only that cross-stage equality and preserves descriptor/release-to-association, original preparation-input-to-version, exact source/graph/ROOM, held authority and lifecycle CAS checks. Follow-on inspection also found that the reserved-tenant guard had no activation execution manifest, so it would reject the legitimate canonical CAS. The owner-local correction creates a single-use, complete-row, transaction-bound execution manifest only after validating the exact COMMITTED operation and consumes it at the reserved-tenant guard; the existing deferred CAS guard also rejects unconsumed manifests. Focused definitions cover distinct original and published epochs, successful consumption, wrong transaction/instance/full-row/next-counter denial, no-ledger and ABORTED denial, and complete ledger/manifest/lifecycle rollback after authority loss. Direct runtime writes to the protected manifest must not be granted. Corrected PostgreSQL execution remains required; local compilation or skipped cases do not close either defect or authorize activation. The activation proof is scoped to genuine PREPARING-to-ACTIVE CAS, concurrent COMMITTED/ABORTED outcomes, immutable same-ACTIVE retry and denial of legacy numeric termination. Canonical termination is not implemented in this slice; replay after a genuine later canonical TERMINATED transition remains an explicit World lifecycle capability/proof obligation. The fixture must not invent that transition or imply its legacy numeric denial proves the target path. diff --git a/services/world-management-service/src/main/resources/db/migration/V43__canonical_instance_activation_operation.sql b/services/world-management-service/src/main/resources/db/migration/V43__canonical_instance_activation_operation.sql index ce4cd82159..175c33022a 100644 --- a/services/world-management-service/src/main/resources/db/migration/V43__canonical_instance_activation_operation.sql +++ b/services/world-management-service/src/main/resources/db/migration/V43__canonical_instance_activation_operation.sql @@ -298,7 +298,12 @@ BEGIN AND p.input_json::JSONB->'versionIdentity'->>'canonicalVersionId'=v.canonical_version_id::TEXT AND p.input_json::JSONB->'versionIdentity'->>'localVersionKey'=v.local_version_key::TEXT AND p.input_json::JSONB->'versionIdentity'->>'gameDesignVersionId'=v.game_design_version_id::TEXT - AND p.input_json::JSONB->'versionIdentity'->>'versionState'=v.version_state_state + AND p.input_json::JSONB->'versionIdentity'->>'versionState'= + CASE v.version_state_state + WHEN 'DRAFT' THEN 'VERSION_LIFECYCLE_STATE_DRAFT' + WHEN 'PUBLISHED' THEN 'VERSION_LIFECYCLE_STATE_PUBLISHED' + WHEN 'ACTIVE' THEN 'VERSION_LIFECYCLE_STATE_ACTIVE' + END AND p.input_json::JSONB->'versionIdentity'->>'versionStateEpoch'=v.version_state_epoch::TEXT AND p.input_json::JSONB->'versionIdentity'->>'evidenceDigest'=v.version_state_evidence_digest AND p.input_json::JSONB->'sourceIntake'->>'schemaVersion'=s.schema_version::TEXT 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 87f91fdfe9..1670243e35 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 @@ -1022,7 +1022,9 @@ void canonicalActivationCommitsOneOwnerCasAndReplaysWhileLegacyTerminationIsDeni var retainedEpochs = Objects.requireNonNull( dsl.fetchOne( - "SELECT v.version_state_epoch AS source_version_state_epoch, " + "SELECT v.version_state_state AS source_version_state, " + + "p.input_json::JSONB->'versionIdentity'->>'versionState' AS input_version_state, " + + "v.version_state_epoch AS source_version_state_epoch, " + "p.input_json::JSONB->'versionIdentity'->>'versionStateEpoch' AS input_version_state_epoch, " + "b.descriptor_json::JSONB->>'versionStateEpoch' AS descriptor_version_state_epoch, " + "b.release_attestation_json::JSONB->>'versionStateEpoch' AS release_version_state_epoch, " @@ -1033,6 +1035,9 @@ void canonicalActivationCommitsOneOwnerCasAndReplaysWhileLegacyTerminationIsDeni + "JOIN world_canonical_instance_preparation p ON p.canonical_game_instance_id=a.canonical_game_instance_id " + "WHERE a.canonical_game_instance_id=?", fixture.input().canonicalGameInstanceId())); + assertThat(retainedEpochs.get("source_version_state", String.class)).isEqualTo("DRAFT"); + assertThat(retainedEpochs.get("input_version_state", String.class)) + .isEqualTo("VERSION_LIFECYCLE_STATE_DRAFT"); assertThat(retainedEpochs.get("source_version_state_epoch", Long.class)).isEqualTo(1L); assertThat(retainedEpochs.get("input_version_state_epoch", String.class)).isEqualTo("1"); assertThat(retainedEpochs.get("descriptor_version_state_epoch", String.class)).isEqualTo("2"); From e7feaf83ce9f1c6271c10c5fe9b95c58091fb961 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 16:07:19 +1300 Subject: [PATCH 10/12] Inject activation authority loss at observed pre-CAS phase --- ...aphApplicationPostgresIntegrationTest.java | 46 ++++++++++++------- 1 file changed, 30 insertions(+), 16 deletions(-) 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 1670243e35..17490a9617 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 @@ -25,6 +25,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; @@ -1322,7 +1323,7 @@ void lostHeldAuthorityAfterOperationInsertRollsBackActivationAndLedger() { PreparedLifecycleFixture fixture = materializedLifecycleFixture(); var request = new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); - AtomicInteger checks = new AtomicInteger(); + AtomicBoolean lossInjectedAfterOperationInsert = new AtomicBoolean(); var service = canonicalActivationService( fixture, @@ -1330,21 +1331,33 @@ void lostHeldAuthorityAfterOperationInsertRollsBackActivationAndLedger() { assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); return new WorldCanonicalInstanceActivationService.HeldActivationAuthority() { public void requireHeld() { - int count = checks.incrementAndGet(); - if (count == 4) { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()) - .isTrue(); - assertThat( - Objects.requireNonNull( - dsl.fetchOne( - "SELECT count(*) FROM world_canonical_instance_activation_operation WHERE activation_request_id=?", - request.activationRequestId())) - .get(0, Long.class)) - .isEqualTo(1L); - assertThat(activationManifestCountForRequest(request.activationRequestId())) - .isEqualTo(1L); - throw new IllegalStateException("stipulated activation authority loss"); - } + if (!TransactionSynchronizationManager.isActualTransactionActive()) return; + long operationCount = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_instance_activation_operation WHERE activation_request_id=?", + request.activationRequestId())) + .get(0, Long.class); + long manifestCount = + activationManifestCountForRequest(request.activationRequestId()); + if (operationCount != 1L || manifestCount != 1L) return; + + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + var lifecycleRow = + dsl.fetchOne( + "SELECT status, lifecycle_epoch, row_version FROM world_instance WHERE id=?", + fixture.materialized().association().worldInstanceId()); + assertThat(lifecycleRow).isNotNull(); + assertThat(lifecycleRow.get("status", String.class)).isEqualTo("PREPARING"); + assertThat(lifecycleRow.get("lifecycle_epoch", Long.class)) + .isEqualTo(request.expectedLifecycleEpoch()); + assertThat(lifecycleRow.get("row_version", Long.class)) + .isEqualTo(request.expectedRowVersion()); + assertThat(operationCount).isEqualTo(1L); + assertThat(manifestCount).isEqualTo(1L); + lossInjectedAfterOperationInsert.set(true); + throw new IllegalStateException("stipulated activation authority loss"); } public void close() {} @@ -1353,6 +1366,7 @@ public void close() {} assertThatThrownBy(() -> service.activate(request)) .hasMessageContaining("stipulated activation authority loss"); + assertThat(lossInjectedAfterOperationInsert).isTrue(); var current = fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow(); assertThat(current.lifecycleStatus()).isEqualTo("PREPARING"); assertThat(current.lifecycleEpoch()).isEqualTo(fixture.preparing().lifecycleEpoch()); From a9f32559fd6235a1a345048e75be207d4fc9759c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 17:07:34 +1300 Subject: [PATCH 11/12] Preserve full Account PostgreSQL results before strict CI captures --- .github/workflows/ci.yml | 8 ------ .../world-runtime-and-movement.md | 2 ++ .../tests/gradle-proof-tooling-contract.sh | 28 +++++++++++++++++++ 3 files changed, 30 insertions(+), 8 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b6aba3335c..3db6a0824b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2217,14 +2217,6 @@ jobs: --require-case 'net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalOutcomePostgresIntegrationTest#migrationDoesNotInventAccountOutcomesForRetainedStatusOnlyRows()' \ game-design-service - - name: Run Account publication settlement and consumer component proof - if: ${{ !cancelled() && matrix.module == 'account-service' }} - run: | - ./gradlew :account-service:integrationTest \ - --tests integration.net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFencePostgresIntegrationTest \ - --tests integration.net.firedevops.firemud.accountservice.authorpublication.AccountPublicationTerminalReconciliationServiceTest \ - -PfullCheck --no-build-cache --no-configuration-cache - - name: Capture Account publication participation PostgreSQL raw XML if: ${{ always() && matrix.module == 'account-service' }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 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 9b38273a9e..91c64e5f43 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 +Exact source `e7feaf83ce9f1c6271c10c5fe9b95c58091fb961` [CI 37565429271](https://github.com/benhook1013/FireMUD/actions/runs/37565429271) executed the World PostgreSQL graph/application suite (34/34), canonical association (12/12), definitive Draft abort (7/7), and publication fence (8/8), with zero skips in those raw XML captures. The graph suite includes the corrected held-authority-loss rollback case. This closes those named source database-fixture gaps, not later hold/placement composition, genuine multi-owner authorization, or playable handoff. Aggregate CI remains red: Account's subsequent filtered `integrationTest` rerun overwrote the raw results needed by strict Draft/JOIN capture, and TCP's cross-service PLAY cases could not establish actor identity after LOGIN. The bounded workflow correction removes only that redundant Account rerun and retains every strict capture/verifier; its focused ordering contract passes, but actual corrected CI capture remains required. Game Session was cancelled and supplies no completed proof from this run. + Exact-source #3035 [CI 37555140377](https://github.com/benhook1013/FireMUD/actions/runs/37555140377) ran 34 graph/application cases without skips: 30 passed and four activation cases failed the immutable-binding predicate. Association 12, Draft-abort seven and publication-fence eight cases executed cleanly. The remaining activation mismatch is between the retained source row's normalized `DRAFT` token and the preparation producer's intentional `VERSION_LIFECYCLE_STATE_DRAFT` spelling; the guarded SQL now uses an explicit closed DRAFT/PUBLISHED/ACTIVE mapping, preserving original bytes, exact source epochs and every source/association/release/ROOM and one-use execution-manifest check. The existing real-store fixture asserts both retained representations. The corrected World full check, formatting/static analysis, jOOQ generation, boot JAR and documentation gate passed with 392 clean unit executions; all 172 integration cases compiled/discovered but skipped without Docker. Corrected PostgreSQL execution remains required; the broad World task's later connection failures and missing strict Account captures are separate proof gaps, not waived successes. The exact #3035 e751 runner exposed a V43 activation guard defect: it equated the immutable original version-intake epoch with the later published launch epoch. Those are separately authenticated captures, not interchangeable counters. The correction removes only that cross-stage equality and preserves descriptor/release-to-association, original preparation-input-to-version, exact source/graph/ROOM, held authority and lifecycle CAS checks. Follow-on inspection also found that the reserved-tenant guard had no activation execution manifest, so it would reject the legitimate canonical CAS. The owner-local correction creates a single-use, complete-row, transaction-bound execution manifest only after validating the exact COMMITTED operation and consumes it at the reserved-tenant guard; the existing deferred CAS guard also rejects unconsumed manifests. Focused definitions cover distinct original and published epochs, successful consumption, wrong transaction/instance/full-row/next-counter denial, no-ledger and ABORTED denial, and complete ledger/manifest/lifecycle rollback after authority loss. Direct runtime writes to the protected manifest must not be granted. Corrected PostgreSQL execution remains required; local compilation or skipped cases do not close either defect or authorize activation. diff --git a/dev-tools/tests/gradle-proof-tooling-contract.sh b/dev-tools/tests/gradle-proof-tooling-contract.sh index 492371b364..0167937550 100644 --- a/dev-tools/tests/gradle-proof-tooling-contract.sh +++ b/dev-tools/tests/gradle-proof-tooling-contract.sh @@ -308,6 +308,8 @@ STORAGE_CASES = ( f"{STORAGE_SUITE}#migrationWaitsForConcurrentWriterThenRejectsItsCommittedEvidence()", ) CHECK_STEP = "🧪 Run Gradle Checks" +ACCOUNT_PUBLICATION_CAPTURE_STEP = "Capture Account publication participation PostgreSQL raw XML" +ACCOUNT_INTEGRATION_TEST_COMMAND = "./gradlew :account-service:integrationTest" GAME_DESIGN_OWNER_STEP = "Run complete Game Design owner component PostgreSQL proof" GAME_TENANT_CREATION_STEP = "Verify Game Design fresh tenant creation PostgreSQL proof" GAME_AUTHORED_WORLD_SOURCE_STEP = "Verify Game Design authored-world source PostgreSQL proof" @@ -357,6 +359,14 @@ def validate(document) -> None: require(flag in branch[2], f"fresh Gradle check branch omits {flag}") check_index = document["jobs"]["build-and-test"]["steps"].index(check) + account_capture = find_step(document, ACCOUNT_PUBLICATION_CAPTURE_STEP) + account_capture_index = steps.index(account_capture) + require(account_capture_index > check_index, "Account publication XML must be captured after the full Account check") + intervening_steps = steps[check_index + 1 : account_capture_index] + require( + all(ACCOUNT_INTEGRATION_TEST_COMMAND not in str(step.get("run", "")) for step in intervening_steps), + "Account integrationTest must not rerun between the full Account check and raw XML capture", + ) for name, service, suite, cases in ( (SOCIAL_STEP, "social-groups-service", SOCIAL_SUITE, SOCIAL_CASES), (LOGGING_STEP, "logging-admin-service", LOGGING_SUITE, LOGGING_CASES), @@ -467,6 +477,24 @@ mutation_must_fail( ) +def insert_account_integration_test_before_capture(document) -> None: + steps = document["jobs"]["build-and-test"]["steps"] + capture = find_step(document, ACCOUNT_PUBLICATION_CAPTURE_STEP) + steps.insert( + steps.index(capture), + { + "name": "Unexpected Account rerun", + "run": f"{ACCOUNT_INTEGRATION_TEST_COMMAND} --tests ExampleTest", + }, + ) + + +mutation_must_fail( + "Account integrationTest rerun before raw XML capture", + insert_account_integration_test_before_capture, +) + + def move_step_after(document, name: str, anchor_name: str) -> None: steps = document["jobs"]["build-and-test"]["steps"] step = find_step(document, name) From 1b38b0d5c6c7aa5558ec985e50227bb4bf0b4258 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 7 Oct 2026 18:11:07 +1300 Subject: [PATCH 12/12] test(account): compose publication reconciliation with real SQL store --- ...orizationFencePostgresIntegrationTest.java | 275 +++++++++++++++++- 1 file changed, 272 insertions(+), 3 deletions(-) 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 index 27b9c67e39..d3e0955a7b 100644 --- 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 @@ -2,19 +2,27 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import java.io.ByteArrayOutputStream; import java.time.OffsetDateTime; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; 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.AccountPublicationTerminalReconciliationService; import net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFenceRepository; import net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFenceRepository.Ordering; import net.firedevops.firemud.accountservice.authorpublication.PublicationAuthorizationFenceRepository.Owner; @@ -23,10 +31,14 @@ 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.gamedesign.GameDesignPublicationTerminalClient; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.world.WorldPublicationTerminalClient; +import net.firedevops.firemud.common.world.WorldPublicationTerminalReadEvidence; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -37,6 +49,7 @@ import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -44,9 +57,11 @@ /** * 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. Structural terminal rows in the focused SQL tests below are deliberately synthetic: - * they test PostgreSQL integrity/ordering guards only and are not transport or owner proof. + * Account capture. They prove no operative legal terms, source-verification product, live owner RPC + * or publication. Reconciliation definitions inject explicitly synthetic upstream transport doubles + * while exercising the real Account PostgreSQL store. Structural terminal rows in the focused SQL + * tests below are deliberately synthetic: they test PostgreSQL integrity/ordering guards only and + * are not transport or owner proof. */ @Testcontainers(disabledWithoutDocker = true) class PublicationAuthorizationFencePostgresIntegrationTest { @@ -452,6 +467,242 @@ void publishedOwnerPairSettlesPublicationOrderAndAllowsSourceTransition() throws .isEqualTo("SOURCE_COMMITTED"); } + @Test + void realStoreReconciliationRetainsPublishedDesignUntilWorldRetryAndThenSettlesOriginalPair() + throws Exception { + Context context = context(); + var fixture = AccountPublicationTerminalFixtures.scenario(); + tx(context, () -> context.publication().reserve(fixture.account())); + tx(context, () -> context.publication().claimPublicationOrder(fixture.account())); + var change = change(fixture.account()); + assertThat(tx(context, () -> context.draft().requestSourceChange(change))).isFalse(); + + var gameDesignClient = mock(GameDesignPublicationTerminalClient.class); + var worldClient = mock(WorldPublicationTerminalClient.class); + AtomicInteger worldReads = new AtomicInteger(); + when(gameDesignClient.read(any())) + .thenAnswer( + invocation -> { + assertOwnerRpcOutsideAccountTransaction(); + var request = + (GameDesignPublicationTerminalReadEvidence.ReadRequest) invocation.getArgument(0); + return new GameDesignPublicationTerminalReadEvidence.ReadResult( + request, + GameDesignPublicationTerminalReadEvidence.Status.PUBLISHED, + Optional.of(fixture.publishedTerminal())); + }); + when(worldClient.read(any())) + .thenAnswer( + invocation -> { + assertOwnerRpcOutsideAccountTransaction(); + var request = + (WorldPublicationTerminalReadEvidence.Request) invocation.getArgument(0); + if (worldReads.getAndIncrement() == 0) { + return new WorldPublicationTerminalReadEvidence.ReadResult( + request, WorldPublicationTerminalReadEvidence.Status.UNKNOWN, Optional.empty()); + } + return new WorldPublicationTerminalReadEvidence.ReadResult( + request, + WorldPublicationTerminalReadEvidence.Status.PUBLISHED, + Optional.of(fixture.publishedTerminal())); + }); + + var firstService = reconciliationService(context, gameDesignClient, worldClient); + assertThat(firstService.reconcile(fixture.operation().canonicalBytes())) + .contains(Settlement.PENDING); + var retainedDesign = + tx( + context, + () -> context.publication().readOriginalOperation(fixture.operation()).orElseThrow()); + assertThat(retainedDesign.ordering()).isEqualTo(Ordering.PUBLICATION_ORDER); + assertThat(retainedDesign.settlement()).isEqualTo(Settlement.PENDING); + assertThat(retainedDesign.gameDesignResult()).isPresent(); + assertThat(retainedDesign.worldResult()).isEmpty(); + assertThat(retainedDesign.gameDesignResult().orElseThrow().terminalBytes()) + .containsExactly(fixture.publishedTerminal().canonicalBytes()); + assertThat(tx(context, () -> context.draft().sourceMutationPermitted(change))).isFalse(); + + // A restarted service resumes from the exact Account row; it need not refetch Game Design. + var restartedService = reconciliationService(context, gameDesignClient, worldClient); + assertThat(restartedService.reconcile(fixture.operation().canonicalBytes())) + .contains(Settlement.PUBLISHED); + var settled = + tx( + context, + () -> context.publication().readOriginalOperation(fixture.operation()).orElseThrow()); + assertThat(settled.settlement()).isEqualTo(Settlement.PUBLISHED); + assertThat(settled.gameDesignResult()).isPresent(); + assertThat(settled.worldResult()).isPresent(); + assertThat(settled.gameDesignResult().orElseThrow().operationBytes()) + .containsExactly(fixture.operation().canonicalBytes()); + assertThat(settled.gameDesignResult().orElseThrow().terminalBytes()) + .containsExactly(fixture.publishedTerminal().canonicalBytes()); + assertThat(settled.gameDesignResult().orElseThrow().recordedAt()) + .isEqualTo(retainedDesign.gameDesignResult().orElseThrow().recordedAt()); + assertThat(settled.worldResult().orElseThrow().operationBytes()) + .containsExactly(fixture.operation().canonicalBytes()); + assertThat(settled.worldResult().orElseThrow().terminalBytes()) + .containsExactly(fixture.publishedTerminal().canonicalBytes()); + assertThat(tx(context, () -> context.draft().sourceMutationPermitted(change))).isTrue(); + txRun(context, () -> context.draft().markSourceCommitted(change)); + + assertThat(restartedService.reconcile(fixture.operation().canonicalBytes())) + .contains(Settlement.PUBLISHED); + verify(gameDesignClient, times(1)).read(any()); + verify(worldClient, times(2)).read(any()); + assertThat(tx(context, () -> context.draft().readSourceChange(change)).status()) + .isEqualTo("SOURCE_COMMITTED"); + } + + @Test + void realStoreRejectsWrongOperationWorldEvidenceAndExactRetryCanCompleteOriginalPair() + throws Exception { + Context context = context(); + var fixture = AccountPublicationTerminalFixtures.scenario(); + var conflictingFixture = AccountPublicationTerminalFixtures.scenario(); + tx(context, () -> context.publication().reserve(fixture.account())); + tx(context, () -> context.publication().claimPublicationOrder(fixture.account())); + var change = change(fixture.account()); + assertThat(tx(context, () -> context.draft().requestSourceChange(change))).isFalse(); + + var gameDesignClient = mock(GameDesignPublicationTerminalClient.class); + var worldClient = mock(WorldPublicationTerminalClient.class); + AtomicInteger worldReads = new AtomicInteger(); + when(gameDesignClient.read(any())) + .thenAnswer( + invocation -> { + assertOwnerRpcOutsideAccountTransaction(); + var request = + (GameDesignPublicationTerminalReadEvidence.ReadRequest) invocation.getArgument(0); + return new GameDesignPublicationTerminalReadEvidence.ReadResult( + request, + GameDesignPublicationTerminalReadEvidence.Status.PUBLISHED, + Optional.of(fixture.publishedTerminal())); + }); + when(worldClient.read(any())) + .thenAnswer( + invocation -> { + assertOwnerRpcOutsideAccountTransaction(); + var request = + (WorldPublicationTerminalReadEvidence.Request) invocation.getArgument(0); + var evidence = + worldReads.getAndIncrement() == 0 + ? conflictingFixture.publishedTerminal() + : fixture.publishedTerminal(); + return new WorldPublicationTerminalReadEvidence.ReadResult( + request, + WorldPublicationTerminalReadEvidence.Status.PUBLISHED, + Optional.of(evidence)); + }); + + var service = reconciliationService(context, gameDesignClient, worldClient); + assertThat(service.reconcile(fixture.operation().canonicalBytes())) + .contains(Settlement.PENDING); + var pending = + tx( + context, + () -> context.publication().readOriginalOperation(fixture.operation()).orElseThrow()); + assertThat(pending.settlement()).isEqualTo(Settlement.PENDING); + assertThat(pending.gameDesignResult()).isPresent(); + assertThat(pending.worldResult()).isEmpty(); + assertThat(pending.gameDesignResult().orElseThrow().terminalBytes()) + .containsExactly(fixture.publishedTerminal().canonicalBytes()); + assertThat(tx(context, () -> context.draft().sourceMutationPermitted(change))).isFalse(); + + assertThat(service.reconcile(fixture.operation().canonicalBytes())) + .contains(Settlement.PUBLISHED); + var settled = + tx( + context, + () -> context.publication().readOriginalOperation(fixture.operation()).orElseThrow()); + assertThat(settled.settlement()).isEqualTo(Settlement.PUBLISHED); + assertThat(settled.gameDesignResult().orElseThrow().terminalBytes()) + .containsExactly(fixture.publishedTerminal().canonicalBytes()); + assertThat(settled.worldResult().orElseThrow().terminalBytes()) + .containsExactly(fixture.publishedTerminal().canonicalBytes()); + assertThat(settled.gameDesignResult().orElseThrow().recordedAt()) + .isEqualTo(pending.gameDesignResult().orElseThrow().recordedAt()); + assertThat(tx(context, () -> context.draft().sourceMutationPermitted(change))).isTrue(); + verify(gameDesignClient, times(1)).read(any()); + verify(worldClient, times(2)).read(any()); + } + + @Test + void concurrentExactRealStoreReconciliationRetriesRetainOneImmutablePublishedPair() + throws Exception { + Context context = context(); + var fixture = AccountPublicationTerminalFixtures.scenario(); + tx(context, () -> context.publication().reserve(fixture.account())); + tx(context, () -> context.publication().claimPublicationOrder(fixture.account())); + var change = change(fixture.account()); + assertThat(tx(context, () -> context.draft().requestSourceChange(change))).isFalse(); + + var gameDesignClient = mock(GameDesignPublicationTerminalClient.class); + var worldClient = mock(WorldPublicationTerminalClient.class); + CountDownLatch designReads = new CountDownLatch(2); + when(gameDesignClient.read(any())) + .thenAnswer( + invocation -> { + assertOwnerRpcOutsideAccountTransaction(); + var request = + (GameDesignPublicationTerminalReadEvidence.ReadRequest) invocation.getArgument(0); + designReads.countDown(); + await(designReads); + return new GameDesignPublicationTerminalReadEvidence.ReadResult( + request, + GameDesignPublicationTerminalReadEvidence.Status.PUBLISHED, + Optional.of(fixture.publishedTerminal())); + }); + when(worldClient.read(any())) + .thenAnswer( + invocation -> { + assertOwnerRpcOutsideAccountTransaction(); + var request = + (WorldPublicationTerminalReadEvidence.Request) invocation.getArgument(0); + return new WorldPublicationTerminalReadEvidence.ReadResult( + request, + WorldPublicationTerminalReadEvidence.Status.PUBLISHED, + Optional.of(fixture.publishedTerminal())); + }); + + var service = reconciliationService(context, gameDesignClient, worldClient); + try (var executor = Executors.newFixedThreadPool(2)) { + var first = executor.submit(() -> service.reconcile(fixture.operation().canonicalBytes())); + var second = executor.submit(() -> service.reconcile(fixture.operation().canonicalBytes())); + assertThat(first.get(20, TimeUnit.SECONDS)).contains(Settlement.PUBLISHED); + assertThat(second.get(20, TimeUnit.SECONDS)).contains(Settlement.PUBLISHED); + } + var stored = + tx( + context, + () -> context.publication().readOriginalOperation(fixture.operation()).orElseThrow()); + assertThat(stored.ordering()).isEqualTo(Ordering.PUBLICATION_ORDER); + assertThat(stored.settlement()).isEqualTo(Settlement.PUBLISHED); + assertThat(stored.gameDesignResult()).isPresent(); + assertThat(stored.worldResult()).isPresent(); + for (var ownerResult : + List.of(stored.gameDesignResult().orElseThrow(), stored.worldResult().orElseThrow())) { + assertThat(ownerResult.operationBytes()) + .containsExactly(fixture.operation().canonicalBytes()); + assertThat(ownerResult.terminalBytes()) + .containsExactly(fixture.publishedTerminal().canonicalBytes()); + } + var ownerResultCount = + java.util.Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT count(*) FROM account_publication_authorization_owner_results" + + " WHERE operation_id=?", + fixture.operation().account().operationId())); + assertThat(ownerResultCount.get(0, Long.class)).isEqualTo(2L); + assertThat(tx(context, () -> context.draft().sourceMutationPermitted(change))).isTrue(); + verify(gameDesignClient, times(2)).read(any()); + verify(worldClient, times(2)).read(any()); + assertThat(tx(context, () -> context.publication().readSettlement(fixture.operation()))) + .isEqualTo(Settlement.PUBLISHED); + } + @Test void revokeOrderRequiresExactNoPublicationPairBeforeDefinitiveSourceAbort() throws Exception { Context context = context(); @@ -1241,6 +1492,24 @@ private static void txRun(Context context, Runnable work) { }); } + /** These mocked owner transports are synthetic response fixtures, not live owner verification. */ + private static AccountPublicationTerminalReconciliationService reconciliationService( + Context context, + GameDesignPublicationTerminalClient gameDesignClient, + WorldPublicationTerminalClient worldClient) { + return new AccountPublicationTerminalReconciliationService( + context.publication(), + new DataSourceTransactionManager(context.source()), + gameDesignClient, + worldClient, + "test"); + } + + private static void assertOwnerRpcOutsideAccountTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + private static void await(CountDownLatch latch) { try { if (!latch.await(10, TimeUnit.SECONDS)) throw new IllegalStateException("fixture timeout");