From 77adf6b6a530926496b679bd1ca72c68170f048c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 14:58:20 +1300 Subject: [PATCH 01/14] Prepare actual Game Logic retention and selected GDS receipt composition --- .../game-design-service/version-control.md | 2 + .../game-logic-service/runtime-and-data.md | 4 +- .../gameplay-rules-entities-and-effects.md | 6 + services/game-design-service/build.gradle.kts | 18 + ...signGameplayRuleSourceReadGrpcService.java | 59 + ...meDesignGameplayRuleSourceReadService.java | 89 ++ ...tedDraftGameLogicIntakeCommandService.java | 178 +++ .../SelectedDraftGameLogicReceipt.java | 71 + ...lectedDraftGameLogicReceiptRepository.java | 231 +++ .../SelectedDraftGameLogicReceiptService.java | 129 ++ ...ameLogicIntakePostgresIntegrationTest.java | 1242 +++++++++++++++++ ...meLogicReceiptPostgresIntegrationTest.java | 445 ++++++ ...GameplayRuleSourceReadGrpcServiceTest.java | 61 + ...signGameplayRuleSourceReadServiceTest.java | 195 +++ ...raftGameLogicIntakeCommandServiceTest.java | 318 +++++ ...ectedDraftGameLogicReceiptServiceTest.java | 200 +++ .../SelectedDraftGameLogicReceiptTest.java | 224 +++ services/game-logic-service/build.gradle.kts | 25 + ...ameLogicGameplayRuleIntakeGrpcService.java | 80 ++ ...GameLogicGameplayRuleIntakeRepository.java | 109 ++ .../GameLogicGameplayRuleIntakeService.java | 198 +++ ...playRuleIntakeTerminalReadGrpcService.java | 54 + ...GameplayRuleIntakeTerminalReadService.java | 52 + ...GameLogicPublicationSourceReadService.java | 236 ++++ ..._immutable_gameplay_rule_source_intake.sql | 52 + ...lementComposedPostgresIntegrationTest.java | 678 +++++++++ ...playRuleIntakePostgresIntegrationTest.java | 453 ++++++ ...ogicGameplayRuleIntakeGrpcServiceTest.java | 269 ++++ ...ameLogicGameplayRuleIntakeServiceTest.java | 456 ++++++ ...LogicPublicationSourceReadServiceTest.java | 375 +++++ 30 files changed, 6508 insertions(+), 1 deletion(-) create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadGrpcService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceipt.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptService.java create mode 100644 services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadGrpcServiceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadServiceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandServiceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptServiceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptTest.java create mode 100644 services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcService.java create mode 100644 services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeRepository.java create mode 100644 services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java create mode 100644 services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcService.java create mode 100644 services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadService.java create mode 100644 services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationSourceReadService.java create mode 100644 services/game-logic-service/src/main/resources/db/migration/V2__immutable_gameplay_rule_source_intake.sql create mode 100644 services/game-logic-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GameLogicIntakeSettlementComposedPostgresIntegrationTest.java create mode 100644 services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java create mode 100644 services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcServiceTest.java create mode 100644 services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java create mode 100644 services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationSourceReadServiceTest.java diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 89720bd2f3..9a14270997 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -6,6 +6,8 @@ Game Design is the canonical authored-history, publication-coordination, release ## Implementation Status +The prepared selected gameplay-rule source export and intake/receipt composition remain standalone and unregistered; they add no full-version publication authority or runtime rule activation. The [gameplay-rule retention tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) owns qualification, exact owner composition and controlled-input limits. + The combined World source successor implements local shared Draft-writer containment and prepares an unregistered strict Common/protocol foundation for exact owner evidence. Its source foundation alone does not implement Game Design publication orchestration; the standalone World consumer and subsequent Game Design terminal-producer boundaries retain separately scoped proof and authority limits. The [World owner API contract](../world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state) remains authoritative for freeze and terminal operations; separately scoped implementation/proof status is recorded in [the World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#shared-draft-mutation-fence). The owner-local foundation stores canonical Version identity derived from the exact persisted Game row and canonical release identity with an owner-generated opaque reference. Retained Versions and bundles keep their original all-null canonical identity; new canonical inserts cannot mint identity for a retained unbound Version. Bundle writes are immutable, and demo restart reads and reuses the existing bundle. The additive asset-mapping and export-snapshot schemas do not activate asset publication; the complete source-bound fixture successor supplies its own claimed registration, receipt, and runtime handler boundary. State-changing `CompareAndSetVersionState` requests fail closed after tenant/version and expected-epoch checks, preserving same-state no-op; legal transition and database CAS proof remain unavailable. diff --git a/design/architecture/microservices/game-logic-service/runtime-and-data.md b/design/architecture/microservices/game-logic-service/runtime-and-data.md index 268ba9f5ff..aac2fdd985 100644 --- a/design/architecture/microservices/game-logic-service/runtime-and-data.md +++ b/design/architecture/microservices/game-logic-service/runtime-and-data.md @@ -4,6 +4,8 @@ This document defines the Game Logic Service runtime model, dependency ownership ## Implementation Status +The prepared selected gameplay-rule intake repository, terminal owner and publication source reader are standalone and unregistered. Their forward V2 storage does not enable runtime rule consumption or replace the existing legacy digest handler. [The implementation tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) owns qualification and composition limits. + The sections below define the target-state runtime contract. Current implementation and proof status is: - The current implementation attests an empty owned-rule manifest and returns synthetic `appliedCommitId = "version:"` because Game Logic does not yet own version-scoped draft rule tables. The empty-manifest digest is intentional and does not represent hidden service state. @@ -25,7 +27,7 @@ The sections below define the target-state runtime contract. Current implementat - The target runtime contract is that every player-delegated gameplay RPC carries the complete validated typed `PlayerExecutionContext`, including `tenantId`, `playableStateNamespaceId`, server-derived `playableStateScope`, active `gameInstanceId`, and applicable region/epoch or executor fences. The live per-RPC schemas, including `SendCommunication` and its legacy `session_attestation`, remain an implementation gap; see the [PlayerExecutionContext contract](../../system-architecture-authentication.md#gameplay-player-execution-context-contract-normative). - Gameplay gRPC requests do not include JWTs. Game Session provides player identity from Redis via `SessionContext`, may refresh a JWT from Account Service if roles change, and does not validate tokens for gameplay. Service-to-service traffic still uses mutual TLS as described in the [Security Architecture](../../system-architecture-security.md). - Utilizes the [Shared Libraries](../../system-architecture-shared-libraries.md) for DTO definitions, logging interceptors, and Micrometer metrics. -- Flyway is enabled for consistency with other services, but the initial migration is empty because no tables are required. +- Flyway V1 is the existing empty baseline; the prepared V2 adds immutable selected gameplay-rule intake storage. Its qualification and inactive runtime consequences are recorded in the implementation tracker above. - NPC morale and aggression-state evaluation remain part of this service's runtime behavior. When gameplay rules consume faction or reputation signals sourced from Social & Groups, the local morale logic is still owned here, including transitions such as `FLEEING` and `SURRENDERED`; cross-service reputation data informs the decision, but Game Logic owns the gameplay-state consequence. ## Workflow Participation diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index b84d218491..f1c2febc5f 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -6,6 +6,12 @@ This is a non-normative implementation tracker for gameplay rules, entities, and ## Current Status +### Selected gameplay-rule retention and receipt composition + +The prepared standalone Game Logic intake owner requires the exact Account HELD authorization and selected synchronized Game Design source before retaining an immutable terminal. The Game Design selected-intake command and receipt owners compose that retention with Account-owned terminal settlement and persist the exact receipt under existing GDS V1009. New Game Logic V2 follows the empty V1 baseline; existing Account and GDS migration history stays unchanged. None of these owners or read adapters is registered, and the current legacy digest receiver and runtime rule consumption remain separate. + +Compilation, jOOQ generation, focused static/format and physical qualification remain pending. The prepared multi-owner proof uses the actual Game Design-plus-World source commit, World graph application, Account original settlement, selected source export, Game Logic retention and Account intake settlement, with test-only PKI and controlled upstream issuer/environment/source identity inputs. The durable selection is reserved directly through its owner repository; this is not proof of the separate selected-publication command, genuine deployed authoring or release authority. The actual pipeline must qualify before any launch-descriptor consumer may use its receipt. Entity schema 3, Automation schema 6, selected-full attestation 4, activation, placement and delivery remain unfinished; all genuine Gameplay handoffs and Unit 1B/corpus holds remain open. Canonical ownership remains in [Game Logic runtime/data](../../architecture/microservices/game-logic-service/runtime-and-data.md), [Game Design version control](../../architecture/microservices/game-design-service/version-control.md) and the [Account prerequisite tracker](./player-access-and-session.md#selected-gameplay-rule-intake-authorization-prerequisite). + ### Selected gameplay-rule intake prerequisite The prepared typed Account intake boundary carries a complete selected gameplay-rule source binding and immutable authorization, recovery and terminal-settlement evidence. It preserves the current stricter gameplay-rule manifest validation, including numeric stat values. Its Account unit/static/format and five PostgreSQL cases pass, and the corrected Common socket/static/format gate passes; exact scopes and earlier failed large-wire fixtures are attributed in the Account prerequisite tracker. Controlled upstream evidence is not genuine Game Design authoring or Game Logic retention. The actual Game Logic storage/terminal owner and Game Design selected-source/receipt pipeline remain absent from this cut and must qualify before the launch-descriptor producer can consume an intake receipt. Selected-full Entity schema 3 and Automation schema 6 convergence remains a separate unfinished producer/consumer obligation; retained release attestations 1–3 keep their original meaning. See the [Account prerequisite tracker](./player-access-and-session.md#selected-gameplay-rule-intake-authorization-prerequisite) for owner and proof scope. diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts index 6cce7d5e17..71a13035f9 100644 --- a/services/game-design-service/build.gradle.kts +++ b/services/game-design-service/build.gradle.kts @@ -40,8 +40,26 @@ dependencies { "crossServiceTestImplementation", project(mapOf("path" to ":account-service", "configuration" to "accountOriginalOrderProof")) ) + add( + "crossServiceTestImplementation", + project(mapOf("path" to ":game-logic-service", "configuration" to "gameLogicClassesProof")) + ) testImplementation(testFixtures(project(":common-platform-core"))) add("crossServiceTestCompileOnly", libs.spotbugs.annotations) add("crossServiceTestImplementation", "io.grpc:grpc-util:${libs.versions.grpc.get()}") testImplementation(libs.bouncycastle.pkix) } + +// Export GDS owner classes for the GL composed proof without application or Flyway resources. +val gameDesignClassesProofJar by tasks.registering(Jar::class) { + archiveClassifier.set("classes-proof") + dependsOn(tasks.named("classes")) + from(sourceSets.main.get().output.classesDirs) +} + +val gameDesignClassesProof by configurations.creating { + isCanBeConsumed = true + isCanBeResolved = false + extendsFrom(configurations.implementation.get()) + outgoing.artifact(gameDesignClassesProofJar) +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadGrpcService.java new file mode 100644 index 0000000000..aff884a9d9 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadGrpcService.java @@ -0,0 +1,59 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadGrpcCodec; +import net.firedevops.firemud.gamedesign.v1.GameDesignGameplayRuleSourceReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedGameplayRuleSourceRequest; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedGameplayRuleSourceResponse; + +/** Standalone endpoint; authenticate before parsing any source selectors. */ +public final class GameDesignGameplayRuleSourceReadGrpcService + extends GameDesignGameplayRuleSourceReadServiceGrpc + .GameDesignGameplayRuleSourceReadServiceImplBase { + private final GameDesignGameplayRuleSourceReadService owner; + private final String namespace; + + public GameDesignGameplayRuleSourceReadGrpcService( + GameDesignGameplayRuleSourceReadService owner, String namespace) { + this.owner = Objects.requireNonNull(owner); + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + } + + @Override + public void readSelectedGameplayRuleSource( + ReadSelectedGameplayRuleSourceRequest request, + StreamObserver observer) { + try { + GameDesignGameplayRuleSourceReadService.requirePeer(namespace); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + final net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence.Request decoded; + try { + decoded = GameplayRuleSourceReadGrpcCodec.fromRequest(request); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + try { + var result = owner.read(decoded); + observer.onNext(GameplayRuleSourceReadGrpcCodec.toResponse(result)); + observer.onCompleted(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + } catch (IllegalArgumentException | IllegalStateException unavailable) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Complete synchronized rule source unavailable") + .asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadService.java new file mode 100644 index 0000000000..26b43d858c --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadService.java @@ -0,0 +1,89 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import java.util.Objects; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered exact synchronized source read with Account-confirmed reader permission. This read + * does not grant source mutation or Game Logic retention authority. + */ +public final class GameDesignGameplayRuleSourceReadService { + private final GameplayRuleSourceRepository repository; + private final TransactionTemplate transaction; + private final String namespace; + private final net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadClient permissions; + + public GameDesignGameplayRuleSourceReadService( + GameplayRuleSourceRepository repository, + PlatformTransactionManager transactions, + net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadClient permissions, + String namespace) { + this.repository = Objects.requireNonNull(repository); + this.permissions = Objects.requireNonNull(permissions); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + } + + public GameplayRuleSourceReadEvidence read(GameplayRuleSourceReadEvidence.Request request) { + requirePeer(namespace); + if (!namespace.equals(request.targetNamespace())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw Status.FAILED_PRECONDITION + .withDescription("Independent GD owner read required") + .asRuntimeException(); + String reader = GrpcPeerIdentity.current().uri(); + boolean accountReader = + reader.equals("spiffe://firemud/ns/" + namespace + "/sa/account-service"); + if (accountReader != (request.proof() instanceof GameplayRuleSourceReadEvidence.Preliminary)) + throw Status.PERMISSION_DENIED.asRuntimeException(); + var permissionRequest = + net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadEvidence.Request.create( + namespace, reader, request.purpose(), request.proof()); + var permission = permissions.read(permissionRequest); + if (permission == null || !permissionRequest.equals(permission.request())) + throw Status.FAILED_PRECONDITION + .withDescription("Exact Account source permission required") + .asRuntimeException(); + return transaction.execute( + ignored -> { + var snapshot = + repository.requireCompleteForGameLogic( + request.binding().target(), request.binding().commitId()); + if (!snapshot.binding().equals(request.binding())) + throw Status.FAILED_PRECONDITION + .withDescription("Selected rule binding differs") + .asRuntimeException(); + if (request.proof() instanceof GameplayRuleSourceReadEvidence.Finalized finalized + && !java.util.Arrays.equals( + snapshot.canonicalBytes(), finalized.authorization().source().canonicalBytes())) + throw Status.FAILED_PRECONDITION + .withDescription("Finalized source differs") + .asRuntimeException(); + return new GameplayRuleSourceReadEvidence( + request, new GameplayRuleSelectedSource(snapshot.canonicalJson())); + }); + } + + static void requirePeer(String namespace) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + String prefix = "spiffe://firemud/ns/" + namespace + "/sa/"; + if (!(prefix + "account-service").equals(peer.uri()) + && !(prefix + "game-logic-service").equals(peer.uri())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandService.java new file mode 100644 index 0000000000..c3e90c2837 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandService.java @@ -0,0 +1,178 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import org.jooq.DSLContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered composition of the original Account intake producer and the selected-release receipt + * owner. The caller supplies the stable intake identity for both first admission and exact + * recovery; this class does not create or replace that identity. + */ +public final class SelectedDraftGameLogicIntakeCommandService { + private final SelectionReader selections; + private final GameLogicIntakeAuthorizationClient account; + private final ReceiptRetainer receipts; + private final String namespace; + + public SelectedDraftGameLogicIntakeCommandService( + DSLContext dsl, + GameLogicIntakeAuthorizationClient account, + SelectedDraftGameLogicReceiptService receipts, + String namespace) { + this( + repositoryReader(dsl), + account, + Objects.requireNonNull(receipts, "receipts")::retain, + namespace); + } + + SelectedDraftGameLogicIntakeCommandService( + SelectionReader selections, + GameLogicIntakeAuthorizationClient account, + ReceiptRetainer receipts, + String namespace) { + this.selections = Objects.requireNonNull(selections, "selections"); + this.account = Objects.requireNonNull(account, "account"); + this.receipts = Objects.requireNonNull(receipts, "receipts"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + } + + /** Obtains a fresh finalized Account authorization, then retains its exact selected receipt. */ + public SelectedDraftGameLogicReceipt authorizeAndRetain( + AuthoredDraftPublishSelection selection, + GameLogicIntakeAuthorizationEvidence.Request request, + String originalCreatorCredential) { + return produce(selection, request, originalCreatorCredential, account::authorize); + } + + /** Recovers the caller's original intake identity after an uncertain acknowledgement. */ + public SelectedDraftGameLogicReceipt recoverAndRetain( + AuthoredDraftPublishSelection selection, + GameLogicIntakeAuthorizationEvidence.Request request, + String originalCreatorCredential) { + return produce(selection, request, originalCreatorCredential, account::recover); + } + + private SelectedDraftGameLogicReceipt produce( + AuthoredDraftPublishSelection selection, + GameLogicIntakeAuthorizationEvidence.Request request, + String originalCreatorCredential, + AuthorizationCall call) { + requireNoTransaction(); + requireRequestMatchesSelection(selection, request); + + var retainedSelection = + selections + .read(selection) + .orElseThrow( + () -> new IllegalStateException("SELECTED_PUBLICATION_SELECTION_UNAVAILABLE")); + if (!Arrays.equals(selection.canonicalBytes(), retainedSelection.canonicalBytes())) + throw new IllegalStateException("Selected publication differs from immutable selection"); + + // The durable owner read above is outside the ambient caller transaction. Account's producer + // must also remain outside any ambient SQL transaction. + requireNoTransaction(); + final GameLogicIntakeAuthorizationEvidence.Result result; + try { + result = call.invoke(request, originalCreatorCredential); + } catch (RuntimeException denied) { + // The protected original credential must never be reflected by an injected client error. + throw new IllegalStateException("Account intake authorization denied or unavailable"); + } + var authorization = requireFinalized(request, result); + return receipts.retain(selection, authorization); + } + + private void requireRequestMatchesSelection( + AuthoredDraftPublishSelection selection, + GameLogicIntakeAuthorizationEvidence.Request request) { + Objects.requireNonNull(selection, "selection"); + Objects.requireNonNull(request, "request"); + if (!namespace.equals(request.targetNamespace())) + throw new IllegalArgumentException("Intake authorization namespace mismatch"); + byte[] selectionBytes = selection.canonicalBytes(); + if (selectionBytes.length > SelectedDraftGameLogicReceipt.MAX_SELECTION_BYTES + || !Arrays.equals( + selection.selectedCommit().canonicalBytes(), request.selectedDraftBinding())) + throw new IllegalArgumentException("Intake request differs from selected Draft binding"); + // Re-parse the caller's selection so only the canonical immutable representation proceeds. + var canonical = + AuthoredDraftPublishSelection.fromStored(selection.canonicalJson(), selection.digest()); + if (!Arrays.equals(selectionBytes, canonical.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical selected publication"); + } + + private static GameLogicIntakeAuthorizationBinding requireFinalized( + GameLogicIntakeAuthorizationEvidence.Request request, + GameLogicIntakeAuthorizationEvidence.Result result) { + if (result == null || !sameRequest(request, result.request())) + throw new IllegalStateException("Account intake authorization request readback conflict"); + if (result.outcome() != GameLogicIntakeAuthorizationEvidence.Outcome.FINALIZED + || result.authorization().isEmpty()) + throw new IllegalStateException("Account intake authorization is not finalized"); + + var authorization = result.authorization().orElseThrow(); + if (!request.intakeRequestId().equals(authorization.intakeRequestId()) + || !Arrays.equals( + request.selectedDraftBinding(), authorization.source().binding().canonicalBytes())) + throw new IllegalStateException("Account intake authorization differs from exact request"); + return authorization; + } + + private static boolean sameRequest( + GameLogicIntakeAuthorizationEvidence.Request expected, + GameLogicIntakeAuthorizationEvidence.Request actual) { + return actual != null + && expected.schemaVersion() == actual.schemaVersion() + && expected.targetNamespace().equals(actual.targetNamespace()) + && expected.transportRequestId().equals(actual.transportRequestId()) + && expected.intakeRequestId().equals(actual.intakeRequestId()) + && Arrays.equals(expected.selectedDraftBinding(), actual.selectedDraftBinding()); + } + + private static SelectionReader repositoryReader(DSLContext dsl) { + Objects.requireNonNull(dsl, "dsl"); + return selection -> + new AuthoredDraftPublishSelectionRepository(dsl, new DraftCommitCoordinatorRepository(dsl)) + .read( + selection.intent().canonicalTenantId(), + selection.intent().canonicalVersionId(), + selection.intent().publishRequestId()) + .map(AuthoredDraftPublishSelectionRepository.SelectionSnapshot::selection); + } + + private static void requireNoTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw new IllegalStateException("Account intake authorization requires no ambient SQL"); + } + + @FunctionalInterface + interface SelectionReader { + Optional read(AuthoredDraftPublishSelection selection); + } + + @FunctionalInterface + interface ReceiptRetainer { + SelectedDraftGameLogicReceipt retain( + AuthoredDraftPublishSelection selection, GameLogicIntakeAuthorizationBinding authorization); + } + + @FunctionalInterface + private interface AuthorizationCall { + GameLogicIntakeAuthorizationEvidence.Result invoke( + GameLogicIntakeAuthorizationEvidence.Request request, String originalCreatorCredential); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceipt.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceipt.java new file mode 100644 index 0000000000..ea48f81e03 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceipt.java @@ -0,0 +1,71 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; + +/** Derived evidence outside the authored preimage; canonical integrity grants no authority. */ +public record SelectedDraftGameLogicReceipt( + AuthoredDraftPublishSelection selection, + GameLogicIntakeAuthorizationBinding authorization, + AccountGameLogicIntakeSettlementEvidence receipt) { + public static final int MAX_SELECTION_BYTES = 8 * 1024 * 1024; + + public SelectedDraftGameLogicReceipt { + Objects.requireNonNull(receipt, "receipt"); + requireExactSelection(selection, authorization); + requireRetainedTerminal(authorization, receipt.terminal()); + // Enforce each existing codec's closed payload limit before storage. + authorization.canonicalBytes(); + receipt.canonicalBytes(); + } + + static void requireRetainedTerminal( + GameLogicIntakeAuthorizationBinding authorization, + GameLogicGameplayRuleIntakeTerminal terminal) { + if (terminal.outcome() != GameLogicGameplayRuleIntakeTerminal.Outcome.RETAINED + || !Arrays.equals(authorization.canonicalBytes(), terminal.authorizationBytes()) + || !authorization.digest().equals(terminal.authorizationDigest()) + || !Arrays.equals( + authorization.source().canonicalBytes(), terminal.selectedSourceBytes())) { + throw new IllegalArgumentException("Exact RETAINED Account settlement required"); + } + } + + public String workflowIdentity() { + return PublicationDigestRequestBinding.full( + selection.intent().canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + selection.intent().publishRequestId()) + .derivedWorkflowIdentity(); + } + + public static void requireExactSelection( + AuthoredDraftPublishSelection selection, GameLogicIntakeAuthorizationBinding authorization) { + Objects.requireNonNull(selection, "selection"); + Objects.requireNonNull(authorization, "authorization"); + if (selection.canonicalBytes().length > MAX_SELECTION_BYTES) + throw new IllegalArgumentException("Selected publication evidence exceeds 8 MiB"); + authorization.canonicalBytes(); + if (!selection.target().canonicalTenantId().equals(authorization.tenantId()) + || !selection.target().canonicalVersionId().equals(authorization.versionId()) + || !Arrays.equals( + selection.selectedCommit().canonicalBytes(), + authorization.source().binding().canonicalBytes())) { + throw new IllegalArgumentException("Intake differs from complete selected Draft binding"); + } + } + + public void requireExactRequest( + AuthoredDraftPublishSelection expectedSelection, + GameLogicIntakeAuthorizationBinding expectedAuthorization) { + if (!Arrays.equals(selection.canonicalBytes(), expectedSelection.canonicalBytes()) + || !Arrays.equals(authorization.canonicalBytes(), expectedAuthorization.canonicalBytes())) { + throw new IllegalStateException("Selected Game Logic receipt identity conflict"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptRepository.java new file mode 100644 index 0000000000..9aeaf52828 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptRepository.java @@ -0,0 +1,231 @@ +package net.firedevops.firemud.gamedesign.publication; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered immutable derived-receipt storage, separate from publication-operation bytes. */ +public class SelectedDraftGameLogicReceiptRepository { + private final DSLContext dsl; + + @SuppressFBWarnings( + value = {"CT_CONSTRUCTOR_THROW", "EI_EXPOSE_REP2"}, + justification = + "Owner-local persistence collaborator; no resources acquired or finalizer used.") + public SelectedDraftGameLogicReceiptRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + public Optional read( + AuthoredDraftPublishSelection selection, GameLogicIntakeAuthorizationBinding authorization) { + SelectedDraftGameLogicReceipt.requireExactSelection(selection, authorization); + Record row = + dsl.fetchOne( + "SELECT * FROM game_design_selected_game_logic_receipt WHERE canonical_tenant_id = ? AND publish_request_id = ?", + selection.intent().canonicalTenantId(), + selection.intent().publishRequestId()); + if (row == null) return Optional.empty(); + var retained = decode(row); + retained.requireExactRequest(selection, authorization); + return Optional.of(retained); + } + + /** Reads the immutable receipt selected by the exact full-version publication request. */ + public Optional readForPublication( + PublicationDigestRequestBinding publicationRequest) { + Objects.requireNonNull(publicationRequest, "publicationRequest"); + if (publicationRequest.scopeKind() != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION) { + throw new IllegalArgumentException( + "Game Logic receipt publication read requires FULL_VERSION"); + } + UUID canonicalTenantId; + try { + canonicalTenantId = UUID.fromString(publicationRequest.tenantId()); + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException("Publication tenant must be a canonical UUID", malformed); + } + if (!canonicalTenantId.toString().equals(publicationRequest.tenantId())) { + throw new IllegalArgumentException("Publication tenant must be a canonical UUID"); + } + + // The immutable receipt's primary key is exactly the tenant and stable request identity. + // Version and workflow are verified against the decoded selection below; they are not fallback + // lookup dimensions and no latest or numeric-to-UUID inference is permitted. + Record row = + dsl.fetchOne( + "SELECT * FROM game_design_selected_game_logic_receipt WHERE canonical_tenant_id = ? AND publish_request_id = ?", + canonicalTenantId, + publicationRequest.publishRequestId()); + if (row == null) return Optional.empty(); + + var retained = decode(row); + var selection = retained.selection(); + var target = selection.target(); + if (!Long.toString(target.gameDesignVersionRowId()).equals(publicationRequest.versionId()) + || !retained.workflowIdentity().equals(publicationRequest.derivedWorkflowIdentity())) { + throw new IllegalStateException( + "Selected Game Logic receipt does not match publication request"); + } + + // Reconstruct the distinct publication-source binding from the complete original finalized + // Account authorization retained in this immutable receipt. This validates tenant, numeric + // Version row, selected commit and source correlation without creating read authority. + new GameLogicPublicationSourceReadBinding(publicationRequest, retained.authorization()); + + if (dsl.fetchOne( + "SELECT v.id FROM version v JOIN game g " + + "ON g.id = v.identity_source_game_row_id " + + "AND g.tenant_id = v.identity_source_game_tenant_key " + + "AND g.canonical_tenant_id = v.canonical_tenant_id " + + "AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind " + + "AND g.tenant_identity_source_game_id = g.id " + + "AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id " + + "WHERE v.id = ? AND v.tenant_id = ? AND v.canonical_tenant_id = ? " + + "AND v.canonical_version_id = ? AND v.identity_source_game_row_id = ? " + + "AND v.identity_source_game_tenant_key = ? AND v.identity_source_provenance_kind = ? " + + "AND v.identity_source_game_row_id > 0 " + + "AND v.identity_source_game_tenant_key = v.tenant_id " + + "AND v.identity_source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') " + + "AND v.version_state_epoch > 0", + Long.parseLong(publicationRequest.versionId()), + target.gameDesignVersionTenantKey(), + canonicalTenantId, + selection.intent().canonicalVersionId(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind()) + == null) { + throw new IllegalStateException("Selected Game Design Version row proof unavailable"); + } + return Optional.of(retained); + } + + public SelectedDraftGameLogicReceipt retain(SelectedDraftGameLogicReceipt candidate) { + requireTransaction(); + var selection = candidate.selection(); + // Keep the existing owner lock order: Version before immutable selection. + var target = selection.target(); + if (dsl.fetchOne( + "SELECT v.id FROM version v JOIN game g " + + "ON g.id = v.identity_source_game_row_id " + + "AND g.tenant_id = v.identity_source_game_tenant_key " + + "AND g.canonical_tenant_id = v.canonical_tenant_id " + + "AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind " + + "AND g.tenant_identity_source_game_id = g.id " + + "AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id " + + "WHERE v.id = ? AND v.tenant_id = ? AND v.canonical_tenant_id = ? " + + "AND v.canonical_version_id = ? AND v.identity_source_game_row_id = ? " + + "AND v.identity_source_game_tenant_key = ? AND v.identity_source_provenance_kind = ? " + + "AND v.identity_source_game_row_id > 0 " + + "AND v.identity_source_game_tenant_key = v.tenant_id " + + "AND v.identity_source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') " + + "AND v.version_state_epoch > 0 FOR UPDATE OF v", + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.canonicalTenantId(), + target.canonicalVersionId(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind()) + == null) { + throw new IllegalStateException("Selected Version source proof unavailable"); + } + dsl.fetchOne( + "SELECT canonical_tenant_id FROM game_design_authored_draft_publish_selection WHERE canonical_tenant_id = ? AND canonical_version_id = ? FOR UPDATE", + selection.target().canonicalTenantId(), + selection.target().canonicalVersionId()); + var retainedSelection = + new AuthoredDraftPublishSelectionRepository(dsl, new DraftCommitCoordinatorRepository(dsl)) + .read( + selection.intent().canonicalTenantId(), + selection.intent().canonicalVersionId(), + selection.intent().publishRequestId()) + .orElseThrow( + () -> new IllegalStateException("SELECTED_PUBLICATION_SELECTION_UNAVAILABLE")) + .selection(); + if (!Arrays.equals(selection.canonicalBytes(), retainedSelection.canonicalBytes())) { + throw new IllegalStateException("Selected publication changed before receipt retention"); + } + var prior = read(selection, candidate.authorization()); + if (prior.isPresent()) return requireSameReceipt(candidate, prior.get()); + dsl.execute( + "INSERT INTO game_design_selected_game_logic_receipt (canonical_tenant_id, canonical_version_id, publish_request_id, selection_digest, workflow_identity, selection_bytes, authorization_bytes, authorization_digest, receipt_bytes, receipt_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (canonical_tenant_id, publish_request_id) DO NOTHING", + selection.intent().canonicalTenantId(), + selection.intent().canonicalVersionId(), + selection.intent().publishRequestId(), + selection.digest(), + candidate.workflowIdentity(), + selection.canonicalBytes(), + candidate.authorization().canonicalBytes(), + candidate.authorization().digest(), + candidate.receipt().canonicalBytes(), + candidate.receipt().digest()); + return requireSameReceipt(candidate, read(selection, candidate.authorization()).orElseThrow()); + } + + private static SelectedDraftGameLogicReceipt requireSameReceipt( + SelectedDraftGameLogicReceipt candidate, SelectedDraftGameLogicReceipt retained) { + if (!Arrays.equals(candidate.receipt().canonicalBytes(), retained.receipt().canonicalBytes())) { + throw new IllegalStateException("Immutable selected Game Logic receipt conflict"); + } + return retained; + } + + private static SelectedDraftGameLogicReceipt decode(Record row) { + byte[] selectionBytes = row.get("selection_bytes", byte[].class); + var selection = + AuthoredDraftPublishSelection.fromStored( + new String(selectionBytes, StandardCharsets.UTF_8), + row.get("selection_digest", String.class)); + var authorization = + GameLogicIntakeAuthorizationBinding.fromStored( + row.get("authorization_bytes", byte[].class)); + var receipt = + AccountGameLogicIntakeSettlementEvidence.fromStored(row.get("receipt_bytes", byte[].class)); + var value = new SelectedDraftGameLogicReceipt(selection, authorization, receipt); + if (!Arrays.equals(selectionBytes, selection.canonicalBytes()) + || !selection + .intent() + .canonicalTenantId() + .equals(row.get("canonical_tenant_id", java.util.UUID.class)) + || !selection + .intent() + .canonicalVersionId() + .equals(row.get("canonical_version_id", java.util.UUID.class)) + || !selection + .intent() + .publishRequestId() + .equals(row.get("publish_request_id", String.class)) + || !value.workflowIdentity().equals(row.get("workflow_identity", String.class)) + || !authorization.digest().equals(row.get("authorization_digest", String.class)) + || !receipt.digest().equals(row.get("receipt_digest", String.class))) { + throw new IllegalStateException("Stored selected Game Logic receipt integrity conflict"); + } + return value; + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Receipt retention requires writable READ_COMMITTED transaction"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptService.java new file mode 100644 index 0000000000..d5a93c4a87 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptService.java @@ -0,0 +1,129 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementReadClient; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeRetainClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeRetainEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import org.jooq.DSLContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered derived-evidence producer. Requires a separately issued original intake order; + * configured authenticated clients, rather than canonical bytes alone, establish owner provenance. + */ +public final class SelectedDraftGameLogicReceiptService { + private final SelectedDraftGameLogicReceiptRepository repository; + private final SelectionReader selections; + private final GameLogicIntakeRetainClient gameLogic; + private final AccountGameLogicIntakeSettlementReadClient account; + private final TransactionTemplate transaction; + private final String namespace; + + public SelectedDraftGameLogicReceiptService( + DSLContext dsl, + PlatformTransactionManager transactions, + GameLogicIntakeRetainClient gameLogic, + AccountGameLogicIntakeSettlementReadClient account, + String namespace) { + this( + new SelectedDraftGameLogicReceiptRepository(dsl), + selection -> + new AuthoredDraftPublishSelectionRepository( + dsl, new DraftCommitCoordinatorRepository(dsl)) + .read( + selection.intent().canonicalTenantId(), + selection.intent().canonicalVersionId(), + selection.intent().publishRequestId()) + .map(AuthoredDraftPublishSelectionRepository.SelectionSnapshot::selection), + transactions, + gameLogic, + account, + namespace); + } + + SelectedDraftGameLogicReceiptService( + SelectedDraftGameLogicReceiptRepository repository, + SelectionReader selections, + PlatformTransactionManager transactions, + GameLogicIntakeRetainClient gameLogic, + AccountGameLogicIntakeSettlementReadClient account, + String namespace) { + this.repository = Objects.requireNonNull(repository); + this.selections = Objects.requireNonNull(selections); + this.gameLogic = Objects.requireNonNull(gameLogic); + this.account = Objects.requireNonNull(account); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); + transaction.setReadOnly(false); + } + + public SelectedDraftGameLogicReceipt retain( + AuthoredDraftPublishSelection selection, GameLogicIntakeAuthorizationBinding authorization) { + requireNoTransaction(); + SelectedDraftGameLogicReceipt.requireExactSelection(selection, authorization); + var retainedSelection = + selections + .read(selection) + .orElseThrow( + () -> new IllegalStateException("SELECTED_PUBLICATION_SELECTION_UNAVAILABLE")); + if (!Arrays.equals(selection.canonicalBytes(), retainedSelection.canonicalBytes())) { + throw new IllegalStateException("Selected publication differs from immutable selection"); + } + var prior = repository.read(selection, authorization); + if (prior.isPresent()) { + prior.get().requireExactRequest(selection, authorization); + if (!namespace.equals(prior.get().receipt().terminal().operation().targetNamespace())) + throw new IllegalStateException("Retained intake namespace conflict"); + return prior.get(); + } + var retainRequest = GameLogicIntakeRetainEvidence.Request.create(namespace, authorization); + var retained = gameLogic.retain(retainRequest); + if (retained == null || !retainRequest.equals(retained.request())) { + throw new IllegalStateException("Game Logic retain request readback conflict"); + } + if (!namespace.equals(retained.terminal().operation().targetNamespace()) + || !Arrays.equals(authorization.canonicalBytes(), retained.terminal().authorizationBytes()) + || !authorization.digest().equals(retained.terminal().authorizationDigest())) + throw new IllegalStateException("Game Logic intake authorization or namespace conflict"); + // Settle either genuine terminal. ABORTED releases only its own participation and still + // cannot become a positive publication receipt. + var accountRequest = + AccountGameLogicIntakeSettlementReadEvidence.Request.create(namespace, authorization); + var settled = account.read(accountRequest); + if (settled == null + || !accountRequest.equals(settled.request()) + || !Arrays.equals( + retained.terminal().canonicalBytes(), settled.receipt().terminal().canonicalBytes()) + || !retained.terminal().digest().equals(settled.receipt().terminal().digest())) { + throw new IllegalStateException("Account settlement differs from exact retained intake"); + } + var candidate = new SelectedDraftGameLogicReceipt(selection, authorization, settled.receipt()); + return Objects.requireNonNull(transaction.execute(status -> repository.retain(candidate))); + } + + private static void requireNoTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw new IllegalStateException("Receipt owner RPCs require no ambient SQL transaction"); + } + + @FunctionalInterface + interface SelectionReader { + Optional read(AuthoredDraftPublishSelection selection); + } +} diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java new file mode 100644 index 0000000000..aa393d8d13 --- /dev/null +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java @@ -0,0 +1,1242 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.util.JsonFormat; +import io.grpc.BindableService; +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.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.util.MutableHandlerRegistry; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderClient; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftBaseReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitOrderReadClient; +import net.firedevops.firemud.common.authoring.GameDesignDraftTerminalReadClient; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadClient; +import net.firedevops.firemud.common.authoring.WorldOriginalDraftGraphApplyClient; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeTerminalReadClient; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; +import net.firedevops.firemud.common.gamelogic.GrpcAccountGameLogicIntakeSettlementReadClient; +import net.firedevops.firemud.common.gamelogic.GrpcGameLogicIntakeAuthorizationClient; +import net.firedevops.firemud.common.gamelogic.GrpcGameLogicIntakeRetainClient; +import net.firedevops.firemud.common.gamelogic.GrpcGameLogicIntakeSourceReadClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalOperation; +import net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalOutcomeRepository; +import net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalReadGrpcService; +import net.firedevops.firemud.gamedesign.draft.GameDesignReviewedBaseRepository; +import net.firedevops.firemud.gamedesign.draft.GameDesignWorldSourceCommitService; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignGameplayRuleSourceReadGrpcService; +import net.firedevops.firemud.gamedesign.publication.GameDesignGameplayRuleSourceReadService; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicIntakeCommandService; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptRepository; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptService; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldSourceReadGrpcService; +import net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldVersionStateGrpcService; +import net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldVersionStateService; +import net.firedevops.firemud.gamedesign.service.impl.TenantIdentityGrpcService; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeGrpcService; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeRepository; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeService; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeTerminalReadGrpcService; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeTerminalReadService; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeService; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityService; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftCommitOrderVerifier; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTerminalOutcomeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTerminalReadGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalDraftGraphApplicationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalDraftGraphApplyGrpcService; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; +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.WorldInboundSourceClosureDeclaration; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamily; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamilyCount; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; +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; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Bounded GD+World source commit through selection, Account intake, GL terminal, settlement, and + * the immutable GD receipt. SQL owners and loopback mTLS handlers are actual implementations; + * creator, issuer, authored source, Account environment, and workload certificates are controlled + * test inputs and establish no production or registered authority. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GenuineSelectedGameLogicIntakePostgresIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final Network NETWORK = Network.newNetwork(); + + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final PostgreSQLContainer ACCOUNT_POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final PostgreSQLContainer WORLD_POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("genuine-intake-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer REPLICA = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(REDIS) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "genuine-intake-primary", + "6379"); + + @TempDir Path temporary; + + @Test + void controlledCreatorAndWorldFixturesDriveActualOwnersThroughExactIntakeAndReceipt() + throws Exception { + var local = gameDesignLocal(); + var world = worldStore(); + var gameLogic = gameLogicStore(); + try (var account = + new AccountControlUiOriginalOrderFixture( + ACCOUNT_POSTGRES.getJdbcUrl(), + ACCOUNT_POSTGRES.getUsername(), + ACCOUNT_POSTGRES.getPassword(), + REDIS.getHost(), + REDIS.getMappedPort(6379), + temporary.resolve("account"), + local.target().canonicalTenantId())) { + var accountAccess = account.preparedOriginalCreator(); + var accountRepository = + new AccountGameLogicIntakeAuthorizationRepository(accountAccess.sources().dsl); + var accountSourcePermissionOwner = + new AccountGameLogicIntakeSourceReadService( + accountRepository, + account.coordination(), + accountAccess.sources().manager, + Clock.systemUTC(), + NAMESPACE); + var accountHeldReadOwner = + new AccountGameLogicIntakeAuthorizationReadService( + accountRepository, accountAccess.sources().manager, NAMESPACE); + + var endpoints = new ServiceEndpointsProperties(); + var pki = new TestPki(temporary.resolve("pki")); + var gameDesignSourceReads = new AtomicInteger(); + var gameDesignTerminalReads = new AtomicInteger(); + var gameLogicTerminalReads = new AtomicInteger(); + var worldTerminalReads = new AtomicInteger(); + var accountHandlers = new MutableHandlerRegistry(); + var gameDesignHandlers = new MutableHandlerRegistry(); + var gameLogicHandlers = new MutableHandlerRegistry(); + var worldHandlers = new MutableHandlerRegistry(); + Server accountServer = null; + Server gameDesignServer = null; + Server gameLogicServer = null; + Server worldServer = null; + try { + accountServer = startServer(pki, pki.accountServer(), accountHandlers); + endpoints.setAccountService(loopback(accountServer)); + gameDesignServer = startServer(pki, pki.gameDesignServer(), gameDesignHandlers); + endpoints.setGameDesignService(loopback(gameDesignServer)); + gameLogicServer = startServer(pki, pki.gameLogicServer(), gameLogicHandlers); + endpoints.setGameLogicService(loopback(gameLogicServer)); + worldServer = startServer(pki, pki.worldServer(), worldHandlers); + endpoints.setWorldManagementService(loopback(worldServer)); + + registerWorldSourceIdentity(local, world, endpoints, pki, gameDesignHandlers, worldHandlers); + var binding = binding(local, "genuine-admission"); + var reviewedBaseOwner = new GameDesignReviewedBaseRepository(local.dsl()); + transaction(local) + .execute( + ignored -> { + var reviewedBase = + reviewedBaseOwner.resolve( + local.target(), DraftBaseReference.parse(binding.baseCommitId())); + new GameDesignSourceRepository(local.dsl()).claimReviewed(binding, reviewedBase); + var retained = reviewedBaseOwner.requireCurrentRetained(binding); + assertThat(retained.canonicalBytes()).containsExactly(reviewedBase.canonicalBytes()); + assertThat(retained.digest()).isEqualTo(reviewedBase.digest()); + return null; + }); + var originalRequest = account.prepareOriginalDraftOrder(binding, NAMESPACE); + var original = originalRequest.original(); + var credential = originalRequest.originalCreatorCredential(); + + var accountToGameDesignSource = + new GameplayRuleSourceReadClient( + endpoints, + pki.accountClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var gameDesignToAccountPermission = + new GrpcGameLogicIntakeSourceReadClient( + endpoints, + pki.gameDesignClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var gameLogicToAccountHeld = + new GameLogicIntakeAuthorizationReadClient( + endpoints, + pki.gameLogicClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var gameLogicToGameDesignSource = + new GameplayRuleSourceReadClient( + endpoints, + pki.gameLogicClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var accountToGameLogicTerminal = + new GameLogicIntakeTerminalReadClient( + endpoints, + pki.accountClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var gameDesignToAccountAuthorization = + new GrpcGameLogicIntakeAuthorizationClient( + endpoints, + pki.gameDesignClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var gameDesignToGameLogicRetain = + new GrpcGameLogicIntakeRetainClient( + endpoints, + pki.gameDesignClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var gameDesignToAccountSettlement = + new GrpcAccountGameLogicIntakeSettlementReadClient( + endpoints, + pki.gameDesignClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var originalOrderClient = + new AccountOriginalDraftOrderClient( + endpoints, + pki.gameDesignClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var originalTerminalClient = + new GameDesignDraftTerminalReadClient( + endpoints, + pki.accountClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var worldToAccountHeldOrder = + new DraftCommitOrderReadClient( + endpoints, + pki.worldClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var accountToWorldTerminal = + new WorldDraftTerminalReadClient( + endpoints, + pki.accountClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var gameDesignToWorldApply = + new WorldOriginalDraftGraphApplyClient( + endpoints, + pki.gameDesignClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + + var gameDesignSourceOwner = + new GameDesignGameplayRuleSourceReadService( + new GameplayRuleSourceRepository(local.dsl()), + local.transactions(), + gameDesignToAccountPermission, + NAMESPACE); + var gameDesignTerminalOwner = new GameDesignDraftTerminalOutcomeRepository(local.dsl()); + var accountAuthorizationOwner = + new AccountGameLogicIntakeAuthorizationService( + accountAccess.actors(), + accountAccess.sources().fences, + accountRepository, + accountToGameDesignSource, + accountAccess.sources().manager, + NAMESPACE); + var accountSettlementOwner = + new AccountGameLogicIntakeSettlementService( + accountRepository, + accountToGameLogicTerminal, + accountAccess.sources().manager, + NAMESPACE); + var gameLogicRepository = new GameLogicGameplayRuleIntakeRepository(gameLogic.dsl()); + var gameLogicOwner = + new GameLogicGameplayRuleIntakeService( + gameLogicRepository, + gameLogic.transactions(), + gameLogicToAccountHeld, + gameLogicToGameDesignSource, + NAMESPACE); + var worldIntakes = new WorldAuthoredSourceIntakeRepository(world.dsl()); + var worldIdentities = new WorldAuthoredVersionIdentityRepository(world.dsl()); + var worldFence = new WorldDesignPublicationFenceRepository(world.dsl(), worldIntakes); + var mapper = new tools.jackson.databind.ObjectMapper(); + var worldApplications = + new WorldDraftGraphApplicationRepository( + world.dsl(), worldFence, mapper); + var worldTerminals = new WorldDraftTerminalOutcomeRepository(world.dsl(), worldFence, mapper); + var worldApplicationService = + new WorldDraftGraphApplicationService( + worldApplications, + world.transactions(), + new WorldDraftCommitOrderVerifier(worldToAccountHeldOrder, NAMESPACE)); + var worldOriginalApply = + new WorldOriginalDraftGraphApplicationService( + worldIdentities, worldIntakes, worldApplicationService); + registerServices( + accountHandlers, + Map.of(), + account.originalDraftOrderProducer(NAMESPACE), + new net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadGrpcService( + account.heldOrderOwner(NAMESPACE), NAMESPACE), + new AccountGameLogicIntakeAuthorizationGrpcService( + accountAuthorizationOwner, accountAccess.sources().terms, NAMESPACE), + new AccountGameLogicIntakeSourceReadGrpcService( + accountSourcePermissionOwner, NAMESPACE), + new AccountGameLogicIntakeAuthorizationReadGrpcService(accountHeldReadOwner, NAMESPACE), + new AccountGameLogicIntakeSettlementGrpcService(accountSettlementOwner, NAMESPACE)); + registerServices( + gameDesignHandlers, + Map.of( + "readselectedgameplayrulesource", gameDesignSourceReads, + "readgamedesigndraftterminaloutcome", gameDesignTerminalReads), + new GameDesignGameplayRuleSourceReadGrpcService(gameDesignSourceOwner, NAMESPACE), + new GameDesignDraftTerminalReadGrpcService(gameDesignTerminalOwner, NAMESPACE)); + registerServices( + gameLogicHandlers, + Map.of("readgameplayruleintaketerminal", gameLogicTerminalReads), + new GameLogicGameplayRuleIntakeGrpcService(gameLogicOwner, NAMESPACE), + new GameLogicGameplayRuleIntakeTerminalReadGrpcService( + new GameLogicGameplayRuleIntakeTerminalReadService(gameLogicRepository, NAMESPACE), + NAMESPACE)); + registerServices( + worldHandlers, + Map.of("readworlddraftterminaloutcome", worldTerminalReads), + new WorldDraftTerminalReadGrpcService(worldTerminals, worldApplications, NAMESPACE), + new WorldOriginalDraftGraphApplyGrpcService(worldOriginalApply, NAMESPACE)); + + try (accountToGameDesignSource; + gameDesignToAccountPermission; + gameLogicToAccountHeld; + gameLogicToGameDesignSource; + accountToGameLogicTerminal; + gameDesignToAccountAuthorization; + gameDesignToGameLogicRetain; + gameDesignToAccountSettlement; + originalOrderClient; + originalTerminalClient; + worldToAccountHeldOrder; + accountToWorldTerminal; + gameDesignToWorldApply) { + accountToGameDesignSource.init(); + gameDesignToAccountPermission.init(); + gameLogicToAccountHeld.init(); + gameLogicToGameDesignSource.init(); + accountToGameLogicTerminal.init(); + gameDesignToAccountAuthorization.init(); + gameDesignToGameLogicRetain.init(); + gameDesignToAccountSettlement.init(); + originalOrderClient.init(); + originalTerminalClient.init(); + worldToAccountHeldOrder.init(); + accountToWorldTerminal.init(); + gameDesignToWorldApply.init(); + + var commitService = + new GameDesignWorldSourceCommitService( + originalOrderClient, + gameDesignToWorldApply, + new DraftCommitCoordinatorRepository(local.dsl()), + new GameDesignDraftTerminalOutcomeRepository(local.dsl()), + new GameDesignSourceRepository(local.dsl()), + local.transactions(), + NAMESPACE); + var originalTerminal = commitService.commit(original, credential); + assertThat(originalTerminal.result()) + .isEqualTo( + net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalOutcome.Result + .COMMITTED); + assertThat(originalTerminal.operation().accountBindingBytes()) + .containsExactly(originalRequest.originalAccountBinding()); + assertSynchronizedSource(local, original); + account.assertOriginalDraftOrderPending(original); + + account.reconcileOriginalDraft( + original, + originalTerminalClient, + accountToWorldTerminal, + NAMESPACE); + assertThat(gameDesignTerminalReads).hasValue(1); + assertThat(worldTerminalReads).hasValue(1); + assertThat(gameDesignSourceReads).hasValue(0); + + var selection = reserveSelection(local, original); + var receiptOwner = + new SelectedDraftGameLogicReceiptService( + local.dsl(), + local.transactions(), + gameDesignToGameLogicRetain, + gameDesignToAccountSettlement, + NAMESPACE); + var authorizationCalls = new AtomicInteger(); + var lostFirstResponse = new AtomicBoolean(); + GameLogicIntakeAuthorizationClient lostResponseClient = + new GameLogicIntakeAuthorizationClient() { + @Override + public GameLogicIntakeAuthorizationEvidence.Result authorize( + GameLogicIntakeAuthorizationEvidence.Request request, + String originalCreatorCredential) { + authorizationCalls.incrementAndGet(); + var response = + gameDesignToAccountAuthorization.authorize( + request, originalCreatorCredential); + if (lostFirstResponse.compareAndSet(false, true)) + throw new IllegalStateException( + "test-only lost Account authorization response"); + return response; + } + + @Override + public GameLogicIntakeAuthorizationEvidence.Result recover( + GameLogicIntakeAuthorizationEvidence.Request request, + String originalCreatorCredential) { + return gameDesignToAccountAuthorization.recover( + request, originalCreatorCredential); + } + + @Override + public GameLogicIntakeAuthorizationEvidence.Result abort( + GameLogicIntakeAuthorizationEvidence.Request request, + String originalCreatorCredential) { + return gameDesignToAccountAuthorization.abort(request, originalCreatorCredential); + } + }; + var command = + new SelectedDraftGameLogicIntakeCommandService( + local.dsl(), lostResponseClient, receiptOwner, NAMESPACE); + var wrongSourceRequest = + GameLogicIntakeAuthorizationEvidence.Request.create( + NAMESPACE, UUID.randomUUID(), binding(local, "substituted-admission")); + assertThatThrownBy( + () -> command.authorizeAndRetain(selection, wrongSourceRequest, credential)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("selected Draft binding"); + assertThat(authorizationCalls).hasValue(0); + assertThat(gameDesignSourceReads).hasValue(0); + + var request = + GameLogicIntakeAuthorizationEvidence.Request.create( + NAMESPACE, UUID.randomUUID(), selection.selectedCommit()); + assertThatThrownBy(() -> command.authorizeAndRetain(selection, request, credential)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Account intake authorization denied or unavailable"); + assertThat(authorizationCalls).hasValue(1); + assertThat( + accountAccess + .sources() + .dsl + .fetchCount(DSL.table("account_game_logic_intake_authorizations"))) + .isEqualTo(1); + assertThat(gameDesignSourceReads).hasValue(1); + + SelectedDraftGameLogicReceipt recovered = + command.recoverAndRetain(selection, request, credential); + assertThat(recovered.authorization().source().binding().canonicalBytes()) + .containsExactly(selection.selectedCommit().canonicalBytes()); + assertThat(recovered.receipt().terminal().outcome()) + .isEqualTo( + net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal + .Outcome.RETAINED); + assertThat(gameDesignSourceReads).hasValue(2); + assertThat(gameLogicTerminalReads).hasValue(1); + + var retry = command.recoverAndRetain(selection, request, credential); + assertThat(retry.selection().canonicalBytes()) + .containsExactly(recovered.selection().canonicalBytes()); + assertThat(retry.authorization().canonicalBytes()) + .containsExactly(recovered.authorization().canonicalBytes()); + assertThat(retry.receipt().canonicalBytes()) + .containsExactly(recovered.receipt().canonicalBytes()); + assertThat(gameDesignSourceReads).hasValue(2); + assertThat(gameLogicTerminalReads).hasValue(1); + var retainedReceipt = + new SelectedDraftGameLogicReceiptRepository(local.dsl()) + .read(selection, recovered.authorization()) + .orElseThrow(); + assertThat(retainedReceipt.selection().canonicalBytes()) + .containsExactly(recovered.selection().canonicalBytes()); + assertThat(retainedReceipt.authorization().canonicalBytes()) + .containsExactly(recovered.authorization().canonicalBytes()); + assertThat(retainedReceipt.receipt().canonicalBytes()) + .containsExactly(recovered.receipt().canonicalBytes()); + assertThat( + gameLogicRepository + .findTerminal(recovered.authorization().operationId()) + .orElseThrow() + .canonicalBytes()) + .containsExactly(recovered.receipt().terminal().canonicalBytes()); + assertThat( + accountAccess + .sources() + .dsl + .fetchCount(DSL.table("account_game_logic_intake_settlements"))) + .isEqualTo(1); + assertThat( + gameLogic.dsl().fetchCount(DSL.table("game_logic_gameplay_rule_intake_terminal"))) + .isEqualTo(1); + assertThat(local.dsl().fetchCount(DSL.table("game_design_selected_game_logic_receipt"))) + .isEqualTo(1); + assertThat( + accountAccess + .sources() + .tx(() -> accountAccess.sources().fences.readSettlement(original))) + .isEqualTo(DraftAuthorizationFenceRepository.Settlement.COMMITTED); + } + } finally { + stopAll(worldServer, gameLogicServer, gameDesignServer, accountServer); + } + } + } + + private AuthoredDraftPublishSelection reserveSelection( + Local local, DraftAuthorizationFenceBinding original) { + var tx = transaction(local); + var selected = new GameDesignDraftTerminalOperation(original).gameDesignBinding(); + return tx.execute( + ignored -> + new AuthoredDraftPublishSelectionRepository( + local.dsl(), new DraftCommitCoordinatorRepository(local.dsl())) + .reserve( + new AuthoredDraftPublishSelection.PublishIntent( + local.target().canonicalTenantId(), + local.target().canonicalVersionId(), + UUID.randomUUID().toString(), + "1", + "controlled owner source receipt proof", + selected.requestId(), + selected.commitId(), + selected.digest())) + .selection()); + } + + private static void assertSynchronizedSource( + Local local, DraftAuthorizationFenceBinding original) { + var snapshot = + new GameDesignSourceRepository(local.dsl()) + .readSynchronized(local.target(), original.commitId()) + .orElseThrow(); + assertThat( + snapshot + .gameplay() + .manifest() + .families() + .get(GameplayRuleManifest.Family.ADMISSION_TAGS)) + .hasSize(1); + assertThat(snapshot.gameplay().binding().canonicalBytes()) + .containsExactly(original.gameDesignBinding()); + } + + private void registerWorldSourceIdentity( + Local local, + WorldStore world, + ServiceEndpointsProperties endpoints, + TestPki pki, + MutableHandlerRegistry gameDesignHandlers, + MutableHandlerRegistry worldHandlers) + throws Exception { + var gameSourceRepository = new GameAuthoredWorldSourceRepository(local.dsl()); + registerServices( + gameDesignHandlers, + Map.of(), + new TenantIdentityGrpcService( + new GameTenantCreationRepository(local.dsl(), new GameRepository(local.dsl())), + NAMESPACE), + new AuthoredWorldSourceReadGrpcService(gameSourceRepository, NAMESPACE), + new AuthoredWorldVersionStateGrpcService( + new AuthoredWorldVersionStateService(local.transactions(), gameSourceRepository), + NAMESPACE)); + var source = + transaction(local) + .execute( + ignored -> + gameSourceRepository.register( + NAMESPACE, + UUID.randomUUID(), + local.target().canonicalTenantId(), + "controlled-tenant", + "controlled-world", + "Controlled authored World source")); + var intakes = new WorldAuthoredSourceIntakeRepository(world.dsl()); + var identities = new WorldAuthoredVersionIdentityRepository(world.dsl()); + try (var sourceClient = + new AuthoredWorldSourceClient( + endpoints, + pki.worldClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var versionClient = + new AuthoredWorldVersionStateClient( + endpoints, + pki.worldClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var intakeClient = + new WorldAuthoredSourceIntakeClient( + endpoints, + pki.gameDesignClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE)) { + sourceClient.init(); + versionClient.init(); + var intakeService = + new WorldAuthoredSourceIntakeService( + sourceClient, intakes, world.transactions(), NAMESPACE); + var identityService = + new WorldAuthoredVersionIdentityService( + versionClient, identities, intakes, world.transactions(), NAMESPACE); + var associationComplete = new AtomicBoolean(); + var associationHook = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata headers, + ServerCallHandler next) { + return next.startCall( + new ForwardingServerCall.SimpleForwardingServerCall<>(call) { + @Override + public void sendMessage(RespT message) { + if (associationComplete.compareAndSet(false, true)) { + var peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("game-design-service") + || !peer.isInNamespace(NAMESPACE)) + throw new SecurityException( + "Authenticated controlled Game Design socket peer required"); + identityService.associate( + NAMESPACE, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + local.target().canonicalVersionId(), + local.target().gameDesignVersionRowId(), + UUID.randomUUID()); + } + super.sendMessage(message); + } + }, + headers); + } + }; + worldHandlers.addService( + ServerInterceptors.intercept( + new WorldAuthoredSourceIntakeGrpcService(intakeService, NAMESPACE), + new GrpcPeerIdentityInterceptor(), + associationHook)); + intakeClient.init(); + var request = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + NAMESPACE, + UUID.randomUUID(), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest()); + var response = intakeClient.intake(request); + var retained = intakes.read(NAMESPACE, request.intakeRequestId()).orElseThrow(); + assertThat(response.receiptDigest()).isEqualTo(retained.receiptDigest()); + var identity = + identities + .readByCanonicalTarget( + NAMESPACE, + source.canonicalTenantId(), + local.target().canonicalVersionId(), + local.target().gameDesignVersionRowId()) + .orElseThrow(); + assertThat(identity.sourceIntakeReceipt()).isEqualTo(retained); + } + } + + private Local gameDesignLocal() { + var schema = "game_design_" + UUID.randomUUID().toString().replace("-", ""); + var data = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + data.setSchema(schema); + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_game_design") + .placeholders(Map.of("serviceSchema", schema)) + .locations(migrationLocation("game-design")) + .load() + .migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + var manager = new DataSourceTransactionManager(data); + var game = new Game(); + game.setTenantId(UUID.randomUUID().toString()); + game.setName("Genuine selected intake Game"); + game.setDescription("Persisted Game Design identity and source provenance"); + var savedGame = + java.util.Objects.requireNonNull( + transaction(manager).execute(ignored -> new GameRepository(dsl).save(game))); + var version = new Version(); + version.setTenantId(savedGame.getTenantId()); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + var saved = + java.util.Objects.requireNonNull( + transaction(manager).execute(ignored -> new VersionRepository(dsl).save(version))); + var target = + new DraftCommitBinding.TargetProof( + saved.getCanonicalTenantId(), + saved.getCanonicalVersionId(), + saved.getId(), + saved.getTenantId(), + saved.getIdentitySourceGameRowId(), + saved.getIdentitySourceGameTenantKey(), + saved.getIdentitySourceProvenanceKind()); + assertThat(new GameplayRuleSourceRepository(dsl).readGenesis(target)).isPresent(); + return new Local(dsl, manager, target); + } + + private GameLogicStore gameLogicStore() { + var schema = "game_logic_" + UUID.randomUUID().toString().replace("-", ""); + var data = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + data.setSchema(schema); + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_game_logic") + .placeholders(Map.of("serviceSchema", schema)) + .locations(migrationLocation("game-logic")) + .load() + .migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + return new GameLogicStore(dsl, new DataSourceTransactionManager(data)); + } + + private WorldStore worldStore() { + var schema = "world_management_" + UUID.randomUUID().toString().replace("-", ""); + var data = + new DriverManagerDataSource( + WORLD_POSTGRES.getJdbcUrl(), WORLD_POSTGRES.getUsername(), WORLD_POSTGRES.getPassword()); + data.setSchema(schema); + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_world_management") + .placeholders(Map.of("serviceSchema", schema)) + .locations(migrationLocation("world-management")) + .load() + .migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + return new WorldStore(dsl, new DataSourceTransactionManager(data)); + } + + private DraftCommitBinding binding(Local local, String admissionTag) throws Exception { + var genesis = new GameDesignSourceRepository(local.dsl()).readGenesis(local.target()).orElseThrow(); + String baseCommitId = "genesis:" + genesis.policy().receiptId(); + UUID commit = UUID.randomUUID(); + UUID region = UUID.randomUUID(); + UUID zone = UUID.randomUUID(); + UUID room = UUID.randomUUID(); + var familyCounts = new java.util.ArrayList(); + for (var family : + List.of( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING)) { + familyCounts.add( + WorldFreshGraphFamilyCount.newBuilder() + .setFamily(family) + .setCount( + family == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION + || family == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE + || family == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM + ? 1 + : 0) + .build()); + } + var inbound = WorldInboundSourceClosureDeclaration.newBuilder().setSchemaVersion(1); + for (WorldInboundSourceFamily family : + List.of( + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT, + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT, + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION, + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING, + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK, + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE, + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING)) { + inbound.addFamilyCounts( + WorldInboundSourceFamilyCount.newBuilder().setFamily(family).setCount(0)); + } + var declaration = + WorldFreshGraphDeclaration.newBuilder() + .setTenantId(local.target().canonicalTenantId().toString()) + .setVersionId(local.target().canonicalVersionId().toString()) + .addAllFamilyCounts(familyCounts) + .setInboundSourceClosure(inbound.build()) + .setStartLocation( + net.firedevops.firemud.worldmanagement.v1.RoomTemplateRef.newBuilder() + .setTenantId(local.target().canonicalTenantId().toString()) + .setVersionId(local.target().canonicalVersionId().toString()) + .setRoomTemplateId(room.toString())) + .build(); + var mutations = + List.of( + mutation(commit, room, region, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .setRoom( + RoomDesignMutation.newBuilder() + .setName("Controlled room") + .setZoneId(zone.toString()) + .setDescription("Controlled original World source fixture")) + .build(), + mutation(commit, zone, region, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE) + .setZone( + ZoneDesignMutation.newBuilder() + .setName("Controlled zone") + .setRegionId(region.toString())) + .build(), + mutation( + commit, + region, + region, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setRegion( + RegionDesignMutation.newBuilder() + .setName("Controlled region") + .setWeather("clear") + .setShardId(1)) + .setFreshGraphDeclaration(declaration) + .build()); + var revisions = new java.util.ArrayList(); + var units = new java.util.ArrayList(); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(new GameplayRuleManifest.AdmissionTag(admissionTag)))); + units.add( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.SCOPE, + local.target().canonicalVersionId().toString(), + GameplayRuleSource.SCOPE, + "effective", + "0")); + for (var mutation : mutations) { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisions.size()), + UUID.fromString(mutation.getLogicalRevisionId()), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + JsonFormat.printer().omittingInsignificantWhitespace().print(mutation))); + var family = + mutation.getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + units.add( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + mutation.getAggregateId(), + "AGGREGATE", + mutation.getAggregateId(), + "0")); + units.add( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + mutation.getAggregateId(), + "REGION_SUBTREE", + mutation.getScopeId(), + "0")); + } + return DraftCommitBinding.create( + local.target(), UUID.randomUUID(), commit, baseCommitId, revisions, units); + } + + private static WorldDesignMutationRevision.Builder mutation( + UUID commit, UUID id, UUID region, WorldDesignAggregateType type) { + return WorldDesignMutationRevision.newBuilder() + .setCommitId(commit.toString()) + .setLogicalRevisionId(UUID.randomUUID().toString()) + .setAggregateId(id.toString()) + .setAggregateType(type) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(region.toString()); + } + + private static TransactionTemplate transaction(Local local) { + return transaction(local.transactions()); + } + + private static TransactionTemplate transaction(DataSourceTransactionManager manager) { + var tx = new TransactionTemplate(manager); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return tx; + } + + private static String migrationLocation(String service) { + var directoryName = service + "-service"; + var current = Path.of("").toAbsolutePath(); + while (current != null) { + var migrations = + current + .resolve("services") + .resolve(directoryName) + .resolve("src/main/resources/db/migration"); + if (Files.isDirectory(migrations)) return "filesystem:" + migrations; + current = current.getParent(); + } + throw new IllegalStateException("Service migration directory is unavailable: " + service); + } + + private static Server startServer( + TestPki pki, TestIdentity identity, MutableHandlerRegistry handlers) throws Exception { + var builder = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .fallbackHandlerRegistry(handlers) + .maxInboundMessageSize(20 * 1024 * 1024) + .maxInboundMetadataSize(AccountOriginalDraftOrderGrpcCodec.MAX_METADATA_BYTES) + .sslContext( + GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()) + .trustManager(pki.ca().toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()); + return builder.build().start(); + } + + private static void registerServices( + MutableHandlerRegistry handlers, + Map methodCounts, + BindableService... services) { + for (var service : services) + handlers.addService( + ServerInterceptors.intercept( + service, new GrpcPeerIdentityInterceptor(), countingInterceptor(methodCounts))); + } + + private static ServerInterceptor countingInterceptor(Map methodCounts) { + return new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + String method = call.getMethodDescriptor().getFullMethodName().toLowerCase(Locale.ROOT); + methodCounts.forEach( + (fragment, count) -> { + if (method.contains(fragment)) count.incrementAndGet(); + }); + return next.startCall(call, headers); + } + }; + } + + private static String loopback(Server server) { + return "127.0.0.1:" + server.getPort(); + } + + private static void stopAll(Server... servers) throws InterruptedException { + for (var server : servers) if (server != null) server.shutdownNow(); + var terminated = true; + for (var server : servers) + if (server != null) terminated &= server.awaitTermination(5, TimeUnit.SECONDS); + if (!terminated) throw new IllegalStateException("Test owner server did not stop"); + } + + private record Local( + DSLContext dsl, + DataSourceTransactionManager transactions, + DraftCommitBinding.TargetProof target) {} + + private record GameLogicStore(DSLContext dsl, DataSourceTransactionManager transactions) {} + + private record WorldStore(DSLContext dsl, DataSourceTransactionManager transactions) {} + + private record TestIdentity(Path certificate, Path key) { + CommonGrpcClientProperties properties(Path ca) { + var result = new CommonGrpcClientProperties(); + result.setPlaintext(false); + result.setCertChain(certificate.toString()); + result.setPrivateKey(key.toString()); + result.setCaCert(ca.toString()); + return result; + } + } + + /** Ephemeral test CA and controlled same-namespace Account, GD, World, and GL identities. */ + private static final class TestPki { + private final Path ca; + private final TestIdentity accountServer; + private final TestIdentity accountClient; + private final TestIdentity gameDesignServer; + private final TestIdentity gameDesignClient; + private final TestIdentity worldServer; + private final TestIdentity worldClient; + private final TestIdentity gameLogicServer; + private final TestIdentity gameLogicClient; + + TestPki(Path root) throws Exception { + Files.createDirectories(root); + var generator = java.security.KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + var caKeys = generator.generateKeyPair(); + var caName = new org.bouncycastle.asn1.x500.X500Name("CN=Test-only genuine intake proof CA"); + var now = java.time.Instant.now(); + var caBuilder = + new org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder( + caName, + java.math.BigInteger.ONE, + java.util.Date.from(now.minusSeconds(60)), + java.util.Date.from(now.plusSeconds(3600)), + caName, + caKeys.getPublic()); + caBuilder.addExtension( + org.bouncycastle.asn1.x509.Extension.basicConstraints, + true, + new org.bouncycastle.asn1.x509.BasicConstraints(true)); + caBuilder.addExtension( + org.bouncycastle.asn1.x509.Extension.keyUsage, + true, + new org.bouncycastle.asn1.x509.KeyUsage(org.bouncycastle.asn1.x509.KeyUsage.keyCertSign)); + var caCertificate = + new org.bouncycastle.cert.jcajce.JcaX509CertificateConverter() + .getCertificate( + caBuilder.build( + new org.bouncycastle.operator.jcajce.JcaContentSignerBuilder("SHA256withRSA") + .build(caKeys.getPrivate()))); + ca = pem(root.resolve("ca.pem"), caCertificate); + accountServer = issue(root, "account-service", true, caKeys, caCertificate); + accountClient = issue(root, "account-service", false, caKeys, caCertificate); + gameDesignServer = issue(root, "game-design-service", true, caKeys, caCertificate); + gameDesignClient = issue(root, "game-design-service", false, caKeys, caCertificate); + worldServer = issue(root, "world-management-service", true, caKeys, caCertificate); + worldClient = issue(root, "world-management-service", false, caKeys, caCertificate); + gameLogicServer = issue(root, "game-logic-service", true, caKeys, caCertificate); + gameLogicClient = issue(root, "game-logic-service", false, caKeys, caCertificate); + } + + Path ca() { + return ca; + } + + TestIdentity accountServer() { + return accountServer; + } + + TestIdentity accountClient() { + return accountClient; + } + + TestIdentity gameDesignServer() { + return gameDesignServer; + } + + TestIdentity gameDesignClient() { + return gameDesignClient; + } + + TestIdentity worldServer() { + return worldServer; + } + + TestIdentity worldClient() { + return worldClient; + } + + TestIdentity gameLogicServer() { + return gameLogicServer; + } + + TestIdentity gameLogicClient() { + return gameLogicClient; + } + + private static TestIdentity issue( + Path root, + String service, + boolean server, + java.security.KeyPair caKeys, + java.security.cert.X509Certificate caCertificate) + throws Exception { + var generator = java.security.KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + var keys = generator.generateKeyPair(); + var now = java.time.Instant.now(); + var builder = + new org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder( + caCertificate, + new java.math.BigInteger(120, new java.security.SecureRandom()), + java.util.Date.from(now.minusSeconds(60)), + java.util.Date.from(now.plusSeconds(3600)), + new org.bouncycastle.asn1.x500.X500Name("CN=" + service), + keys.getPublic()); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.basicConstraints, + true, + new org.bouncycastle.asn1.x509.BasicConstraints(false)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.keyUsage, + false, + new org.bouncycastle.asn1.x509.KeyUsage( + org.bouncycastle.asn1.x509.KeyUsage.digitalSignature + | org.bouncycastle.asn1.x509.KeyUsage.keyEncipherment)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.extendedKeyUsage, + false, + new org.bouncycastle.asn1.x509.ExtendedKeyUsage( + server + ? org.bouncycastle.asn1.x509.KeyPurposeId.id_kp_serverAuth + : org.bouncycastle.asn1.x509.KeyPurposeId.id_kp_clientAuth)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, + false, + new org.bouncycastle.asn1.x509.GeneralNames( + new org.bouncycastle.asn1.x509.GeneralName[] { + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.uniformResourceIdentifier, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/" + service), + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.dNSName, "localhost"), + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.iPAddress, "127.0.0.1") + })); + var certificate = + new org.bouncycastle.cert.jcajce.JcaX509CertificateConverter() + .getCertificate( + builder.build( + new org.bouncycastle.operator.jcajce.JcaContentSignerBuilder("SHA256withRSA") + .build(caKeys.getPrivate()))); + String prefix = service + (server ? "-server" : "-client"); + return new TestIdentity( + pem(root.resolve(prefix + ".crt"), certificate), + pem(root.resolve(prefix + ".key"), keys.getPrivate())); + } + + private static Path pem(Path path, Object value) throws Exception { + try (var writer = + new org.bouncycastle.openssl.jcajce.JcaPEMWriter(Files.newBufferedWriter(path))) { + writer.writeObject(value); + } + return path; + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java new file mode 100644 index 0000000000..cb8b8d8174 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java @@ -0,0 +1,445 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * V1009 PostgreSQL storage proof definitions. The predecessor selection table and upstream + * authority are explicit fixtures; this is not composed authoring or authenticated intake proof. + */ +@Testcontainers(disabledWithoutDocker = true) +class SelectedDraftGameLogicReceiptPostgresIntegrationTest { + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void migrationPreservesHistoricalSelectionAndReceiptReadbackIsImmutableAndExact() { + var value = receiptFixture(); + var fixture = fixture(value); + var dsl = fixture.dsl(); + var repository = new SelectedDraftGameLogicReceiptRepository(dsl); + fixture.tx().executeWithoutResult(ignored -> repository.retain(value)); + fixture + .tx() + .executeWithoutResult( + ignored -> + assertThat(repository.retain(value).receipt().canonicalBytes()) + .containsExactly(value.receipt().canonicalBytes())); + var recovered = repository.read(value.selection(), value.authorization()).orElseThrow(); + assertThat(recovered.receipt().canonicalBytes()) + .containsExactly(value.receipt().canonicalBytes()); + assertThat(recovered.authorization().canonicalBytes()) + .containsExactly(value.authorization().canonicalBytes()); + // Publication may advance the mutable lifecycle epoch. Exact retained content recovery uses + // the original authenticated epoch, not a new mutation authorization against current state. + dsl.execute( + "UPDATE version SET version_state_epoch = version_state_epoch + 1 WHERE id = ?", + value.selection().target().gameDesignVersionRowId()); + var publicationRead = repository.readForPublication(publicationBinding(value)); + assertThat(publicationRead).isPresent(); + assertThat(publicationRead.orElseThrow().receipt().canonicalBytes()) + .containsExactly(value.receipt().canonicalBytes()); + assertThat( + dsl.fetchSingle("SELECT count(*) FROM game_design_selected_game_logic_receipt") + .get(0, Long.class)) + .isEqualTo(1L); + assertThat( + dsl.fetchSingle( + "SELECT selection_json FROM game_design_authored_draft_publish_selection") + .get(0, String.class)) + .isEqualTo(value.selection().canonicalJson()); + var changed = + new GameLogicIntakeAuthorizationBinding( + value.authorization().operationId(), + UUID.randomUUID(), + value.authorization().intakeRequestId(), + value.authorization().actorAccountId(), + value.authorization().source(), + value.authorization().sources()); + assertThatThrownBy(() -> repository.read(value.selection(), changed)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_design_selected_game_logic_receipt SET receipt_bytes = ?", + new byte[] {1})) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy(() -> dsl.execute("DELETE FROM game_design_selected_game_logic_receipt")) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy( + () -> + insert( + dsl, + value, + value.selection().canonicalBytes(), + value.receipt().canonicalBytes())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + + @Test + void publicationReadUsesExactTenantAndRequestAndRejectsChangedVersionOrPatchScope() { + var value = receiptFixture(); + var fixture = fixture(value); + var dsl = fixture.dsl(); + var repository = new SelectedDraftGameLogicReceiptRepository(dsl); + fixture.tx().executeWithoutResult(ignored -> repository.retain(value)); + + assertThat( + repository.readForPublication( + PublicationDigestRequestBinding.full( + value.selection().intent().canonicalTenantId().toString(), + Long.toString(value.selection().target().gameDesignVersionRowId()), + "different-request"))) + .isEmpty(); + assertThat( + repository.readForPublication( + PublicationDigestRequestBinding.full( + UUID.randomUUID().toString(), + Long.toString(value.selection().target().gameDesignVersionRowId()), + value.selection().intent().publishRequestId()))) + .isEmpty(); + assertThatThrownBy( + () -> + repository.readForPublication( + PublicationDigestRequestBinding.full( + value.selection().intent().canonicalTenantId().toString(), + Long.toString(value.selection().target().gameDesignVersionRowId() + 1), + value.selection().intent().publishRequestId()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("does not match publication request"); + assertThatThrownBy( + () -> + repository.readForPublication( + PublicationDigestRequestBinding.patch( + value.selection().intent().canonicalTenantId().toString(), + "1", + "patch-1", + value.selection().intent().publishRequestId()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("FULL_VERSION"); + assertThat( + dsl.fetchSingle("SELECT count(*) FROM game_design_selected_game_logic_receipt") + .get(0, Long.class)) + .isEqualTo(1L); + } + + @Test + void publicationReadFailsClosedWhenNumericVersionRowNoLongerMatchesSelection() { + var value = receiptFixture(); + var fixture = fixture(value); + var repository = new SelectedDraftGameLogicReceiptRepository(fixture.dsl()); + fixture.tx().executeWithoutResult(ignored -> repository.retain(value)); + fixture + .dsl() + .execute( + "UPDATE version SET canonical_version_id = ? WHERE id = ?", + UUID.randomUUID(), + value.selection().target().gameDesignVersionRowId()); + + assertThatThrownBy(() -> repository.readForPublication(publicationBinding(value))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Version row proof unavailable"); + } + + @Test + void publicationReadFailsClosedOnConflictingRetainedAuthorizationBytes() { + var value = receiptFixture(); + var fixture = fixture(value); + var dsl = fixture.dsl(); + var repository = new SelectedDraftGameLogicReceiptRepository(dsl); + fixture.tx().executeWithoutResult(ignored -> repository.retain(value)); + var conflictingAuthorization = + new GameLogicIntakeAuthorizationBinding( + value.authorization().operationId(), + UUID.randomUUID(), + value.authorization().intakeRequestId(), + value.authorization().actorAccountId(), + value.authorization().source(), + value.authorization().sources()); + // The trigger is bypassed to inject a changed but valid authorization payload. The database + // CHECK constraints remain active; the repository must detect the digest mismatch on read. + dsl.execute( + "ALTER TABLE game_design_selected_game_logic_receipt DISABLE TRIGGER trg_gd_selected_game_logic_receipt"); + dsl.execute( + "UPDATE game_design_selected_game_logic_receipt SET authorization_bytes = ?", + conflictingAuthorization.canonicalBytes()); + + assertThatThrownBy(() -> repository.readForPublication(publicationBinding(value))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Exact RETAINED Account settlement required"); + assertThat( + dsl.fetchSingle("SELECT receipt_bytes FROM game_design_selected_game_logic_receipt") + .get(0, byte[].class)) + .containsExactly(value.receipt().canonicalBytes()); + } + + @Test + void missingReceiptIsAbsentAndChangedSelectionOrOversizedReceiptCannotInsert() { + var value = receiptFixture(); + var fixture = fixture(value); + var dsl = fixture.dsl(); + assertThat( + new SelectedDraftGameLogicReceiptRepository(dsl) + .read(value.selection(), value.authorization())) + .isEmpty(); + assertThatThrownBy(() -> insert(dsl, value, new byte[] {1}, value.receipt().canonicalBytes())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy( + () -> insert(dsl, value, value.selection().canonicalBytes(), new byte[16778241])) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat( + dsl.fetchSingle("SELECT count(*) FROM game_design_selected_game_logic_receipt") + .get(0, Long.class)) + .isZero(); + } + + @Test + void ownerTransactionRechecksCompleteSelectionBeforeInsertingDerivedReceipt() { + var value = receiptFixture(); + var fixture = fixture(value); + String altered = + value.selection().canonicalJson().replace("\"notes\":\"\"", "\"notes\":\"changed\""); + String digest = + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.digest( + altered.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + // This predecessor fixture permits fault injection; the real V43 owner rejects rewriting. + fixture + .dsl() + .execute( + "UPDATE game_design_authored_draft_publish_selection SET selection_json = ?, selection_digest = ?", + altered, + digest); + var repository = new SelectedDraftGameLogicReceiptRepository(fixture.dsl()); + assertThatThrownBy(() -> fixture.tx().execute(status -> repository.retain(value))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("changed before receipt retention"); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT count(*) FROM game_design_selected_game_logic_receipt") + .get(0, Long.class)) + .isZero(); + } + + private static Fixture fixture(SelectedDraftGameLogicReceipt value) { + String schema = "receipt_" + UUID.randomUUID().toString().replace("-", ""); + var data = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + DSL.using(data, SQLDialect.POSTGRES).execute("CREATE SCHEMA " + schema); + var scoped = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl() + + (POSTGRES.getJdbcUrl().contains("?") ? "&" : "?") + + "currentSchema=" + + schema, + POSTGRES.getUsername(), + POSTGRES.getPassword()); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(scoped), SQLDialect.POSTGRES); + dsl.execute( + "CREATE TABLE game_design_authored_draft_publish_selection (canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, publish_request_id TEXT NOT NULL, selection_digest TEXT NOT NULL, selection_json TEXT NOT NULL, game_design_version_row_id BIGINT NOT NULL, game_design_version_tenant_key TEXT NOT NULL, source_game_row_id BIGINT NOT NULL, source_game_tenant_key TEXT NOT NULL, source_provenance_kind TEXT NOT NULL, version_state_epoch BIGINT NOT NULL, selected_commit_request_id UUID NOT NULL, selected_commit_id UUID NOT NULL, selected_commit_digest TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (canonical_tenant_id, canonical_version_id, publish_request_id))"); + dsl.execute( + "CREATE TABLE game (id BIGINT PRIMARY KEY, tenant_id TEXT, canonical_tenant_id UUID, tenant_identity_provenance_kind TEXT, tenant_identity_source_game_id BIGINT, tenant_identity_source_legacy_tenant_id TEXT)"); + dsl.execute( + "CREATE TABLE version (id BIGINT PRIMARY KEY, tenant_id TEXT, canonical_tenant_id UUID, canonical_version_id UUID, identity_source_game_row_id BIGINT, identity_source_game_tenant_key TEXT, identity_source_provenance_kind TEXT, version_state_epoch BIGINT)"); + var target = value.selection().target(); + dsl.execute( + "INSERT INTO game VALUES (?, ?, ?, ?, ?, ?)", + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.canonicalTenantId(), + target.sourceProvenanceKind(), + target.sourceGameRowId(), + target.sourceGameTenantKey()); + dsl.execute( + "INSERT INTO version VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.canonicalTenantId(), + target.canonicalVersionId(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind(), + Long.parseLong(value.selection().intent().expectedVersionStateEpoch())); + selection(dsl, value); + Flyway.configure() + .dataSource(scoped) + .defaultSchema(schema) + .schemas(schema) + .baselineOnMigrate(true) + .baselineVersion("1008") + .target("1009") + .placeholders(Map.of("serviceSchema", schema)) + .load() + .migrate(); + var tx = new TransactionTemplate(new DataSourceTransactionManager(scoped)); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return new Fixture(dsl, tx); + } + + private static void selection(DSLContext dsl, SelectedDraftGameLogicReceipt value) { + var target = value.selection().target(); + var intent = value.selection().intent(); + dsl.execute( + "INSERT INTO game_design_authored_draft_publish_selection (canonical_tenant_id, canonical_version_id, publish_request_id, selection_digest, selection_json, game_design_version_row_id, game_design_version_tenant_key, source_game_row_id, source_game_tenant_key, source_provenance_kind, version_state_epoch, selected_commit_request_id, selected_commit_id, selected_commit_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + value.selection().intent().canonicalTenantId(), + value.selection().intent().canonicalVersionId(), + value.selection().intent().publishRequestId(), + value.selection().digest(), + value.selection().canonicalJson(), + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind(), + Long.parseLong(intent.expectedVersionStateEpoch()), + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()); + } + + private static void insert( + DSLContext dsl, + SelectedDraftGameLogicReceipt value, + byte[] selectionBytes, + byte[] receiptBytes) { + dsl.execute( + "INSERT INTO game_design_selected_game_logic_receipt (canonical_tenant_id, canonical_version_id, publish_request_id, selection_digest, workflow_identity, selection_bytes, authorization_bytes, authorization_digest, receipt_bytes, receipt_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + value.selection().intent().canonicalTenantId(), + value.selection().intent().canonicalVersionId(), + value.selection().intent().publishRequestId(), + value.selection().digest(), + value.workflowIdentity(), + selectionBytes, + value.authorization().canonicalBytes(), + value.authorization().digest(), + receiptBytes, + value.receipt().digest()); + } + + private static SelectedDraftGameLogicReceipt receiptFixture() { + UUID actor = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "private", 2, "private", "NEW_GAME_ROW"); + var binding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var source = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", binding.canonicalJson(), + "bindingDigest", binding.digest(), + "sourceEpoch", "1", + "inheritedCommitId", "", + "genesisReceiptId", UUID.randomUUID().toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + var auth = + new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + source, + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + var selected = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + "publish-1", + "1", + "", + binding.requestId(), + binding.commitId(), + binding.digest()), + target, + binding, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + binding.requestId(), + binding.commitId(), + binding.digest(), + "[]", + OffsetDateTime.parse("2026-10-08T00:00:00Z"))); + var terminal = + GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation("test", auth), + source.canonicalBytes(), + source.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + return new SelectedDraftGameLogicReceipt( + AuthoredDraftPublishSelection.fromStored(selected.canonicalJson(), selected.digest()), + auth, + new AccountGameLogicIntakeSettlementEvidence(terminal)); + } + + private static PublicationDigestRequestBinding publicationBinding( + SelectedDraftGameLogicReceipt value) { + return PublicationDigestRequestBinding.full( + value.selection().intent().canonicalTenantId().toString(), + Long.toString(value.selection().target().gameDesignVersionRowId()), + value.selection().intent().publishRequestId()); + } + + private record Fixture(DSLContext dsl, TransactionTemplate tx) {} +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadGrpcServiceTest.java new file mode 100644 index 0000000000..d0c6fc3757 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadGrpcServiceTest.java @@ -0,0 +1,61 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedGameplayRuleSourceRequest; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedGameplayRuleSourceResponse; +import org.junit.jupiter.api.Test; + +class GameDesignGameplayRuleSourceReadGrpcServiceTest { + @Test + void authenticatesExactAccountOrGameLogicBeforeDecoding() { + var owner = mock(GameDesignGameplayRuleSourceReadService.class); + var service = new GameDesignGameplayRuleSourceReadGrpcService(owner, "test"); + var malformed = ReadSelectedGameplayRuleSourceRequest.newBuilder().setSchemaVersion(-1).build(); + var missing = new Collector(); + service.readSelectedGameplayRuleSource(malformed, missing); + assertThat(missing.error).isEqualTo(Status.Code.UNAUTHENTICATED); + for (String caller : new String[] {"game-design-service", "world-management-service"}) { + var result = new Collector(); + peer("test", caller).run(() -> service.readSelectedGameplayRuleSource(malformed, result)); + assertThat(result.error).isEqualTo(Status.Code.PERMISSION_DENIED); + } + for (String caller : new String[] {"account-service", "game-logic-service"}) { + var result = new Collector(); + peer("test", caller).run(() -> service.readSelectedGameplayRuleSource(malformed, result)); + assertThat(result.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + } + verifyNoInteractions(owner); + } + + private static Context peer(String namespace, String service) { + return Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow()); + } + + private static final class Collector + implements StreamObserver { + Status.Code error; + + public void onNext(ReadSelectedGameplayRuleSourceResponse value) { + throw new AssertionError("No positive result"); + } + + public void onError(Throwable value) { + error = Status.fromThrowable(value).getCode(); + } + + public void onCompleted() { + throw new AssertionError("No successful read"); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadServiceTest.java new file mode 100644 index 0000000000..5ec5b3b4e6 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadServiceTest.java @@ -0,0 +1,195 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionStatus; + +class GameDesignGameplayRuleSourceReadServiceTest { + @Test + void exportsOnlyTheCompleteOwnerReadForTheExactSynchronizedBinding() { + var repository = mock(GameplayRuleSourceRepository.class); + var transactions = mock(PlatformTransactionManager.class); + when(transactions.getTransaction(any())).thenReturn(mock(TransactionStatus.class)); + var permissions = + mock(net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadClient.class); + org.mockito.Mockito.doAnswer( + invocation -> + new net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadEvidence( + invocation.getArgument(0))) + .when(permissions) + .read(any()); + var owner = + new GameDesignGameplayRuleSourceReadService(repository, transactions, permissions, "test"); + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "private", 2, "private", "NEW_GAME_ROW"); + var selected = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload( + new GameplayRuleManifest.AdmissionTag("gameplay")))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.SCOPE, + target.canonicalVersionId().toString(), + GameplayRuleSource.SCOPE, + GameplayRuleSource.SCOPE_ID, + "0"))); + var snapshot = + new GameplayRuleSnapshot( + selected, "1", null, UUID.randomUUID(), GameplayRuleSource.replay(List.of(), selected)); + when(repository.requireCompleteForGameLogic(target, selected.commitId())).thenReturn(snapshot); + var request = + GameplayRuleSourceReadEvidence.Request.forAccountSourceScope( + "test", + new net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadScope( + "test", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + selected, + "spiffe://firemud/ns/test/sa/account-service", + "GAME_LOGIC_INTAKE_SOURCE")); + var result = new AtomicReference(); + asAccount(() -> result.set(owner.read(request))); + assertThat(result.get().source().canonicalBytes()).containsExactly(snapshot.canonicalBytes()); + assertThat(result.get().source().manifest()).isEqualTo(snapshot.manifest()); + verify(repository).requireCompleteForGameLogic(target, selected.commitId()); + var ordered = org.mockito.Mockito.inOrder(permissions, transactions, repository); + ordered.verify(permissions).read(any()); + ordered.verify(transactions).getTransaction(any()); + ordered.verify(repository).requireCompleteForGameLogic(target, selected.commitId()); + + org.mockito.Mockito.clearInvocations(permissions, transactions, repository); + org.mockito.Mockito.doThrow(io.grpc.Status.PERMISSION_DENIED.asRuntimeException()) + .when(permissions) + .read(any()); + assertThatThrownBy(() -> asAccount(() -> owner.read(request))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + org.mockito.Mockito.verifyNoInteractions(transactions, repository); + org.mockito.Mockito.doAnswer( + invocation -> + new net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadEvidence( + invocation.getArgument(0))) + .when(permissions) + .read(any()); + + var actor = UUID.randomUUID(); + var finalAuthorization = + new net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + new net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource( + snapshot.canonicalJson()), + List.of( + new net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding + .SourceEvidence( + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding + .SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + var finalizedRequest = + GameplayRuleSourceReadEvidence.Request.forFinalizedIntake("test", finalAuthorization); + asGameLogic( + () -> + assertThat(owner.read(finalizedRequest).source().canonicalBytes()) + .containsExactly(snapshot.canonicalBytes())); + org.mockito.Mockito.clearInvocations(permissions, transactions, repository); + assertThatThrownBy(() -> asAccount(() -> owner.read(finalizedRequest))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + assertThatThrownBy(() -> asGameLogic(() -> owner.read(request))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + org.mockito.Mockito.verifyNoInteractions(permissions, transactions, repository); + org.mockito.Mockito.doReturn(null).when(permissions).read(any()); + assertThatThrownBy(() -> asAccount(() -> owner.read(request))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + org.mockito.Mockito.verifyNoInteractions(transactions, repository); + org.mockito.Mockito.doThrow(io.grpc.Status.UNAVAILABLE.asRuntimeException()) + .when(permissions) + .read(any()); + assertThatThrownBy(() -> asAccount(() -> owner.read(request))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + org.mockito.Mockito.verifyNoInteractions(transactions, repository); + org.mockito.Mockito.doAnswer( + invocation -> { + var original = + invocation + . + getArgument(0); + return new net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadEvidence( + net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadEvidence.Request + .create( + original.targetNamespace(), + original.intendedReader(), + original.purpose(), + original.proof())); + }) + .when(permissions) + .read(any()); + assertThatThrownBy(() -> asAccount(() -> owner.read(request))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + org.mockito.Mockito.verifyNoInteractions(transactions, repository); + org.mockito.Mockito.doAnswer( + invocation -> + new net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadEvidence( + invocation.getArgument(0))) + .when(permissions) + .read(any()); + + when(repository.requireCompleteForGameLogic(target, selected.commitId())) + .thenThrow(new IllegalStateException("GAMEPLAY_RULE_LEGACY_COMMAND_SOURCE_NOT_CONVERGED")); + assertThatThrownBy(() -> asAccount(() -> owner.read(request))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("NOT_CONVERGED"); + } + + private static void asAccount(Runnable action) { + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/account-service").orElseThrow()) + .run(action); + } + + private static void asGameLogic(Runnable action) { + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-logic-service") + .orElseThrow()) + .run(action); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandServiceTest.java new file mode 100644 index 0000000000..2ddf72cc8b --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandServiceTest.java @@ -0,0 +1,318 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +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.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationEvidence; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class SelectedDraftGameLogicIntakeCommandServiceTest { + private static final String CREDENTIAL = "original-creator-credential-never-persisted"; + + @Test + void verifiesImmutableSelectionThenAuthorizesAndRetainsOutsideSqlInOrder() { + var value = SelectedDraftGameLogicReceiptTest.fixture(); + var request = request(value.selection()); + var authorization = authorizationFor(value, request); + var expectedReceipt = receiptFor(value.selection(), authorization); + var account = mock(GameLogicIntakeAuthorizationClient.class); + var events = new ArrayList(); + when(account.authorize(any(), anyString())) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(call.getArgument(0, GameLogicIntakeAuthorizationEvidence.Request.class)) + .isSameAs(request); + assertThat(call.getArgument(1, String.class)).isEqualTo(CREDENTIAL); + events.add("account.authorize"); + return GameLogicIntakeAuthorizationEvidence.Result.authorized(request, authorization); + }); + var service = + new SelectedDraftGameLogicIntakeCommandService( + selected -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + events.add("selection.read"); + return Optional.of(value.selection()); + }, + account, + (selected, retainedAuthorization) -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(selected.canonicalBytes()) + .containsExactly(value.selection().canonicalBytes()); + assertThat(retainedAuthorization.canonicalBytes()) + .containsExactly(authorization.canonicalBytes()); + events.add("receipt.retain"); + return expectedReceipt; + }, + "test"); + + var receipt = service.authorizeAndRetain(value.selection(), request, CREDENTIAL); + + assertThat(receipt).isSameAs(expectedReceipt); + assertThat(events).containsExactly("selection.read", "account.authorize", "receipt.retain"); + verify(account, never()).recover(any(), anyString()); + } + + @Test + void rejectsMalformedRequestOrChangedDurableSelectionBeforeAccountRpc() { + var value = SelectedDraftGameLogicReceiptTest.fixture(); + var account = mock(GameLogicIntakeAuthorizationClient.class); + var retainCalls = new AtomicInteger(); + var readerCalls = new AtomicInteger(); + var service = + new SelectedDraftGameLogicIntakeCommandService( + selected -> { + readerCalls.incrementAndGet(); + return Optional.of(selected); + }, + account, + (selected, authorization) -> { + retainCalls.incrementAndGet(); + return value; + }, + "test"); + + var wrongNamespace = + new GameLogicIntakeAuthorizationEvidence.Request( + 1, + "other", + UUID.randomUUID(), + UUID.randomUUID(), + value.selection().selectedCommit().canonicalBytes()); + assertThatThrownBy( + () -> service.authorizeAndRetain(value.selection(), wrongNamespace, CREDENTIAL)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("namespace"); + var wrongSelectedBinding = request(SelectedDraftGameLogicReceiptTest.fixture().selection()); + assertThatThrownBy( + () -> service.authorizeAndRetain(value.selection(), wrongSelectedBinding, CREDENTIAL)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("selected Draft binding"); + assertThat(readerCalls).hasValue(0); + + String alteredJson = + value.selection().canonicalJson().replace("\"notes\":\"\"", "\"notes\":\"changed\""); + var changedStoredSelection = + AuthoredDraftPublishSelection.fromStored( + alteredJson, + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.digest( + alteredJson.getBytes(StandardCharsets.UTF_8))); + var changedSelectionService = + new SelectedDraftGameLogicIntakeCommandService( + ignored -> Optional.of(changedStoredSelection), + account, + (selected, authorization) -> { + retainCalls.incrementAndGet(); + return value; + }, + "test"); + assertThatThrownBy( + () -> + changedSelectionService.authorizeAndRetain( + value.selection(), request(value.selection()), CREDENTIAL)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("immutable selection"); + + assertThat(retainCalls).hasValue(0); + verifyNoInteractions(account); + } + + @Test + void rejectsChangedResponseTransportCorrelationBeforeReceiptRetention() { + var value = SelectedDraftGameLogicReceiptTest.fixture(); + var request = request(value.selection()); + var changedResponseRequest = + new GameLogicIntakeAuthorizationEvidence.Request( + request.schemaVersion(), + request.targetNamespace(), + UUID.randomUUID(), + request.intakeRequestId(), + request.selectedDraftBinding()); + var account = mock(GameLogicIntakeAuthorizationClient.class); + when(account.authorize(any(), anyString())) + .thenReturn( + GameLogicIntakeAuthorizationEvidence.Result.authorized( + changedResponseRequest, authorizationFor(value, changedResponseRequest))); + var retainCalls = new AtomicInteger(); + var service = + new SelectedDraftGameLogicIntakeCommandService( + ignored -> Optional.of(value.selection()), + account, + (selected, authorization) -> { + retainCalls.incrementAndGet(); + return value; + }, + "test"); + + assertThatThrownBy(() -> service.authorizeAndRetain(value.selection(), request, CREDENTIAL)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("request readback conflict"); + + assertThat(retainCalls).hasValue(0); + } + + @Test + void rejectsAuthorizationWhoseSourceDoesNotMatchExactRequest() { + var value = SelectedDraftGameLogicReceiptTest.fixture(); + var other = SelectedDraftGameLogicReceiptTest.fixture(); + var request = request(value.selection()); + var changedAuthorization = authorizationFor(other, request); + var response = mock(GameLogicIntakeAuthorizationEvidence.Result.class); + when(response.request()).thenReturn(request); + when(response.outcome()).thenReturn(GameLogicIntakeAuthorizationEvidence.Outcome.FINALIZED); + when(response.authorization()).thenReturn(Optional.of(changedAuthorization)); + var account = mock(GameLogicIntakeAuthorizationClient.class); + when(account.recover(any(), anyString())).thenReturn(response); + var retainCalls = new AtomicInteger(); + var service = + new SelectedDraftGameLogicIntakeCommandService( + ignored -> Optional.of(value.selection()), + account, + (selected, authorization) -> { + retainCalls.incrementAndGet(); + return value; + }, + "test"); + + assertThatThrownBy(() -> service.recoverAndRetain(value.selection(), request, CREDENTIAL)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("differs from exact request"); + + assertThat(retainCalls).hasValue(0); + } + + @Test + void sanitizesProducerFailuresWithoutReflectingProtectedCredential() { + var value = SelectedDraftGameLogicReceiptTest.fixture(); + var account = mock(GameLogicIntakeAuthorizationClient.class); + when(account.authorize(any(), anyString())).thenThrow(new IllegalStateException(CREDENTIAL)); + var service = + new SelectedDraftGameLogicIntakeCommandService( + ignored -> Optional.of(value.selection()), + account, + (selected, authorization) -> value, + "test"); + + assertThatThrownBy( + () -> + service.authorizeAndRetain( + value.selection(), request(value.selection()), CREDENTIAL)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account intake authorization denied or unavailable") + .hasMessageNotContaining(CREDENTIAL); + } + + @Test + void reservedAndAbortedRecoveryNeverCreatesReceipt() { + var value = SelectedDraftGameLogicReceiptTest.fixture(); + var request = request(value.selection()); + var account = mock(GameLogicIntakeAuthorizationClient.class); + var reserved = response(request, GameLogicIntakeAuthorizationEvidence.Outcome.RESERVED); + var aborted = response(request, GameLogicIntakeAuthorizationEvidence.Outcome.ABORTED); + when(account.recover(any(), anyString())).thenReturn(reserved, aborted); + var retainCalls = new AtomicInteger(); + var service = + new SelectedDraftGameLogicIntakeCommandService( + ignored -> Optional.of(value.selection()), + account, + (selected, authorization) -> { + retainCalls.incrementAndGet(); + return value; + }, + "test"); + + for (int i = 0; i < 2; i++) { + assertThatThrownBy(() -> service.recoverAndRetain(value.selection(), request, CREDENTIAL)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not finalized"); + } + + assertThat(retainCalls).hasValue(0); + } + + @Test + void exactRecoveryUsesCallerIntakeIdentityWithoutIssuingAnotherAuthorization() { + var value = SelectedDraftGameLogicReceiptTest.fixture(); + var request = request(value.selection()); + var authorization = authorizationFor(value, request); + var expectedReceipt = receiptFor(value.selection(), authorization); + var account = mock(GameLogicIntakeAuthorizationClient.class); + when(account.recover(any(), anyString())) + .thenAnswer( + call -> { + assertThat(call.getArgument(0, GameLogicIntakeAuthorizationEvidence.Request.class)) + .isSameAs(request); + assertThat(call.getArgument(1, String.class)).isEqualTo(CREDENTIAL); + return GameLogicIntakeAuthorizationEvidence.Result.authorized(request, authorization); + }); + var service = + new SelectedDraftGameLogicIntakeCommandService( + ignored -> Optional.of(value.selection()), + account, + (selected, retainedAuthorization) -> expectedReceipt, + "test"); + + assertThat(service.recoverAndRetain(value.selection(), request, CREDENTIAL)) + .isSameAs(expectedReceipt); + assertThat(request.intakeRequestId()).isEqualTo(authorization.intakeRequestId()); + verify(account, never()).authorize(any(), anyString()); + } + + private static GameLogicIntakeAuthorizationEvidence.Result response( + GameLogicIntakeAuthorizationEvidence.Request request, + GameLogicIntakeAuthorizationEvidence.Outcome outcome) { + var result = mock(GameLogicIntakeAuthorizationEvidence.Result.class); + when(result.request()).thenReturn(request); + when(result.outcome()).thenReturn(outcome); + when(result.authorization()).thenReturn(Optional.empty()); + return result; + } + + private static GameLogicIntakeAuthorizationEvidence.Request request( + AuthoredDraftPublishSelection selection) { + return GameLogicIntakeAuthorizationEvidence.Request.create( + "test", UUID.randomUUID(), selection.selectedCommit()); + } + + private static GameLogicIntakeAuthorizationBinding authorizationFor( + SelectedDraftGameLogicReceipt fixture, GameLogicIntakeAuthorizationEvidence.Request request) { + var original = fixture.authorization(); + return new GameLogicIntakeAuthorizationBinding( + original.operationId(), + original.fenceId(), + request.intakeRequestId(), + original.actorAccountId(), + original.source(), + original.sources()); + } + + private static SelectedDraftGameLogicReceipt receiptFor( + AuthoredDraftPublishSelection selection, GameLogicIntakeAuthorizationBinding authorization) { + var terminal = + GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation("test", authorization), + authorization.source().canonicalBytes(), + authorization.source().manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + return new SelectedDraftGameLogicReceipt( + selection, authorization, new AccountGameLogicIntakeSettlementEvidence(terminal)); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptServiceTest.java new file mode 100644 index 0000000000..428881c867 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptServiceTest.java @@ -0,0 +1,200 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementReadClient; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeRetainClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeRetainEvidence; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class SelectedDraftGameLogicReceiptServiceTest { + @Test + void ownerCallsOutsideSqlThenStoresExactAccountReceiptAndRecoversWithoutRpc() { + var value = SelectedDraftGameLogicReceiptTest.fixture(); + var repository = mock(SelectedDraftGameLogicReceiptRepository.class); + var transactions = mock(PlatformTransactionManager.class); + var gl = mock(GameLogicIntakeRetainClient.class); + var account = mock(AccountGameLogicIntakeSettlementReadClient.class); + when(repository.read(any(), any())).thenReturn(Optional.empty()); + when(repository.retain(any())).thenReturn(value); + when(gl.retain(any())) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return new GameLogicIntakeRetainEvidence( + call.getArgument(0), value.receipt().terminal()); + }); + when(account.read(any())) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return new AccountGameLogicIntakeSettlementReadEvidence( + call.getArgument(0), value.receipt()); + }); + var service = + new SelectedDraftGameLogicReceiptService( + repository, + ignored -> Optional.of(value.selection()), + transactions, + gl, + account, + "test"); + assertThat(service.retain(value.selection(), value.authorization())).isSameAs(value); + var order = inOrder(repository, gl, account, transactions); + order.verify(repository).read(any(), any()); + order.verify(gl).retain(any()); + order.verify(account).read(any()); + order.verify(transactions).getTransaction(any()); + order.verify(repository).retain(any()); + clearInvocations(gl, account, transactions); + when(repository.read(any(), any())).thenReturn(Optional.of(value)); + assertThat(service.retain(value.selection(), value.authorization())).isSameAs(value); + verifyNoInteractions(gl, account, transactions); + } + + @Test + void missingSelectionAndWrongCompleteSelectionDenyBeforeRpcOrTransaction() { + var value = SelectedDraftGameLogicReceiptTest.fixture(); + var repository = mock(SelectedDraftGameLogicReceiptRepository.class); + var transactions = mock(PlatformTransactionManager.class); + var gl = mock(GameLogicIntakeRetainClient.class); + var account = mock(AccountGameLogicIntakeSettlementReadClient.class); + var service = + new SelectedDraftGameLogicReceiptService( + repository, ignored -> Optional.empty(), transactions, gl, account, "test"); + assertThatThrownBy(() -> service.retain(value.selection(), value.authorization())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("SELECTION_UNAVAILABLE"); + assertThatThrownBy( + () -> + service.retain( + value.selection(), SelectedDraftGameLogicReceiptTest.fixture().authorization())) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(repository, transactions, gl, account); + } + + @Test + void abortedOrMissingRemoteResultCannotStoreReceipt() { + var value = SelectedDraftGameLogicReceiptTest.fixture(); + var repository = mock(SelectedDraftGameLogicReceiptRepository.class); + when(repository.read(any(), any())).thenReturn(Optional.empty()); + var transactions = mock(PlatformTransactionManager.class); + var gl = mock(GameLogicIntakeRetainClient.class); + var account = mock(AccountGameLogicIntakeSettlementReadClient.class); + var service = + new SelectedDraftGameLogicReceiptService( + repository, + ignored -> Optional.of(value.selection()), + transactions, + gl, + account, + "test"); + assertThatThrownBy(() -> service.retain(value.selection(), value.authorization())) + .isInstanceOf(IllegalStateException.class); + when(gl.retain(any())) + .thenAnswer( + call -> + new GameLogicIntakeRetainEvidence( + call.getArgument(0), + GameLogicGameplayRuleIntakeTerminal.aborted( + new GameLogicGameplayRuleIntakeOperation("test", value.authorization())))); + when(account.read(any())) + .thenAnswer( + call -> + new AccountGameLogicIntakeSettlementReadEvidence( + call.getArgument(0), + new AccountGameLogicIntakeSettlementEvidence( + GameLogicGameplayRuleIntakeTerminal.aborted( + new GameLogicGameplayRuleIntakeOperation( + "test", value.authorization()))))); + assertThatThrownBy(() -> service.retain(value.selection(), value.authorization())) + .isInstanceOf(IllegalArgumentException.class); + verify(account).read(any()); + verifyNoInteractions(transactions); + verify(repository, never()).retain(any()); + } + + @Test + void lostAccountSettlementAcknowledgementRecoversOriginalIntakeWithNewTransportCorrelation() { + var value = SelectedDraftGameLogicReceiptTest.fixture(); + var repository = mock(SelectedDraftGameLogicReceiptRepository.class); + when(repository.read(any(), any())).thenReturn(Optional.empty()); + when(repository.retain(any())).thenReturn(value); + var transactions = mock(PlatformTransactionManager.class); + var gl = mock(GameLogicIntakeRetainClient.class); + var account = mock(AccountGameLogicIntakeSettlementReadClient.class); + when(gl.retain(any())) + .thenAnswer( + call -> + new GameLogicIntakeRetainEvidence(call.getArgument(0), value.receipt().terminal())); + when(account.read(any())) + .thenThrow(new IllegalStateException("lost settlement acknowledgement")); + var service = + new SelectedDraftGameLogicReceiptService( + repository, + ignored -> Optional.of(value.selection()), + transactions, + gl, + account, + "test"); + assertThatThrownBy(() -> service.retain(value.selection(), value.authorization())) + .hasMessage("lost settlement acknowledgement"); + verify(repository, never()).retain(any()); + verifyNoInteractions(transactions); + doAnswer( + call -> + new AccountGameLogicIntakeSettlementReadEvidence( + call.getArgument(0), value.receipt())) + .when(account) + .read(any()); + assertThat(service.retain(value.selection(), value.authorization())).isSameAs(value); + var requests = org.mockito.ArgumentCaptor.forClass(GameLogicIntakeRetainEvidence.Request.class); + verify(gl, times(2)).retain(requests.capture()); + assertThat(requests.getAllValues().get(0).correlationId()) + .isNotEqualTo(requests.getAllValues().get(1).correlationId()); + for (var request : requests.getAllValues()) { + assertThat(request.originalAuthorizationBytes()) + .containsExactly(value.authorization().canonicalBytes()); + } + } + + @Test + void changedRetainedSelectionDeniesEvenWhenTenantVersionAndIntakeMatch() { + var value = SelectedDraftGameLogicReceiptTest.fixture(); + var alteredJson = + value.selection().canonicalJson().replace("\"notes\":\"\"", "\"notes\":\"changed\""); + var changed = + net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.fromStored( + alteredJson, + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.digest( + alteredJson.getBytes(java.nio.charset.StandardCharsets.UTF_8))); + var repository = mock(SelectedDraftGameLogicReceiptRepository.class); + var transactions = mock(PlatformTransactionManager.class); + var gl = mock(GameLogicIntakeRetainClient.class); + var account = mock(AccountGameLogicIntakeSettlementReadClient.class); + var service = + new SelectedDraftGameLogicReceiptService( + repository, ignored -> Optional.of(changed), transactions, gl, account, "test"); + assertThatThrownBy(() -> service.retain(value.selection(), value.authorization())) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(repository, transactions, gl, account); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptTest.java new file mode 100644 index 0000000000..073eecba48 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptTest.java @@ -0,0 +1,224 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import org.junit.jupiter.api.Test; + +/** Canonical fixtures stipulate upstream authority; these are not authenticated owner proof. */ +class SelectedDraftGameLogicReceiptTest { + @Test + void retainsExactSelectionIntakeAndReceiptOutsideAuthoredBytes() { + var receipt = fixture(); + byte[] before = receipt.selection().selectedCommit().canonicalBytes(); + var recovered = + new SelectedDraftGameLogicReceipt( + AuthoredDraftPublishSelection.fromStored( + receipt.selection().canonicalJson(), receipt.selection().digest()), + GameLogicIntakeAuthorizationBinding.fromStored( + receipt.authorization().canonicalBytes()), + AccountGameLogicIntakeSettlementEvidence.fromStored( + receipt.receipt().canonicalBytes())); + recovered.requireExactRequest(receipt.selection(), receipt.authorization()); + assertThat(recovered.receipt().canonicalBytes()) + .containsExactly(receipt.receipt().canonicalBytes()); + assertThat(recovered.selection().selectedCommit().canonicalBytes()).containsExactly(before); + assertThat(recovered.workflowIdentity()) + .isEqualTo("publish:" + receipt.authorization().tenantId() + ":publish-request:publish-1"); + } + + @Test + void rejectsAbortedDifferentSelectionAndChangedAuthorizationRetry() { + var value = fixture(); + var abort = + GameLogicGameplayRuleIntakeTerminal.aborted( + new GameLogicGameplayRuleIntakeOperation("test", value.authorization())); + assertThatThrownBy( + () -> + new SelectedDraftGameLogicReceipt( + value.selection(), + value.authorization(), + new AccountGameLogicIntakeSettlementEvidence(abort))) + .isInstanceOf(IllegalArgumentException.class); + var other = fixture(); + assertThatThrownBy( + () -> + SelectedDraftGameLogicReceipt.requireExactSelection( + value.selection(), other.authorization())) + .isInstanceOf(IllegalArgumentException.class); + var changed = + new GameLogicIntakeAuthorizationBinding( + value.authorization().operationId(), + UUID.randomUUID(), + value.authorization().intakeRequestId(), + value.authorization().actorAccountId(), + value.authorization().source(), + value.authorization().sources()); + assertThatThrownBy(() -> value.requireExactRequest(value.selection(), changed)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> new SelectedDraftGameLogicReceipt(value.selection(), changed, value.receipt())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsChangedAuthoredInputWithSameTenantVersionRequestAndCommitIds() { + var value = fixture(); + var original = value.authorization().source().binding(); + var revision = original.revisions().getFirst(); + var changedBinding = + DraftCommitBinding.create( + original.target(), + original.requestId(), + original.commitId(), + original.baseCommitId(), + List.of( + new DraftCommitBinding.RevisionPayload( + revision.revisionOrder(), + revision.revisionId(), + revision.owner(), + "{\"changed\":true}")), + original.affectedUnits()); + var changedSource = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + changedBinding.canonicalJson(), + "bindingDigest", + changedBinding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + GameplayRuleManifest.tree(value.authorization().source().snapshotJson()) + .path("genesisReceiptId") + .textValue(), + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))); + var changed = + new GameLogicIntakeAuthorizationBinding( + value.authorization().operationId(), + value.authorization().fenceId(), + value.authorization().intakeRequestId(), + value.authorization().actorAccountId(), + changedSource, + value.authorization().sources()); + assertThatThrownBy( + () -> SelectedDraftGameLogicReceipt.requireExactSelection(value.selection(), changed)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("complete selected Draft binding"); + } + + static SelectedDraftGameLogicReceipt fixture() { + UUID actor = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "private", 2, "private", "NEW_GAME_ROW"); + var binding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var source = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))); + var auth = + new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + source, + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + var selected = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + "publish-1", + "1", + "", + binding.requestId(), + binding.commitId(), + binding.digest()), + target, + binding, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + binding.requestId(), + binding.commitId(), + binding.digest(), + "[]", + OffsetDateTime.parse("2026-10-08T00:00:00Z"))); + var terminal = + GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation("test", auth), + source.canonicalBytes(), + source.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + return new SelectedDraftGameLogicReceipt( + AuthoredDraftPublishSelection.fromStored(selected.canonicalJson(), selected.digest()), + auth, + new AccountGameLogicIntakeSettlementEvidence(terminal)); + } +} diff --git a/services/game-logic-service/build.gradle.kts b/services/game-logic-service/build.gradle.kts index dbd48d7512..963092bfd6 100644 --- a/services/game-logic-service/build.gradle.kts +++ b/services/game-logic-service/build.gradle.kts @@ -10,4 +10,29 @@ dependencies { compileOnly(libs.spotbugs.annotations) implementation(project(":common-security")) annotationProcessor(libs.spring.boot.configuration.processor) + add("crossServiceTestCompileOnly", libs.spotbugs.annotations) + add( + "crossServiceTestImplementation", + project(mapOf("path" to ":account-service", "configuration" to "accountOriginalOrderProof")) + ) + add( + "crossServiceTestImplementation", + project(mapOf("path" to ":game-design-service", "configuration" to "gameDesignClassesProof")) + ) + add("crossServiceTestImplementation", libs.bouncycastle.pkix) + add("crossServiceTestImplementation", "io.grpc:grpc-util:${libs.versions.grpc.get()}") +} + +// The genuine GDS-to-GL proof consumes owner classes without adding foreign owners to GL runtime. +val gameLogicClassesProofJar by tasks.registering(Jar::class) { + archiveClassifier.set("classes-proof") + dependsOn(tasks.named("classes")) + from(sourceSets.main.get().output.classesDirs) +} + +val gameLogicClassesProof by configurations.creating { + isCanBeConsumed = true + isCanBeResolved = false + extendsFrom(configurations.implementation.get()) + outgoing.artifact(gameLogicClassesProofJar) } diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcService.java new file mode 100644 index 0000000000..abea6e6c67 --- /dev/null +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcService.java @@ -0,0 +1,80 @@ +package net.firedevops.firemud.gamelogic.sourceintake; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeRetainEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeRetainProtoCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamelogic.v1.GameLogicGameplayRuleIntakeServiceGrpc; +import net.firedevops.firemud.gamelogic.v1.RetainGameplayRuleIntakeRequest; +import net.firedevops.firemud.gamelogic.v1.RetainGameplayRuleIntakeResponse; + +/** Standalone, unregistered transport for the existing owner-local intake service. */ +public final class GameLogicGameplayRuleIntakeGrpcService + extends GameLogicGameplayRuleIntakeServiceGrpc.GameLogicGameplayRuleIntakeServiceImplBase { + private final GameLogicGameplayRuleIntakeService owner; + private final String namespace; + + public GameLogicGameplayRuleIntakeGrpcService( + GameLogicGameplayRuleIntakeService owner, String namespace) { + this.owner = Objects.requireNonNull(owner, "owner"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical namespace required"); + } + this.namespace = namespace; + } + + @Override + public void retainGameplayRuleIntake( + RetainGameplayRuleIntakeRequest request, + StreamObserver observer) { + try { + requireGameDesignPeer(namespace); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + + final GameLogicIntakeRetainEvidence.Request decoded; + try { + decoded = GameLogicIntakeRetainProtoCodec.fromRequest(request); + if (!namespace.equals(decoded.targetNamespace())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + + try { + var terminal = owner.retain(decoded.binding()); + observer.onNext( + GameLogicIntakeRetainProtoCodec.toResponse( + new GameLogicIntakeRetainEvidence(decoded, terminal))); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + observer.onError(failure); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } + + private static void requireGameDesignPeer(String namespace) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + } + if (!peer.isInNamespace(namespace) + || !peer.isService("game-design-service") + || !("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Design workload required") + .asRuntimeException(); + } + } +} diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeRepository.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeRepository.java new file mode 100644 index 0000000000..97c00a0990 --- /dev/null +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeRepository.java @@ -0,0 +1,109 @@ +package net.firedevops.firemud.gamelogic.sourceintake; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Owner-local immutable intake evidence storage. All writes require the caller's local transaction. + */ +public final class GameLogicGameplayRuleIntakeRepository { + private static final long OPERATION_LOCK_NAMESPACE = 0x474c494e54414b45L; + + private final DSLContext dsl; + + public GameLogicGameplayRuleIntakeRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** Serializes fresh retention and explicit abort before a row exists and on exact retries. */ + public void lockOperation(UUID operationId) { + requireReadCommittedTransaction(); + dsl.fetch( + "select pg_catalog.pg_advisory_xact_lock(pg_catalog.hashtextextended(?, ?))", + "game-logic-source-intake:" + operationId, + OPERATION_LOCK_NAMESPACE); + } + + /** Immutable readback is independent of Account's later settlement state. */ + public Optional findTerminal(UUID operationId) { + Record row = + dsl.fetchOne( + "SELECT * FROM game_logic_gameplay_rule_intake_terminal WHERE operation_id = ?", + Objects.requireNonNull(operationId, "operationId")); + if (row == null) return Optional.empty(); + byte[] terminalBytes = row.get("terminal_bytes", byte[].class); + var terminal = GameLogicGameplayRuleIntakeTerminal.fromStored(terminalBytes); + var operation = terminal.operation(); + var authorization = operation.authorization(); + var sourceBinding = authorization.source().binding(); + if (!operationId.equals(row.get("operation_id", UUID.class)) + || !operation.targetNamespace().equals(row.get("target_namespace", String.class)) + || !authorization.actorAccountId().equals(row.get("actor_account_id", UUID.class)) + || !authorization.tenantId().equals(row.get("canonical_tenant_id", UUID.class)) + || !authorization.versionId().equals(row.get("canonical_version_id", UUID.class)) + || !sourceBinding.commitId().equals(row.get("selected_commit_id", UUID.class)) + || !operation.digest().equals(row.get("operation_digest", String.class)) + || !authorization.digest().equals(row.get("authorization_digest", String.class)) + || !terminal.outcome().name().equals(row.get("outcome", String.class)) + || !terminal.digest().equals(row.get("terminal_digest", String.class)) + || !java.util.Arrays.equals( + authorization.canonicalBytes(), row.get("authorization_bytes", byte[].class)) + || !same(terminal.selectedSourceBytes(), row.get("selected_source_bytes", byte[].class)) + || !same(terminal.manifestBytes(), row.get("manifest_bytes", byte[].class)) + || !Objects.equals( + terminal.selectedSourceDigest(), row.get("selected_source_digest", String.class)) + || !Objects.equals(terminal.manifestDigest(), row.get("manifest_digest", String.class))) { + throw new IllegalStateException("GL_GAMEPLAY_RULE_INTAKE_READBACK_CONFLICT"); + } + return Optional.of(terminal); + } + + /** One INSERT stores order, exact GD provenance, manifest, and RETAINED terminal atomically. */ + public void insertTerminal(GameLogicGameplayRuleIntakeTerminal terminal) { + requireReadCommittedTransaction(); + Objects.requireNonNull(terminal, "terminal"); + var operation = terminal.operation(); + var authorization = operation.authorization(); + dsl.execute( + "INSERT INTO game_logic_gameplay_rule_intake_terminal (operation_id, target_namespace, " + + "actor_account_id, canonical_tenant_id, canonical_version_id, selected_commit_id, " + + "operation_digest, authorization_digest, authorization_bytes, outcome, " + + "selected_source_bytes, selected_source_digest, manifest_bytes, manifest_digest, " + + "terminal_bytes, terminal_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + authorization.operationId(), + operation.targetNamespace(), + authorization.actorAccountId(), + authorization.tenantId(), + authorization.versionId(), + authorization.source().binding().commitId(), + operation.digest(), + authorization.digest(), + terminal.authorizationBytes(), + terminal.outcome().name(), + terminal.selectedSourceBytes(), + terminal.selectedSourceDigest(), + terminal.manifestBytes(), + terminal.manifestDigest(), + terminal.canonicalBytes(), + terminal.digest()); + } + + private static void requireReadCommittedTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !Integer.valueOf( + org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "GL intake storage requires an owner READ COMMITTED transaction"); + } + } + + private static boolean same(byte[] left, byte[] right) { + return java.util.Arrays.equals(left, right); + } +} diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java new file mode 100644 index 0000000000..9a67751c45 --- /dev/null +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java @@ -0,0 +1,198 @@ +package net.firedevops.firemud.gamelogic.sourceintake; + +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered owner-local exact-source intake. The caller is the same-namespace GD workload; + * Account and GD reads complete before this service opens its independent retention transaction. + */ +public final class GameLogicGameplayRuleIntakeService { + private final GameLogicGameplayRuleIntakeRepository repository; + private final GameLogicIntakeAuthorizationReadClient accountAuthorizationReader; + private final GameplayRuleSourceReadClient gameDesignSourceReader; + private final String workloadNamespace; + private final TransactionTemplate ownerTransaction; + + public GameLogicGameplayRuleIntakeService( + GameLogicGameplayRuleIntakeRepository repository, + PlatformTransactionManager transactionManager, + GameLogicIntakeAuthorizationReadClient accountAuthorizationReader, + GameplayRuleSourceReadClient gameDesignSourceReader, + String workloadNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.accountAuthorizationReader = + Objects.requireNonNull(accountAuthorizationReader, "accountAuthorizationReader"); + this.gameDesignSourceReader = + Objects.requireNonNull(gameDesignSourceReader, "gameDesignSourceReader"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Logic workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + ownerTransaction = + new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); + ownerTransaction.setName("game-logic-gameplay-rule-source-intake"); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + /** Returns the original terminal for exact retries, including after Account settles the order. */ + public GameLogicGameplayRuleIntakeTerminal retain( + net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding authorization) { + var operation = requestOperation(authorization); + requireNoActiveTransaction(); + Optional prior = + repository.findTerminal(authorization.operationId()); + if (prior.isPresent()) return exactTerminal(prior.orElseThrow(), operation); + + var authorizationRequest = + GameLogicIntakeAuthorizationReadEvidence.Request.create(workloadNamespace, authorization); + var held = accountAuthorizationReader.read(authorizationRequest); + if (held == null || !authorizationRequest.equals(held.request())) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact HELD Account intake authorization required") + .asRuntimeException(); + } + + var sourceRequest = + GameplayRuleSourceReadEvidence.Request.forFinalizedIntake(workloadNamespace, authorization); + var sourceEvidence = gameDesignSourceReader.read(sourceRequest); + if (sourceEvidence == null + || !sourceRequest.equals(sourceEvidence.request()) + || !Arrays.equals( + authorization.source().canonicalBytes(), sourceEvidence.source().canonicalBytes())) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact complete selected GD source differs from Account authorization") + .asRuntimeException(); + } + + byte[] sourceBytes = sourceEvidence.source().canonicalBytes(); + byte[] manifestBytes = + sourceEvidence.source().manifest().canonicalJson().getBytes(StandardCharsets.UTF_8); + var retained = + GameLogicGameplayRuleIntakeTerminal.retained(operation, sourceBytes, manifestBytes); + return ownerTransaction.execute( + status -> { + repository.lockOperation(authorization.operationId()); + var concurrent = repository.findTerminal(authorization.operationId()); + if (concurrent.isPresent()) return exactTerminal(concurrent.orElseThrow(), operation); + repository.insertTerminal(retained); + return repository + .findTerminal(authorization.operationId()) + .filter(value -> Arrays.equals(value.canonicalBytes(), retained.canonicalBytes())) + .orElseThrow( + () -> + new IllegalStateException( + "GL_GAMEPLAY_RULE_INTAKE_COMMIT_READBACK_MISMATCH")); + }); + } + + /** No value means there is no actual owner terminal; ABORTED is an explicit durable terminal. */ + public Optional readTerminal( + net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding authorization) { + GameLogicGameplayRuleIntakeTerminalReadService.requirePeer(workloadNamespace); + var operation = new GameLogicGameplayRuleIntakeOperation(workloadNamespace, authorization); + requireNoActiveTransaction(); + return repository + .findTerminal(authorization.operationId()) + .map(value -> exactTerminal(value, operation)); + } + + /** Explicit owner abort is serialized with retention and never inferred from a read failure. */ + public GameLogicGameplayRuleIntakeTerminal abort( + net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding authorization) { + var operation = requestOperation(authorization); + requireNoActiveTransaction(); + Optional prior = + repository.findTerminal(authorization.operationId()); + if (prior.isPresent()) return exactTerminal(prior.orElseThrow(), operation); + + var authorizationRequest = + GameLogicIntakeAuthorizationReadEvidence.Request.create(workloadNamespace, authorization); + var held = accountAuthorizationReader.read(authorizationRequest); + if (held == null || !authorizationRequest.equals(held.request())) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact HELD Account intake authorization required for explicit abort") + .asRuntimeException(); + } + + return ownerTransaction.execute( + status -> { + repository.lockOperation(authorization.operationId()); + var concurrent = repository.findTerminal(authorization.operationId()); + if (concurrent.isPresent()) return exactTerminal(concurrent.orElseThrow(), operation); + var aborted = GameLogicGameplayRuleIntakeTerminal.aborted(operation); + repository.insertTerminal(aborted); + return repository + .findTerminal(authorization.operationId()) + .filter(value -> Arrays.equals(value.canonicalBytes(), aborted.canonicalBytes())) + .orElseThrow( + () -> + new IllegalStateException("GL_GAMEPLAY_RULE_INTAKE_ABORT_READBACK_MISMATCH")); + }); + } + + private GameLogicGameplayRuleIntakeOperation requestOperation( + net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding authorization) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + if (!peer.isInNamespace(workloadNamespace) + || !peer.isService("game-design-service") + || !("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service") + .equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Design workload required") + .asRuntimeException(); + } + if (AccountSelectedPublicationOrderCredentials.CONTEXT_KEY.get() != null) { + throw Status.PERMISSION_DENIED + .withDescription("Creator publication credentials cannot accompany GL source intake") + .asRuntimeException(); + } + if (authorization == null) { + throw Status.INVALID_ARGUMENT + .withDescription("Original GL intake authorization required") + .asRuntimeException(); + } + return new GameLogicGameplayRuleIntakeOperation(workloadNamespace, authorization); + } + + private static GameLogicGameplayRuleIntakeTerminal exactTerminal( + GameLogicGameplayRuleIntakeTerminal terminal, + GameLogicGameplayRuleIntakeOperation requested) { + if (!Arrays.equals(terminal.operation().canonicalBytes(), requested.canonicalBytes())) { + throw Status.ALREADY_EXISTS + .withDescription("GL intake operation identity was reused with changed authorization") + .asRuntimeException(); + } + return terminal; + } + + private static void requireNoActiveTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("GL intake owner reads must run outside SQL") + .asRuntimeException(); + } + } +} diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcService.java new file mode 100644 index 0000000000..b572a1f0c6 --- /dev/null +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcService.java @@ -0,0 +1,54 @@ +package net.firedevops.firemud.gamelogic.sourceintake; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeTerminalReadGrpcCodec; +import net.firedevops.firemud.gamelogic.v1.GameLogicGameplayRuleIntakeTerminalReadServiceGrpc; +import net.firedevops.firemud.gamelogic.v1.ReadGameplayRuleIntakeTerminalRequest; +import net.firedevops.firemud.gamelogic.v1.ReadGameplayRuleIntakeTerminalResponse; + +/** No automatic registration; authenticate Account before parsing caller-carried evidence. */ +public final class GameLogicGameplayRuleIntakeTerminalReadGrpcService + extends GameLogicGameplayRuleIntakeTerminalReadServiceGrpc + .GameLogicGameplayRuleIntakeTerminalReadServiceImplBase { + private final GameLogicGameplayRuleIntakeTerminalReadService owner; + private final String namespace; + + public GameLogicGameplayRuleIntakeTerminalReadGrpcService( + GameLogicGameplayRuleIntakeTerminalReadService owner, String namespace) { + this.owner = Objects.requireNonNull(owner); + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + } + + @Override + public void readGameplayRuleIntakeTerminal( + ReadGameplayRuleIntakeTerminalRequest request, + StreamObserver observer) { + try { + GameLogicGameplayRuleIntakeTerminalReadService.requirePeer(namespace); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + final net.firedevops.firemud.common.gamelogic.GameLogicIntakeTerminalReadEvidence.Request + decoded; + try { + decoded = GameLogicIntakeTerminalReadGrpcCodec.fromRequest(request); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + try { + observer.onNext(GameLogicIntakeTerminalReadGrpcCodec.toResponse(owner.read(decoded))); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + observer.onError(failure); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } +} diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadService.java new file mode 100644 index 0000000000..a9638ec90d --- /dev/null +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadService.java @@ -0,0 +1,52 @@ +package net.firedevops.firemud.gamelogic.sourceintake; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone Account-only read over actual immutable Game Logic storage. */ +public final class GameLogicGameplayRuleIntakeTerminalReadService { + private final GameLogicGameplayRuleIntakeRepository repository; + private final String namespace; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The injected repository is an intentionally shared service collaborator.") + public GameLogicGameplayRuleIntakeTerminalReadService( + GameLogicGameplayRuleIntakeRepository repository, String namespace) { + this.repository = Objects.requireNonNull(repository); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + } + + public GameLogicIntakeTerminalReadEvidence read( + GameLogicIntakeTerminalReadEvidence.Request request) { + requirePeer(namespace); + if (!namespace.equals(request.targetNamespace())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw Status.FAILED_PRECONDITION.asRuntimeException(); + var original = new GameLogicGameplayRuleIntakeOperation(namespace, request.binding()); + var terminal = repository.findTerminal(request.binding().operationId()); + terminal.ifPresent( + value -> { + if (!Arrays.equals(original.canonicalBytes(), value.operation().canonicalBytes())) + throw Status.ALREADY_EXISTS.asRuntimeException(); + }); + return new GameLogicIntakeTerminalReadEvidence(request, terminal); + } + + static void requirePeer(String namespace) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + if (!("spiffe://firemud/ns/" + namespace + "/sa/account-service").equals(peer.uri())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + } +} diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationSourceReadService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationSourceReadService.java new file mode 100644 index 0000000000..6f5265daaf --- /dev/null +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationSourceReadService.java @@ -0,0 +1,236 @@ +package net.firedevops.firemud.gamelogic.sourceintake; + +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding; +import net.firedevops.firemud.common.gamelogic.GameplayAbilitySchemaProjection; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered read of the genuine retained Game Logic source for one exact publication lookup. + * This service does not create intake authority, read Account state, repair source, or activate a + * digest transport. + */ +public final class GameLogicPublicationSourceReadService { + public static final int DIGEST_SCHEMA_VERSION = 1; + public static final String CANONICALIZATION = "RFC8785"; + + private final GameLogicGameplayRuleIntakeRepository repository; + private final String workloadNamespace; + + public GameLogicPublicationSourceReadService( + GameLogicGameplayRuleIntakeRepository repository, String workloadNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Logic workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + /** + * Returns digests only after the exact operation's actual RETAINED terminal is read back. + * + *

The repository verifies the indexed operation identity and all stored bytes. This method + * additionally correlates that readback with the complete original authorization and exact + * publication selection before deriving either digest. + */ + public Result read(GameLogicPublicationSourceReadBinding binding) { + requirePeer(workloadNamespace); + if (binding == null) { + throw Status.INVALID_ARGUMENT + .withDescription("Exact full-version publication source-read binding required") + .asRuntimeException(); + } + requireNoActiveTransaction(); + + GameLogicIntakeAuthorizationBinding authorization = binding.authorization(); + GameLogicGameplayRuleIntakeOperation requestedOperation = + new GameLogicGameplayRuleIntakeOperation(workloadNamespace, authorization); + GameLogicGameplayRuleIntakeTerminal terminal = + repository + .findTerminal(authorization.operationId()) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Exact retained Game Logic source is unavailable") + .asRuntimeException()); + + requireExactRetainedTerminal(terminal, requestedOperation, authorization); + GameplayRuleSelectedSource retainedSource = + new GameplayRuleSelectedSource( + new String(terminal.selectedSourceBytes(), StandardCharsets.UTF_8)); + byte[] manifestBytes = + retainedSource.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8); + if (!Arrays.equals(manifestBytes, terminal.manifestBytes())) { + throw Status.ALREADY_EXISTS + .withDescription("Retained Game Logic manifest differs from exact selected source") + .asRuntimeException(); + } + + String manifestDigest = GameplayRuleManifest.sha256(manifestBytes); + String abilitySchemaDigest = GameplayAbilitySchemaProjection.digest(retainedSource.manifest()); + return new Result( + binding, + terminal, + retainedSource, + manifestDigest, + abilitySchemaDigest, + DIGEST_SCHEMA_VERSION, + CANONICALIZATION); + } + + private static void requireExactRetainedTerminal( + GameLogicGameplayRuleIntakeTerminal terminal, + GameLogicGameplayRuleIntakeOperation requestedOperation, + GameLogicIntakeAuthorizationBinding authorization) { + if (!Arrays.equals(terminal.operation().canonicalBytes(), requestedOperation.canonicalBytes()) + || !Arrays.equals(terminal.authorizationBytes(), authorization.canonicalBytes())) { + throw Status.ALREADY_EXISTS + .withDescription("Retained Game Logic operation differs from exact publication source") + .asRuntimeException(); + } + if (terminal.outcome() != GameLogicGameplayRuleIntakeTerminal.Outcome.RETAINED) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact Game Logic source operation did not retain source") + .asRuntimeException(); + } + if (!Arrays.equals(terminal.selectedSourceBytes(), authorization.source().canonicalBytes())) { + throw Status.ALREADY_EXISTS + .withDescription("Retained Game Logic source differs from Account authorization") + .asRuntimeException(); + } + if (!authorization + .source() + .binding() + .target() + .canonicalTenantId() + .equals(authorization.tenantId()) + || !authorization + .source() + .binding() + .target() + .canonicalVersionId() + .equals(authorization.versionId())) { + throw Status.ALREADY_EXISTS + .withDescription("Retained Game Logic commit scope differs from Account authorization") + .asRuntimeException(); + } + } + + private static void requirePeer(String namespace) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + } + if (!peer.isInNamespace(namespace) + || !peer.isService("game-design-service") + || !("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Design workload required") + .asRuntimeException(); + } + } + + private static void requireNoActiveTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Publication source reads must run outside SQL") + .asRuntimeException(); + } + } + + /** + * Immutable source-read result whose provenance is the exact object returned by owner storage. + */ + public static final class Result { + private final GameLogicPublicationSourceReadBinding binding; + private final GameLogicGameplayRuleIntakeTerminal terminal; + private final GameplayRuleSelectedSource selectedSource; + private final String manifestDigest; + private final String abilitySchemaDigest; + private final int digestSchemaVersion; + private final String canonicalization; + + private Result( + GameLogicPublicationSourceReadBinding binding, + GameLogicGameplayRuleIntakeTerminal terminal, + GameplayRuleSelectedSource selectedSource, + String manifestDigest, + String abilitySchemaDigest, + int digestSchemaVersion, + String canonicalization) { + this.binding = Objects.requireNonNull(binding, "binding"); + this.terminal = Objects.requireNonNull(terminal, "terminal"); + this.selectedSource = Objects.requireNonNull(selectedSource, "selectedSource"); + this.manifestDigest = Objects.requireNonNull(manifestDigest, "manifestDigest"); + this.abilitySchemaDigest = Objects.requireNonNull(abilitySchemaDigest, "abilitySchemaDigest"); + if (digestSchemaVersion <= 0) { + throw new IllegalArgumentException("Positive digest schema version required"); + } + this.digestSchemaVersion = digestSchemaVersion; + this.canonicalization = Objects.requireNonNull(canonicalization, "canonicalization"); + } + + public GameLogicPublicationSourceReadBinding binding() { + return binding; + } + + /** The genuine immutable terminal instance returned by the owner repository readback. */ + public GameLogicGameplayRuleIntakeTerminal terminal() { + return terminal; + } + + public GameLogicGameplayRuleIntakeOperation operation() { + return terminal.operation(); + } + + /** The exact selected source reconstructed from the terminal's defensive stored bytes. */ + public GameplayRuleSelectedSource selectedSource() { + return selectedSource; + } + + public byte[] terminalBytes() { + return terminal.canonicalBytes(); + } + + public byte[] authorizationBytes() { + return terminal.authorizationBytes(); + } + + public byte[] selectedSourceBytes() { + return terminal.selectedSourceBytes(); + } + + public byte[] manifestBytes() { + return terminal.manifestBytes(); + } + + public String manifestDigest() { + return manifestDigest; + } + + public String abilitySchemaDigest() { + return abilitySchemaDigest; + } + + public int digestSchemaVersion() { + return digestSchemaVersion; + } + + /** Canonicalization evidence for both the retained manifest and v1 ability projection. */ + public String canonicalization() { + return canonicalization; + } + } +} diff --git a/services/game-logic-service/src/main/resources/db/migration/V2__immutable_gameplay_rule_source_intake.sql b/services/game-logic-service/src/main/resources/db/migration/V2__immutable_gameplay_rule_source_intake.sql new file mode 100644 index 0000000000..ce411672be --- /dev/null +++ b/services/game-logic-service/src/main/resources/db/migration/V2__immutable_gameplay_rule_source_intake.sql @@ -0,0 +1,52 @@ +CREATE TABLE game_logic_gameplay_rule_intake_terminal ( + operation_id UUID PRIMARY KEY, + target_namespace VARCHAR(63) NOT NULL CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + actor_account_id UUID NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + selected_commit_id UUID NOT NULL, + operation_digest VARCHAR(71) NOT NULL CHECK (operation_digest ~ '^sha256:[0-9a-f]{64}$'), + authorization_digest VARCHAR(71) NOT NULL CHECK (authorization_digest ~ '^sha256:[0-9a-f]{64}$'), + authorization_bytes BYTEA NOT NULL CHECK (octet_length(authorization_bytes) BETWEEN 1 AND 4194304), + outcome VARCHAR(16) NOT NULL CHECK (outcome IN ('RETAINED', 'ABORTED')), + selected_source_bytes BYTEA, + selected_source_digest VARCHAR(71), + manifest_bytes BYTEA, + manifest_digest VARCHAR(71), + terminal_bytes BYTEA NOT NULL CHECK (octet_length(terminal_bytes) BETWEEN 1 AND 16777216), + terminal_digest VARCHAR(71) NOT NULL CHECK (terminal_digest ~ '^sha256:[0-9a-f]{64}$'), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK ( + (outcome = 'RETAINED' + AND selected_source_bytes IS NOT NULL + AND octet_length(selected_source_bytes) BETWEEN 1 AND 4194304 + AND selected_source_digest IS NOT NULL + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND manifest_bytes IS NOT NULL + AND octet_length(manifest_bytes) BETWEEN 1 AND 4194304 + AND manifest_digest IS NOT NULL + AND manifest_digest ~ '^sha256:[0-9a-f]{64}$') + OR + (outcome = 'ABORTED' + AND selected_source_bytes IS NULL + AND selected_source_digest IS NULL + AND manifest_bytes IS NULL + AND manifest_digest IS NULL) + ) +); + +-- [jooq ignore start] +CREATE FUNCTION reject_game_logic_gameplay_rule_intake_mutation() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Logic gameplay-rule intake terminals are immutable' USING ERRCODE = '23514'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER game_logic_gameplay_rule_intake_immutable + BEFORE UPDATE OR DELETE ON game_logic_gameplay_rule_intake_terminal + FOR EACH ROW EXECUTE FUNCTION reject_game_logic_gameplay_rule_intake_mutation(); + +CREATE TRIGGER game_logic_gameplay_rule_intake_no_truncate + BEFORE TRUNCATE ON game_logic_gameplay_rule_intake_terminal + FOR EACH STATEMENT EXECUTE FUNCTION reject_game_logic_gameplay_rule_intake_mutation(); +-- [jooq ignore stop] diff --git a/services/game-logic-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GameLogicIntakeSettlementComposedPostgresIntegrationTest.java b/services/game-logic-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GameLogicIntakeSettlementComposedPostgresIntegrationTest.java new file mode 100644 index 0000000000..d9631aa2a7 --- /dev/null +++ b/services/game-logic-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GameLogicIntakeSettlementComposedPostgresIntegrationTest.java @@ -0,0 +1,678 @@ +package net.firedevops.firemud.accountservice.service.session; + +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.when; + +import io.grpc.Context; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamelogic.*; +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.gamelogic.sourceintake.*; +import net.firedevops.firemud.test.TestContainerImages; +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; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Actual Account intake producer/SQL guards, GL storage and HELD/terminal mTLS endpoints. GD + * immutable source and the original author's terminal are explicit upstream stipulations. This + * defines downstream composition proof, not full authoring-chain or registered runtime proof. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameLogicIntakeSettlementComposedPostgresIntegrationTest { + private static final String NAMESPACE = "test"; + private static final Network NETWORK = Network.newNetwork(); + + @Container + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("intake-settlement-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer replica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(redis) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "intake-settlement-primary", + "6379"); + + @TempDir Path temporary; + + @Test + void exactTerminalSettlementReleasesOnlyItsOrderAndSurvivesOwnerOutage() throws Exception { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selected(f.tenant); + var captured = f.tx(() -> f.authority.captureInitial(f.tenant, issued.environment())); + var original = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + selected.requestId(), + selected.commitId(), + UUID.randomUUID(), + f.account.getAccountUuid(), + f.tenant, + selected.target().canonicalVersionId(), + selected.baseCommitId(), + "0", + selected.canonicalBytes(), + selected.canonicalBytes(), + selected.digest(), + captured.sources()) + .withRequiredOwners(); + issued.actors().claimOriginalDraft(issued.compact(), original, issued.environment()); + // Upstream original-author terminal fixture; this test does not manufacture GL HELD evidence. + f.tx( + () -> { + f.fences.recordOwnerReadback( + original, + new DraftAuthorizationFenceBinding.OwnerReadback( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + original.operationId(), + original.commitId(), + original.fenceId(), + original.inputDigest(), + original.canonicalBytes(), + new byte[] {1})); + return null; + }); + var source = source(selected); + var gd = mock(GameplayRuleSourceReadClient.class); + when(gd.read(any())) + .thenAnswer(call -> new GameplayRuleSourceReadEvidence(call.getArgument(0), source)); + var accountRepository = new AccountGameLogicIntakeAuthorizationRepository(f.dsl); + var producer = + new AccountGameLogicIntakeAuthorizationService( + issued.actors(), f.fences, accountRepository, gd, f.manager, NAMESPACE); + var retainedOrder = + asGameDesign( + () -> + producer.authorize( + issued.compact(), UUID.randomUUID(), selected, issued.environment())); + var abortedOrder = + asGameDesign( + () -> + producer.authorize( + issued.compact(), UUID.randomUUID(), selected, issued.environment())); + + String schema = "gl_settlement_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + dataSource.setSchema(schema); + org.flywaydb.core.Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + var glDsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var glManager = new DataSourceTransactionManager(dataSource); + var glTransaction = new TransactionTemplate(glManager); + glTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var glRepository = new GameLogicGameplayRuleIntakeRepository(glDsl); + var pki = new TestPki(temporary.resolve("pki")); + var heldOwner = + new AccountGameLogicIntakeAuthorizationReadGrpcService( + new AccountGameLogicIntakeAuthorizationReadService( + accountRepository, f.manager, NAMESPACE), + NAMESPACE); + var terminalOwner = + new GameLogicGameplayRuleIntakeTerminalReadGrpcService( + new GameLogicGameplayRuleIntakeTerminalReadService(glRepository, NAMESPACE), + NAMESPACE); + Server accountServer = server(heldOwner, pki.accountServer, pki); + Server glServer = server(terminalOwner, pki.gameLogicServer, pki); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + accountServer.getPort()); + endpoints.setGameLogicService("127.0.0.1:" + glServer.getPort()); + try (var held = + new GameLogicIntakeAuthorizationReadClient( + endpoints, + pki.gameLogicClient.properties(pki.ca), + new GrpcChannelFactory(), + NAMESPACE); + var terminals = + new GameLogicIntakeTerminalReadClient( + endpoints, + pki.accountClient.properties(pki.ca), + new GrpcChannelFactory(), + NAMESPACE)) { + held.init(); + terminals.init(); + var glOwner = + new GameLogicGameplayRuleIntakeService(glRepository, glManager, held, gd, NAMESPACE); + var settlement = + new AccountGameLogicIntakeSettlementService( + accountRepository, terminals, f.manager, NAMESPACE); + var request = GameLogicIntakeTerminalReadEvidence.Request.create(NAMESPACE, retainedOrder); + assertThat(terminals.read(request).terminal()).isEmpty(); + assertThatThrownBy(() -> asGameDesign(() -> settlement.settle(retainedOrder))) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + assertThat(f.dsl.fetchCount(DSL.table("account_game_logic_intake_settlements"))).isZero(); + f.tx( + () -> { + accountRepository.readHeld(retainedOrder, NAMESPACE); + return null; + }); + var change = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), retainedOrder.sources(), new byte[] {2}); + assertThat(f.tx(() -> f.fences.requestSourceChange(change))).isFalse(); + + // Actual HELD transport and local terminal transaction. Both outcomes remain pending here. + var retained = asGameDesign(() -> glOwner.retain(retainedOrder)); + var aborted = asGameDesign(() -> glOwner.abort(abortedOrder)); + assertThat(asGameDesign(() -> glOwner.retain(abortedOrder)).canonicalBytes()) + .isEqualTo(aborted.canonicalBytes()); + assertThat(aborted.outcome()) + .isEqualTo(GameLogicGameplayRuleIntakeTerminal.Outcome.ABORTED); + assertThat(terminals.read(request).terminal().orElseThrow().canonicalBytes()) + .isEqualTo(retained.canonicalBytes()); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isFalse(); + assertThatThrownBy( + () -> + f.tx( + () -> { + f.fences.requireDisclosurePreparation(retainedOrder.sources()); + return null; + })) + .isInstanceOf(IllegalStateException.class); + + // Unknown/changed operation identity, peer workload and namespace fail at the real + // endpoint. + var changed = + new GameLogicIntakeAuthorizationBinding( + retainedOrder.operationId(), + retainedOrder.fenceId(), + UUID.randomUUID(), + retainedOrder.actorAccountId(), + retainedOrder.source(), + retainedOrder.sources()); + assertThatThrownBy( + () -> + terminals.read( + GameLogicIntakeTerminalReadEvidence.Request.create(NAMESPACE, changed))) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.ALREADY_EXISTS)); + for (var identity : List.of(pki.wrongClient, pki.otherNamespaceClient)) { + try (var denied = + new GameLogicIntakeTerminalReadClient( + endpoints, identity.properties(pki.ca), new GrpcChannelFactory(), NAMESPACE)) { + denied.init(); + assertThatThrownBy(() -> denied.read(request)) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + } + for (var identity : List.of(pki.wrongServer, pki.otherNamespaceServer)) { + Server substituted = server(terminalOwner, identity, pki); + var substitutedEndpoints = endpoints.copy(); + substitutedEndpoints.setGameLogicService("127.0.0.1:" + substituted.getPort()); + try (var denied = + new GameLogicIntakeTerminalReadClient( + substitutedEndpoints, + pki.accountClient.properties(pki.ca), + new GrpcChannelFactory(), + NAMESPACE)) { + denied.init(); + assertThatThrownBy(() -> denied.read(request)) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + } finally { + stop(substituted); + } + } + + // Rollback leaves the exact order held; a fabricated/different terminal cannot release it. + assertThatThrownBy( + () -> + f.tx( + () -> { + accountRepository.settle(new AccountGameLogicIntakeSettlement(retained)); + throw new IllegalStateException("rollback settlement"); + })) + .hasMessageContaining("rollback"); + f.tx( + () -> { + accountRepository.readHeld(retainedOrder, NAMESPACE); + return null; + }); + assertThatThrownBy( + () -> + f.tx( + () -> { + var receipt = new AccountGameLogicIntakeSettlement(retained); + f.dsl.execute( + "INSERT INTO account_game_logic_intake_settlements (operation_id, target_namespace, outcome, terminal_bytes, terminal_digest, receipt_bytes, receipt_digest) VALUES (?, ?, ?, ?, ?, ?, ?)", + abortedOrder.operationId(), + NAMESPACE, + "RETAINED", + retained.canonicalBytes(), + retained.digest(), + receipt.canonicalBytes(), + receipt.digest()); + return null; + })) + .hasStackTraceContaining("Changed original Game Logic operation authorization"); + + AccountGameLogicIntakeSettlement receipt; + try (var executor = Executors.newFixedThreadPool(2)) { + var first = executor.submit(() -> asGameDesign(() -> settlement.settle(retainedOrder))); + var second = executor.submit(() -> asGameDesign(() -> settlement.settle(retainedOrder))); + receipt = first.get(20, TimeUnit.SECONDS); + assertThat(second.get(20, TimeUnit.SECONDS).canonicalBytes()) + .isEqualTo(receipt.canonicalBytes()); + } + assertThat(receipt.terminal().canonicalBytes()).isEqualTo(retained.canonicalBytes()); + assertThat(f.dsl.fetchCount(DSL.table("account_game_logic_intake_settlements"))) + .isEqualTo(1); + assertThatThrownBy( + () -> + held.read( + GameLogicIntakeAuthorizationReadEvidence.Request.create( + NAMESPACE, retainedOrder))) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + f.tx( + () -> { + accountRepository.readHeld(abortedOrder, NAMESPACE); + return null; + }); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isFalse(); + assertThatThrownBy( + () -> + f.tx( + () -> { + f.fences.requireDisclosurePreparation(retainedOrder.sources()); + return null; + })) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + f.tx( + () -> { + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", f.account.getId()); + return null; + })) + .hasStackTraceContaining("Distinct Game Logic intake remains pending"); + var abortReceipt = asGameDesign(() -> settlement.settle(abortedOrder)); + assertThat(abortReceipt.terminal().canonicalBytes()).isEqualTo(aborted.canonicalBytes()); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isTrue(); + f.tx( + () -> { + f.fences.markSourceAborted( + change, + DraftAuthorizationFenceRepository.SourceChangeAbortReason.DEFINITIVE_ABORT); + return null; + }); + f.tx( + () -> { + f.fences.requireDisclosurePreparation(retainedOrder.sources()); + return null; + }); + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE account_game_logic_intake_settlements SET outcome = 'ABORTED' WHERE operation_id = ?", + retainedOrder.operationId())) + .hasStackTraceContaining("immutable"); + assertThatThrownBy( + () -> + f.dsl.execute( + "DELETE FROM account_game_logic_intake_settlements WHERE operation_id = ?", + retainedOrder.operationId())) + .hasStackTraceContaining("immutable"); + assertThatThrownBy(() -> f.dsl.execute("TRUNCATE account_game_logic_intake_settlements")) + .hasStackTraceContaining("immutable"); + stop(glServer); + glServer = null; + // New process collaborators return the stored receipt without an available GL channel. + var restarted = + new AccountGameLogicIntakeSettlementService( + new AccountGameLogicIntakeAuthorizationRepository(f.dsl), + terminals, + f.manager, + NAMESPACE); + assertThat(asGameDesign(() -> restarted.settle(retainedOrder)).canonicalBytes()) + .isEqualTo(receipt.canonicalBytes()); + assertThatThrownBy(() -> asGameDesign(() -> restarted.settle(changed))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(f.dsl.fetchCount(DSL.table("account_game_logic_intake_settlements"))) + .isEqualTo(2); + // Historical GL retry remains exact after Account no longer permits HELD. + assertThat(asGameDesign(() -> glOwner.retain(retainedOrder)).canonicalBytes()) + .isEqualTo(retained.canonicalBytes()); + } finally { + stop(accountServer); + if (glServer != null) stop(glServer); + } + } + } + + private static Server server(io.grpc.BindableService owner, TestIdentity identity, TestPki pki) + throws Exception { + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize(GameLogicGameplayRuleIntakeTerminal.MAX_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + identity.certificate().toFile(), identity.key().toFile())) + .trustManager(pki.ca.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(owner, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private static void stop(Server server) throws Exception { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + + private static DraftCommitBinding selected(UUID tenant) { + var target = + new DraftCommitBinding.TargetProof( + tenant, UUID.randomUUID(), 17, "private", 11, "private", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSourceRevision.upsertPayload( + new GameplayRuleManifest.AdmissionTag("gameplay")))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + } + + private static GameplayRuleSelectedSource source(DraftCommitBinding selected) { + var definition = new GameplayRuleManifest.AdmissionTag("gameplay"); + Map> families = + new EnumMap<>(GameplayRuleManifest.Family.class); + for (var family : GameplayRuleManifest.Family.values()) families.put(family, new ArrayList<>()); + families.get(definition.family()).add(definition); + var manifest = new GameplayRuleManifest(families); + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + manifest.canonicalJson(), + "entries", + List.of( + Map.of( + "family", + definition.family().name(), + "definitionJson", + GameplayRuleManifest.canonical(definition), + "sourceBindingJson", + selected.canonicalJson(), + "sourceBindingDigest", + selected.digest(), + "revisionOrder", + "0", + "revisionId", + selected.revisions().getFirst().revisionId().toString()))))); + } + + private static T asGameDesign(java.util.function.Supplier action) { + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-design-service") + .orElseThrow()); + var previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + /** Ephemeral certificate authority, never a deployed trust root or live workload credential. */ + private static final class TestPki { + final Path ca; + final TestIdentity accountServer, + gameLogicServer, + gameLogicClient, + accountClient, + wrongServer, + wrongClient, + otherNamespaceClient, + otherNamespaceServer; + + TestPki(Path root) throws Exception { + Files.createDirectories(root); + var generator = java.security.KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + var caKeys = generator.generateKeyPair(); + var name = + new org.bouncycastle.asn1.x500.X500Name("CN=Test-only Account Game Logic proof CA"); + var now = java.time.Instant.now(); + var builder = + new org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder( + name, + java.math.BigInteger.ONE, + java.util.Date.from(now.minusSeconds(60)), + java.util.Date.from(now.plusSeconds(3600)), + name, + caKeys.getPublic()); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.basicConstraints, + true, + new org.bouncycastle.asn1.x509.BasicConstraints(true)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.keyUsage, + true, + new org.bouncycastle.asn1.x509.KeyUsage(org.bouncycastle.asn1.x509.KeyUsage.keyCertSign)); + var signer = + new org.bouncycastle.operator.jcajce.JcaContentSignerBuilder("SHA256withRSA") + .build(caKeys.getPrivate()); + var caCert = + new org.bouncycastle.cert.jcajce.JcaX509CertificateConverter() + .getCertificate(builder.build(signer)); + ca = pem(root.resolve("ca.pem"), caCert); + accountServer = issue(root, "account-service", true, caKeys, caCert, NAMESPACE); + gameLogicServer = issue(root, "game-logic-service", true, caKeys, caCert, NAMESPACE); + gameLogicClient = issue(root, "game-logic-service", false, caKeys, caCert, NAMESPACE); + accountClient = issue(root, "account-service", false, caKeys, caCert, NAMESPACE); + wrongServer = issue(root, "game-design-service", true, caKeys, caCert, NAMESPACE); + wrongClient = issue(root, "game-design-service", false, caKeys, caCert, NAMESPACE); + otherNamespaceClient = issue(root, "account-service", false, caKeys, caCert, "other-test"); + otherNamespaceServer = issue(root, "game-logic-service", true, caKeys, caCert, "other-test"); + } + + private static TestIdentity issue( + Path root, + String service, + boolean server, + java.security.KeyPair caKeys, + java.security.cert.X509Certificate caCert, + String namespace) + throws Exception { + var generator = java.security.KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + var keys = generator.generateKeyPair(); + var now = java.time.Instant.now(); + var builder = + new org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder( + caCert, + new java.math.BigInteger(120, new java.security.SecureRandom()), + java.util.Date.from(now.minusSeconds(60)), + java.util.Date.from(now.plusSeconds(3600)), + new org.bouncycastle.asn1.x500.X500Name("CN=" + service), + keys.getPublic()); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.basicConstraints, + true, + new org.bouncycastle.asn1.x509.BasicConstraints(false)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.keyUsage, + true, + new org.bouncycastle.asn1.x509.KeyUsage( + org.bouncycastle.asn1.x509.KeyUsage.digitalSignature + | org.bouncycastle.asn1.x509.KeyUsage.keyEncipherment)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.extendedKeyUsage, + false, + new org.bouncycastle.asn1.x509.ExtendedKeyUsage( + server + ? org.bouncycastle.asn1.x509.KeyPurposeId.id_kp_serverAuth + : org.bouncycastle.asn1.x509.KeyPurposeId.id_kp_clientAuth)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, + false, + new org.bouncycastle.asn1.x509.GeneralNames( + new org.bouncycastle.asn1.x509.GeneralName[] { + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.uniformResourceIdentifier, + "spiffe://firemud/ns/" + namespace + "/sa/" + service), + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.dNSName, "localhost"), + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.iPAddress, "127.0.0.1") + })); + var certificate = + new org.bouncycastle.cert.jcajce.JcaX509CertificateConverter() + .getCertificate( + builder.build( + new org.bouncycastle.operator.jcajce.JcaContentSignerBuilder("SHA256withRSA") + .build(caKeys.getPrivate()))); + String prefix = namespace + "-" + service + (server ? "-server" : "-client"); + return new TestIdentity( + pem(root.resolve(prefix + ".crt"), certificate), + pem(root.resolve(prefix + ".key"), keys.getPrivate())); + } + + private static Path pem(Path path, Object value) throws Exception { + try (var writer = + new org.bouncycastle.openssl.jcajce.JcaPEMWriter(Files.newBufferedWriter(path))) { + writer.writeObject(value); + } + return path; + } + } + + private record TestIdentity(Path certificate, Path key) { + CommonGrpcClientProperties properties(Path ca) { + var result = new CommonGrpcClientProperties(); + result.setPlaintext(false); + result.setCertChain(certificate.toString()); + result.setPrivateKey(key.toString()); + result.setCaCert(ca.toString()); + return result; + } + } +} diff --git a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java new file mode 100644 index 0000000000..efe1be831c --- /dev/null +++ b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java @@ -0,0 +1,453 @@ +package net.firedevops.firemud.gamelogic.sourceintake; + +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.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding; +import net.firedevops.firemud.common.gamelogic.GameplayAbilitySchemaProjection; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameLogicGameplayRuleIntakePostgresIntegrationTest { + private static final String NAMESPACE = "test"; + + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void exactConcurrentRetriesRetainOneImmutableOriginalTerminalAndReadItWithoutOwnerReads() + throws Exception { + var fixture = fixture(); + var authorization = authorization(); + var source = authorization.source(); + var bothSourceReads = new CountDownLatch(2); + var accountReads = new AtomicInteger(); + var gameDesignReads = new AtomicInteger(); + var accountReader = mock(GameLogicIntakeAuthorizationReadClient.class); + var gameDesignReader = mock(GameplayRuleSourceReadClient.class); + when(accountReader.read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + accountReads.incrementAndGet(); + return new GameLogicIntakeAuthorizationReadEvidence(invocation.getArgument(0)); + }); + when(gameDesignReader.read(any(GameplayRuleSourceReadEvidence.Request.class))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + gameDesignReads.incrementAndGet(); + var sourceRequest = invocation.getArgument(0); + assertThat(sourceRequest.proof()) + .isInstanceOf(GameplayRuleSourceReadEvidence.Finalized.class); + assertThat(sourceRequest.proof().canonicalBytes()) + .containsExactly(authorization.canonicalBytes()); + bothSourceReads.countDown(); + if (!bothSourceReads.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent source-read barrier timed out"); + } + return new GameplayRuleSourceReadEvidence(invocation.getArgument(0), source); + }); + var first = fixture.service(accountReader, gameDesignReader); + var second = fixture.service(accountReader, gameDesignReader); + byte[] originalTerminalBytes; + + try (var executor = Executors.newFixedThreadPool(2)) { + var left = executor.submit(() -> asGameDesign(() -> first.retain(authorization))); + var right = executor.submit(() -> asGameDesign(() -> second.retain(authorization))); + var retained = left.get(15, TimeUnit.SECONDS); + var retry = right.get(15, TimeUnit.SECONDS); + originalTerminalBytes = retained.canonicalBytes(); + assertThat(retained.canonicalBytes()).containsExactly(retry.canonicalBytes()); + } + + assertThat(accountReads).hasValue(2); + assertThat(gameDesignReads).hasValue(2); + assertThat(fixture.dsl.fetchCount(DSL.table("game_logic_gameplay_rule_intake_terminal"))) + .isEqualTo(1); + var stored = fixture.repository.findTerminal(authorization.operationId()).orElseThrow(); + assertThat(stored.authorizationBytes()).containsExactly(authorization.canonicalBytes()); + assertThat(stored.selectedSourceBytes()).containsExactly(source.canonicalBytes()); + assertThat(stored.manifestBytes()) + .containsExactly(source.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE game_logic_gameplay_rule_intake_terminal SET outcome = 'ABORTED' WHERE operation_id = ?", + authorization.operationId())) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "DELETE FROM game_logic_gameplay_rule_intake_terminal WHERE operation_id = ?", + authorization.operationId())) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> fixture.dsl.execute("TRUNCATE game_logic_gameplay_rule_intake_terminal")) + .isInstanceOf(RuntimeException.class); + assertThat(fixture.dsl.fetchCount(DSL.table("game_logic_gameplay_rule_intake_terminal"))) + .isEqualTo(1); + + var unavailableAccount = mock(GameLogicIntakeAuthorizationReadClient.class); + var unavailableDesign = mock(GameplayRuleSourceReadClient.class); + when(unavailableAccount.read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class))) + .thenThrow(new AssertionError("Stored terminal retry must not reread Account")); + when(unavailableDesign.read(any(GameplayRuleSourceReadEvidence.Request.class))) + .thenThrow(new AssertionError("Stored terminal retry must not reread latest GD source")); + var restarted = fixture.service(unavailableAccount, unavailableDesign); + var recovered = asGameDesign(() -> restarted.retain(authorization)); + assertThat(recovered.canonicalBytes()).containsExactly(originalTerminalBytes); + } + + @Test + void explicitAbortWinsBeforeRetentionAndPreventsLaterSourceReadsAndCommit() throws Exception { + var fixture = fixture(); + var authorization = authorization(); + var sourceReadEntered = new CountDownLatch(1); + var allowSourceRead = new CountDownLatch(1); + var accountReader = mock(GameLogicIntakeAuthorizationReadClient.class); + var gameDesignReader = mock(GameplayRuleSourceReadClient.class); + when(accountReader.read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class))) + .thenAnswer( + invocation -> new GameLogicIntakeAuthorizationReadEvidence(invocation.getArgument(0))); + when(gameDesignReader.read(any(GameplayRuleSourceReadEvidence.Request.class))) + .thenAnswer( + invocation -> { + sourceReadEntered.countDown(); + if (!allowSourceRead.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Source-read barrier timed out"); + } + return new GameplayRuleSourceReadEvidence( + invocation.getArgument(0), authorization.source()); + }); + var service = fixture.service(accountReader, gameDesignReader); + + try (var executor = Executors.newSingleThreadExecutor()) { + var retention = executor.submit(() -> asGameDesign(() -> service.retain(authorization))); + assertThat(sourceReadEntered.await(5, TimeUnit.SECONDS)).isTrue(); + var aborted = asGameDesign(() -> service.abort(authorization)); + allowSourceRead.countDown(); + var observed = retention.get(15, TimeUnit.SECONDS); + assertThat(aborted.outcome()).isEqualTo(GameLogicGameplayRuleIntakeTerminal.Outcome.ABORTED); + assertThat(observed.canonicalBytes()).containsExactly(aborted.canonicalBytes()); + } finally { + allowSourceRead.countDown(); + } + + assertThat(fixture.dsl.fetchCount(DSL.table("game_logic_gameplay_rule_intake_terminal"))) + .isEqualTo(1); + assertThat(fixture.repository.findTerminal(authorization.operationId()).orElseThrow().outcome()) + .isEqualTo(GameLogicGameplayRuleIntakeTerminal.Outcome.ABORTED); + } + + @Test + void publicationReadUsesCommittedTerminalAfterUpstreamReadersAreUnavailableAndNeverAttestsAbort() + throws Exception { + var fixture = fixture(); + var authorization = authorization(); + // These upstream collaborators are fixture stubs; this definition proves GL's committed local + // readback, not genuine cross-owner Account or Game Design producer issuance. + var accountReader = mock(GameLogicIntakeAuthorizationReadClient.class); + var gameDesignReader = mock(GameplayRuleSourceReadClient.class); + when(accountReader.read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class))) + .thenAnswer( + invocation -> new GameLogicIntakeAuthorizationReadEvidence(invocation.getArgument(0))); + when(gameDesignReader.read(any(GameplayRuleSourceReadEvidence.Request.class))) + .thenAnswer( + invocation -> + new GameplayRuleSourceReadEvidence( + invocation.getArgument(0), authorization.source())); + + var retained = + asGameDesign(() -> fixture.service(accountReader, gameDesignReader).retain(authorization)); + var unavailableAccount = mock(GameLogicIntakeAuthorizationReadClient.class); + var unavailableDesign = mock(GameplayRuleSourceReadClient.class); + when(unavailableAccount.read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class))) + .thenThrow(new AssertionError("Exact retained retry must not reread Account")); + when(unavailableDesign.read(any(GameplayRuleSourceReadEvidence.Request.class))) + .thenThrow(new AssertionError("Exact retained retry must not reread Game Design")); + + var exactRetry = + asGameDesign( + () -> fixture.service(unavailableAccount, unavailableDesign).retain(authorization)); + assertThat(exactRetry.canonicalBytes()).containsExactly(retained.canonicalBytes()); + verify(unavailableAccount, never()) + .read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class)); + verify(unavailableDesign, never()).read(any(GameplayRuleSourceReadEvidence.Request.class)); + + var publicationReader = + new GameLogicPublicationSourceReadService(fixture.repository, NAMESPACE); + var publicationBinding = publicationBinding(authorization); + var publicationResult = asGameDesign(() -> publicationReader.read(publicationBinding)); + var publicationRetry = asGameDesign(() -> publicationReader.read(publicationBinding)); + assertThat(publicationResult.binding().canonicalBytes()) + .containsExactly(publicationBinding.canonicalBytes()); + assertThat(publicationResult.terminalBytes()).containsExactly(retained.canonicalBytes()); + assertThat(publicationRetry.terminalBytes()).containsExactly(publicationResult.terminalBytes()); + assertThat(publicationResult.manifestDigest()) + .isEqualTo(authorization.source().manifest().digest()); + assertThat(publicationResult.abilitySchemaDigest()) + .isEqualTo(GameplayAbilitySchemaProjection.digest(authorization.source().manifest())); + assertThat( + fixture + .repository + .findTerminal(authorization.operationId()) + .orElseThrow() + .canonicalBytes()) + .containsExactly(retained.canonicalBytes()); + + var changedOperationId = + copyAuthorization( + authorization, + UUID.randomUUID(), + authorization.fenceId(), + authorization.intakeRequestId(), + authorization.source()); + assertReadDenied( + Status.Code.FAILED_PRECONDITION, + () -> asGameDesign(() -> publicationReader.read(publicationBinding(changedOperationId)))); + + var changedOperation = + copyAuthorization( + authorization, + authorization.operationId(), + authorization.fenceId(), + UUID.randomUUID(), + authorization.source()); + assertReadDenied( + Status.Code.ALREADY_EXISTS, + () -> asGameDesign(() -> publicationReader.read(publicationBinding(changedOperation)))); + + var changedFence = + copyAuthorization( + authorization, + authorization.operationId(), + UUID.randomUUID(), + authorization.intakeRequestId(), + authorization.source()); + assertReadDenied( + Status.Code.ALREADY_EXISTS, + () -> asGameDesign(() -> publicationReader.read(publicationBinding(changedFence)))); + + var originalCommit = authorization.source().binding(); + var changedCommit = + DraftCommitBinding.create( + originalCommit.target(), + originalCommit.requestId(), + UUID.randomUUID(), + originalCommit.baseCommitId(), + originalCommit.revisions(), + originalCommit.affectedUnits()); + var changedCommitAuthorization = + copyAuthorization( + authorization, + authorization.operationId(), + authorization.fenceId(), + authorization.intakeRequestId(), + source(changedCommit)); + assertReadDenied( + Status.Code.ALREADY_EXISTS, + () -> + asGameDesign( + () -> publicationReader.read(publicationBinding(changedCommitAuthorization)))); + + var abortedAuthorization = authorization(); + var aborted = + asGameDesign( + () -> fixture.service(accountReader, gameDesignReader).abort(abortedAuthorization)); + assertThat(aborted.outcome()).isEqualTo(GameLogicGameplayRuleIntakeTerminal.Outcome.ABORTED); + assertReadDenied( + Status.Code.FAILED_PRECONDITION, + () -> asGameDesign(() -> publicationReader.read(publicationBinding(abortedAuthorization)))); + } + + private static Fixture fixture() { + String schema = "gl_intake_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = new DriverManagerDataSource(); + dataSource.setUrl(POSTGRES.getJdbcUrl()); + dataSource.setUsername(POSTGRES.getUsername()); + dataSource.setPassword(POSTGRES.getPassword()); + dataSource.setSchema(schema); + org.flywaydb.core.Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .table("flyway_schema_history") + .locations("classpath:db/migration") + .load() + .migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var transactionManager = new DataSourceTransactionManager(dataSource); + return new Fixture(dsl, transactionManager, new GameLogicGameplayRuleIntakeRepository(dsl)); + } + + private static T asGameDesign(java.util.concurrent.Callable action) throws Exception { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-design-service", NAMESPACE, "game-design-service"); + Context previous = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).attach(); + try { + return action.call(); + } finally { + Context.current().detach(previous); + } + } + + private static GameLogicIntakeAuthorizationBinding authorization() { + var actor = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "private", 2, "private", "NEW_GAME_ROW"); + var binding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var source = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", binding.canonicalJson(), + "bindingDigest", binding.digest(), + "sourceEpoch", "1", + "inheritedCommitId", "", + "genesisReceiptId", UUID.randomUUID().toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + var accountSource = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {4, 5, 6}); + return new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + source, + List.of(accountSource)); + } + + private static GameLogicIntakeAuthorizationBinding copyAuthorization( + GameLogicIntakeAuthorizationBinding original, + UUID operationId, + UUID fenceId, + UUID intakeRequestId, + GameplayRuleSelectedSource source) { + return new GameLogicIntakeAuthorizationBinding( + operationId, + fenceId, + intakeRequestId, + original.actorAccountId(), + source, + original.sources()); + } + + private static GameplayRuleSelectedSource source(DraftCommitBinding binding) { + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", binding.canonicalJson(), + "bindingDigest", binding.digest(), + "sourceEpoch", "1", + "inheritedCommitId", "", + "genesisReceiptId", UUID.randomUUID().toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + } + + private static GameLogicPublicationSourceReadBinding publicationBinding( + GameLogicIntakeAuthorizationBinding authorization) { + var target = authorization.source().binding().target(); + return new GameLogicPublicationSourceReadBinding( + PublicationDigestRequestBinding.full( + authorization.tenantId().toString(), + Long.toString(target.gameDesignVersionRowId()), + "publication-read"), + authorization); + } + + private static void assertReadDenied( + Status.Code expected, org.assertj.core.api.ThrowableAssert.ThrowingCallable action) { + assertThatThrownBy(action) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private record Fixture( + DSLContext dsl, + DataSourceTransactionManager transactionManager, + GameLogicGameplayRuleIntakeRepository repository) { + private GameLogicGameplayRuleIntakeService service( + GameLogicIntakeAuthorizationReadClient accountReader, + GameplayRuleSourceReadClient gameDesignReader) { + return new GameLogicGameplayRuleIntakeService( + repository, transactionManager, accountReader, gameDesignReader, NAMESPACE); + } + } +} diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcServiceTest.java new file mode 100644 index 0000000000..6a1474180c --- /dev/null +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcServiceTest.java @@ -0,0 +1,269 @@ +package net.firedevops.firemud.gamelogic.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeRetainEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeRetainProtoCodec; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamelogic.v1.RetainGameplayRuleIntakeRequest; +import net.firedevops.firemud.gamelogic.v1.RetainGameplayRuleIntakeResponse; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; + +class GameLogicGameplayRuleIntakeGrpcServiceTest { + private static final String NAMESPACE = "test"; + private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + + @Test + void exactRetryReturnsAndEchoesTheCompleteOriginalTerminal() { + var fixture = new Fixture(); + var request = GameLogicIntakeRetainEvidence.Request.create(NAMESPACE, fixture.authorization); + var observer = new RecordingObserver(); + + asGameDesign( + () -> + fixture.transport.retainGameplayRuleIntake( + GameLogicIntakeRetainProtoCodec.toRequest(request), observer)); + + assertThat(observer.error).isNull(); + assertThat(observer.completed).isTrue(); + var result = GameLogicIntakeRetainProtoCodec.fromResponse(request, observer.value); + assertThat(result.terminal().canonicalBytes()) + .containsExactly(fixture.terminal.canonicalBytes()); + assertThat(result.terminal().outcome()) + .isEqualTo(GameLogicGameplayRuleIntakeTerminal.Outcome.RETAINED); + verify(fixture.repository).findTerminal(fixture.authorization.operationId()); + verify(fixture.accountReader, never()).read(any()); + verify(fixture.gameDesignReader, never()).read(any()); + } + + @Test + void rejectsUnauthenticatedAndWrongPeersBeforeDecodingOrOwnerAccess() { + var fixture = new Fixture(); + var malformed = RetainGameplayRuleIntakeRequest.getDefaultInstance(); + + var unauthenticated = new RecordingObserver(); + fixture.transport.retainGameplayRuleIntake(malformed, unauthenticated); + assertCode(unauthenticated.error, Status.Code.UNAUTHENTICATED); + + var account = new RecordingObserver(); + withPeer( + "spiffe://firemud/ns/test/sa/account-service", + () -> fixture.transport.retainGameplayRuleIntake(malformed, account)); + assertCode(account.error, Status.Code.PERMISSION_DENIED); + + verify(fixture.repository, never()).findTerminal(any(UUID.class)); + verify(fixture.accountReader, never()).read(any()); + verify(fixture.gameDesignReader, never()).read(any()); + } + + @Test + void rejectsChangedNamespaceAndChangedAuthorizationForExistingOperation() { + var fixture = new Fixture(); + + var wrongNamespace = new RecordingObserver(); + var requestForOtherNamespace = + GameLogicIntakeRetainEvidence.Request.create("other", fixture.authorization); + asGameDesign( + () -> + fixture.transport.retainGameplayRuleIntake( + GameLogicIntakeRetainProtoCodec.toRequest(requestForOtherNamespace), + wrongNamespace)); + assertCode(wrongNamespace.error, Status.Code.PERMISSION_DENIED); + + var changed = + new GameLogicIntakeAuthorizationBinding( + fixture.authorization.operationId(), + UUID.randomUUID(), + fixture.authorization.intakeRequestId(), + fixture.authorization.actorAccountId(), + fixture.authorization.source(), + fixture.authorization.sources()); + var changedRequest = GameLogicIntakeRetainEvidence.Request.create(NAMESPACE, changed); + var conflict = new RecordingObserver(); + asGameDesign( + () -> + fixture.transport.retainGameplayRuleIntake( + GameLogicIntakeRetainProtoCodec.toRequest(changedRequest), conflict)); + assertCode(conflict.error, Status.Code.ALREADY_EXISTS); + verify(fixture.repository).findTerminal(fixture.authorization.operationId()); + verify(fixture.accountReader, never()).read(any()); + verify(fixture.gameDesignReader, never()).read(any()); + } + + @Test + void authenticatedMalformedRequestIsRejectedBeforeAnyOwnerRead() { + var fixture = new Fixture(); + var request = + RetainGameplayRuleIntakeRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setCorrelationId(UUID.randomUUID().toString()) + .setOriginalIntakeAuthorization( + com.google.protobuf.ByteString.copyFromUtf8("not-an-order")) + .setIntakeAuthorizationDigest("sha256:" + "0".repeat(64)) + .build(); + var observer = new RecordingObserver(); + + asGameDesign(() -> fixture.transport.retainGameplayRuleIntake(request, observer)); + + assertCode(observer.error, Status.Code.INVALID_ARGUMENT); + verify(fixture.repository, never()).findTerminal(any(UUID.class)); + verify(fixture.accountReader, never()).read(any()); + verify(fixture.gameDesignReader, never()).read(any()); + } + + private static void assertCode(Status.Code error, Status.Code expected) { + assertThat(error).isEqualTo(expected); + } + + private static void asGameDesign(Runnable action) { + withPeer(GAME_DESIGN_URI, action); + } + + private static void withPeer(String uri, Runnable action) { + var peer = GrpcPeerIdentity.parseUri(uri).orElseThrow(); + Context previous = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).attach(); + try { + action.run(); + } finally { + Context.current().detach(previous); + } + } + + private static final class RecordingObserver implements StreamObserver { + private T value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(T next) { + value = next; + } + + @Override + public void onError(Throwable failure) { + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } + + private static final class Fixture { + private final GameLogicGameplayRuleIntakeRepository repository = + mock(GameLogicGameplayRuleIntakeRepository.class); + private final GameLogicIntakeAuthorizationReadClient accountReader = + mock(GameLogicIntakeAuthorizationReadClient.class); + private final GameplayRuleSourceReadClient gameDesignReader = + mock(GameplayRuleSourceReadClient.class); + private final GameLogicIntakeAuthorizationBinding authorization = authorization(); + private final GameLogicGameplayRuleIntakeTerminal terminal = + GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation(NAMESPACE, authorization), + authorization.source().canonicalBytes(), + authorization.source().manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + private final GameLogicGameplayRuleIntakeService owner = + new GameLogicGameplayRuleIntakeService( + repository, + mock(PlatformTransactionManager.class), + accountReader, + gameDesignReader, + NAMESPACE); + private final GameLogicGameplayRuleIntakeGrpcService transport = + new GameLogicGameplayRuleIntakeGrpcService(owner, NAMESPACE); + + private Fixture() { + when(repository.findTerminal(any(UUID.class))).thenReturn(Optional.of(terminal)); + } + } + + private static GameLogicIntakeAuthorizationBinding authorization() { + UUID actor = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "private", 2, "private", "NEW_GAME_ROW"); + var selectedBinding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var source = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selectedBinding.canonicalJson(), + "bindingDigest", + selectedBinding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))); + var accountSource = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + return new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + source, + List.of(accountSource)); + } +} diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java new file mode 100644 index 0000000000..30a8b35ef7 --- /dev/null +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java @@ -0,0 +1,456 @@ +package net.firedevops.firemud.gamelogic.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameLogicGameplayRuleIntakeServiceTest { + private static final String NAMESPACE = "test"; + + @Test + void exactHeldAuthorizationAndSelectedSourceAreRetainedAsOneExactTerminal() { + var fixture = new Fixture(); + var authorization = authorization(); + var selected = authorization.source(); + fixture.respondFor(authorization, selected); + + var terminal = asGameDesign(() -> fixture.service.retain(authorization)); + + assertThat(terminal.outcome()).isEqualTo(GameLogicGameplayRuleIntakeTerminal.Outcome.RETAINED); + assertThat(terminal.authorizationBytes()).containsExactly(authorization.canonicalBytes()); + assertThat(terminal.selectedSourceBytes()).containsExactly(selected.canonicalBytes()); + assertThat(terminal.manifestBytes()) + .containsExactly(selected.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat( + GameLogicGameplayRuleIntakeTerminal.fromStored(terminal.canonicalBytes()) + .canonicalBytes()) + .containsExactly(terminal.canonicalBytes()); + var calls = inOrder(fixture.accountReader, fixture.gameDesignReader); + calls + .verify(fixture.accountReader) + .read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class)); + calls.verify(fixture.gameDesignReader).read(any(GameplayRuleSourceReadEvidence.Request.class)); + var sourceRequest = + org.mockito.ArgumentCaptor.forClass(GameplayRuleSourceReadEvidence.Request.class); + verify(fixture.gameDesignReader).read(sourceRequest.capture()); + assertThat(sourceRequest.getValue().proof()) + .isInstanceOf(GameplayRuleSourceReadEvidence.Finalized.class); + assertThat(sourceRequest.getValue().proof().canonicalBytes()) + .containsExactly(authorization.canonicalBytes()); + } + + @Test + void exactRetryReturnsOriginalBytesWithoutRecheckingSettledAccountOrLatestSource() { + var fixture = new Fixture(); + var authorization = authorization(); + var operation = new GameLogicGameplayRuleIntakeOperation(NAMESPACE, authorization); + var original = + GameLogicGameplayRuleIntakeTerminal.retained( + operation, + authorization.source().canonicalBytes(), + authorization.source().manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + fixture.stored.set(original); + fixture.repositoryFindsStored(); + + var retry = asGameDesign(() -> fixture.service.retain(authorization)); + + assertThat(retry.canonicalBytes()).containsExactly(original.canonicalBytes()); + verify(fixture.accountReader, never()) + .read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class)); + verify(fixture.gameDesignReader, never()) + .read(any(GameplayRuleSourceReadEvidence.Request.class)); + } + + @Test + void explicitAbortIsDurableAndBlocksLaterRetentionWithoutInferringFromMissingReads() { + var fixture = new Fixture(); + var authorization = authorization(); + fixture.repositoryFindsStored(); + fixture.respondAuthorizationOnly(authorization); + + var aborted = asGameDesign(() -> fixture.service.abort(authorization)); + var retry = asGameDesign(() -> fixture.service.retain(authorization)); + + assertThat(aborted.outcome()).isEqualTo(GameLogicGameplayRuleIntakeTerminal.Outcome.ABORTED); + assertThat(retry.canonicalBytes()).containsExactly(aborted.canonicalBytes()); + assertThat(asAccount(() -> fixture.service.readTerminal(authorization))).contains(aborted); + verify(fixture.accountReader).read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class)); + verify(fixture.gameDesignReader, never()) + .read(any(GameplayRuleSourceReadEvidence.Request.class)); + } + + @Test + void explicitAbortRequiresAnExactHeldAccountReadAndDoesNotWriteOnAbsence() { + var fixture = new Fixture(); + var authorization = authorization(); + fixture.repositoryFindsStored(); + when(fixture.accountReader.read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class))) + .thenThrow(Status.FAILED_PRECONDITION.asRuntimeException()); + + assertThatThrownBy(() -> asGameDesign(() -> fixture.service.abort(authorization))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + assertThat(fixture.stored.get()).isNull(); + verify(fixture.repository, never()) + .insertTerminal(any(GameLogicGameplayRuleIntakeTerminal.class)); + verify(fixture.gameDesignReader, never()) + .read(any(GameplayRuleSourceReadEvidence.Request.class)); + } + + @Test + void explicitAbortRejectsAChangedAccountAuthorizationReadback() { + var fixture = new Fixture(); + var authorization = authorization(); + var changed = + new GameLogicIntakeAuthorizationBinding( + authorization.operationId(), + UUID.randomUUID(), + authorization.intakeRequestId(), + authorization.actorAccountId(), + authorization.source(), + authorization.sources()); + when(fixture.accountReader.read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class))) + .thenAnswer( + invocation -> + new GameLogicIntakeAuthorizationReadEvidence( + new GameLogicIntakeAuthorizationReadEvidence.Request( + 1, + NAMESPACE, + invocation + .getArgument(0) + .readRequestId(), + changed))); + + assertThatThrownBy(() -> asGameDesign(() -> fixture.service.abort(authorization))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + assertThat(fixture.stored.get()).isNull(); + verify(fixture.repository, never()) + .insertTerminal(any(GameLogicGameplayRuleIntakeTerminal.class)); + verify(fixture.gameDesignReader, never()) + .read(any(GameplayRuleSourceReadEvidence.Request.class)); + } + + @Test + void authenticatedSourceMismatchDeniesWithoutWritingAnAbortOrTerminal() { + var fixture = new Fixture(); + var authorization = authorization(); + var changed = source(authorization.source().binding(), "2"); + fixture.respondFor(authorization, changed); + + assertThatThrownBy(() -> asGameDesign(() -> fixture.service.retain(authorization))) + .isInstanceOf(RuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + assertThat(fixture.stored.get()).isNull(); + assertThat(asAccount(() -> fixture.service.readTerminal(authorization))).isEmpty(); + verify(fixture.repository, never()) + .insertTerminal(any(GameLogicGameplayRuleIntakeTerminal.class)); + } + + @Test + void unavailableAccountReadLeavesNoTerminalAndDoesNotInferAbort() { + var fixture = new Fixture(); + var authorization = authorization(); + when(fixture.accountReader.read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class))) + .thenThrow(Status.UNAVAILABLE.asRuntimeException()); + + assertThatThrownBy(() -> asGameDesign(() -> fixture.service.retain(authorization))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + assertThat(fixture.stored.get()).isNull(); + assertThat(asAccount(() -> fixture.service.readTerminal(authorization))).isEmpty(); + verify(fixture.gameDesignReader, never()) + .read(any(GameplayRuleSourceReadEvidence.Request.class)); + verify(fixture.repository, never()) + .insertTerminal(any(GameLogicGameplayRuleIntakeTerminal.class)); + } + + @Test + void changedOrderUnderExistingOperationIdentityIsDeniedBeforeRemoteReads() { + var fixture = new Fixture(); + var originalAuthorization = authorization(); + var operation = new GameLogicGameplayRuleIntakeOperation(NAMESPACE, originalAuthorization); + var original = GameLogicGameplayRuleIntakeTerminal.aborted(operation); + fixture.stored.set(original); + fixture.repositoryFindsStored(); + var changedAuthorization = + new GameLogicIntakeAuthorizationBinding( + originalAuthorization.operationId(), + UUID.randomUUID(), + originalAuthorization.intakeRequestId(), + originalAuthorization.actorAccountId(), + originalAuthorization.source(), + originalAuthorization.sources()); + + assertThatThrownBy(() -> asGameDesign(() -> fixture.service.retain(changedAuthorization))) + .isInstanceOf(RuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.ALREADY_EXISTS)); + verify(fixture.accountReader, never()) + .read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class)); + verify(fixture.gameDesignReader, never()) + .read(any(GameplayRuleSourceReadEvidence.Request.class)); + } + + @Test + void onlyTheExactSameNamespaceGameDesignPeerCanInvokeTheOwner() { + var fixture = new Fixture(); + var authorization = authorization(); + var accountPeer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/account-service", NAMESPACE, "account-service"); + Context previous = + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, accountPeer).attach(); + try { + assertThatThrownBy(() -> fixture.service.retain(authorization)) + .isInstanceOf(RuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } finally { + Context.current().detach(previous); + } + verify(fixture.repository, never()).findTerminal(any(UUID.class)); + verify(fixture.accountReader, never()) + .read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class)); + verify(fixture.gameDesignReader, never()) + .read(any(GameplayRuleSourceReadEvidence.Request.class)); + } + + @Test + void creatorPublicationCredentialCannotBeMixedWithTheServicePeer() { + var fixture = new Fixture(); + var authorization = authorization(); + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-design-service", NAMESPACE, "game-design-service"); + Context request = + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .withValue( + AccountSelectedPublicationOrderCredentials.CONTEXT_KEY, + AccountSelectedPublicationOrderCredentials.Credential.of( + "creator-order-credential")); + Context previous = request.attach(); + try { + assertThatThrownBy(() -> fixture.service.retain(authorization)) + .isInstanceOf(RuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } finally { + Context.current().detach(previous); + } + verify(fixture.repository, never()).findTerminal(any(UUID.class)); + verify(fixture.accountReader, never()) + .read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class)); + verify(fixture.gameDesignReader, never()) + .read(any(GameplayRuleSourceReadEvidence.Request.class)); + } + + private static T asAccount(java.util.function.Supplier action) { + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/account-service") + .orElseThrow()); + var previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private static T asGameDesign(java.util.function.Supplier action) { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-design-service", NAMESPACE, "game-design-service"); + Context previous = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).attach(); + try { + return action.get(); + } finally { + Context.current().detach(previous); + } + } + + private static GameLogicIntakeAuthorizationBinding authorization() { + var actor = UUID.randomUUID(); + var source = source(binding(), "1"); + var accountSource = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + return new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + source, + List.of(accountSource)); + } + + private static DraftCommitBinding binding() { + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "private", 2, "private", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + } + + private static GameplayRuleSelectedSource source(DraftCommitBinding binding, String epoch) { + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", binding.canonicalJson(), + "bindingDigest", binding.digest(), + "sourceEpoch", epoch, + "inheritedCommitId", "", + "genesisReceiptId", UUID.randomUUID().toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + } + + private static final class Fixture { + private final GameLogicGameplayRuleIntakeRepository repository = + mock(GameLogicGameplayRuleIntakeRepository.class); + private final GameLogicIntakeAuthorizationReadClient accountReader = + mock(GameLogicIntakeAuthorizationReadClient.class); + private final GameplayRuleSourceReadClient gameDesignReader = + mock(GameplayRuleSourceReadClient.class); + private final AtomicReference stored = + new AtomicReference<>(); + private final GameLogicGameplayRuleIntakeService service = + new GameLogicGameplayRuleIntakeService( + repository, new UnitTransactionManager(), accountReader, gameDesignReader, NAMESPACE); + + private Fixture() { + when(repository.findTerminal(any(UUID.class))) + .thenAnswer(ignored -> Optional.ofNullable(stored.get())); + org.mockito.Mockito.doAnswer( + invocation -> { + stored.set(invocation.getArgument(0)); + return null; + }) + .when(repository) + .insertTerminal(any(GameLogicGameplayRuleIntakeTerminal.class)); + } + + private void repositoryFindsStored() { + when(repository.findTerminal(any(UUID.class))) + .thenAnswer(ignored -> Optional.ofNullable(stored.get())); + } + + private void respondFor( + GameLogicIntakeAuthorizationBinding authorization, GameplayRuleSelectedSource selected) { + respondAuthorizationOnly(authorization); + when(gameDesignReader.read(any(GameplayRuleSourceReadEvidence.Request.class))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var request = invocation.getArgument(0); + return new GameplayRuleSourceReadEvidence(request, selected); + }); + } + + private void respondAuthorizationOnly(GameLogicIntakeAuthorizationBinding authorization) { + when(accountReader.read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var request = + invocation.getArgument(0); + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.binding()).isEqualTo(authorization); + return new GameLogicIntakeAuthorizationReadEvidence(request); + }); + } + } + + private static final class UnitTransactionManager implements PlatformTransactionManager { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + var actualDefinition = definition == null ? TransactionDefinition.withDefaults() : definition; + assertThat(actualDefinition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) {} + + @Override + public void rollback(TransactionStatus status) {} + } +} diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationSourceReadServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationSourceReadServiceTest.java new file mode 100644 index 0000000000..a799f990ff --- /dev/null +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationSourceReadServiceTest.java @@ -0,0 +1,375 @@ +package net.firedevops.firemud.gamelogic.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding; +import net.firedevops.firemud.common.gamelogic.GameplayAbilitySchemaProjection; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Uses a repository stub to exercise the owner read boundary. It does not claim PostgreSQL storage + * provenance; the repository's existing physical readback is responsible for indexed-row proof. + */ +class GameLogicPublicationSourceReadServiceTest { + private static final String NAMESPACE = "test"; + + @AfterEach + void clearThreadState() { + if (TransactionSynchronizationManager.isSynchronizationActive()) + TransactionSynchronizationManager.clearSynchronization(); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + + @Test + void returnsExactStoredTerminalAndBothDistinctCanonicalDigests() { + var fixture = new Fixture(); + var authorization = authorization(); + var stored = retained(authorization); + fixture.store(stored); + var binding = request(authorization); + + var result = asGameDesign(() -> fixture.service.read(binding)); + + assertThat(result.binding()).isSameAs(binding); + assertThat(result.terminal()).isSameAs(stored); + assertThat(result.operation().canonicalBytes()) + .containsExactly(stored.operation().canonicalBytes()); + assertThat(result.authorizationBytes()).containsExactly(authorization.canonicalBytes()); + assertThat(result.selectedSourceBytes()) + .containsExactly(authorization.source().canonicalBytes()); + assertThat(result.manifestBytes()) + .containsExactly(authorization.source().manifest().canonicalBytes()); + assertThat(result.manifestDigest()).isEqualTo(authorization.source().manifest().digest()); + assertThat(result.abilitySchemaDigest()) + .isEqualTo(GameplayAbilitySchemaProjection.digest(authorization.source().manifest())) + .isNotEqualTo(result.manifestDigest()); + assertThat(result.digestSchemaVersion()).isEqualTo(1); + assertThat(result.canonicalization()).isEqualTo("RFC8785"); + assertThat(result.terminalBytes()).containsExactly(stored.canonicalBytes()); + + byte[] returnedSource = result.selectedSourceBytes(); + returnedSource[0] ^= 1; + assertThat(result.selectedSourceBytes()) + .containsExactly(authorization.source().canonicalBytes()); + verify(fixture.repository).findTerminal(authorization.operationId()); + } + + @Test + void exactRetryReadsTheOriginalTerminalWithoutAccountOrLatestSourceReads() { + var fixture = new Fixture(); + var authorization = authorization(); + var stored = retained(authorization); + fixture.store(stored); + var binding = request(authorization); + + var first = asGameDesign(() -> fixture.service.read(binding)); + var retry = asGameDesign(() -> fixture.service.read(binding)); + + assertThat(retry.terminal()).isSameAs(stored); + assertThat(retry.terminalBytes()).containsExactly(first.terminalBytes()); + assertThat(retry.binding().canonicalBytes()).containsExactly(binding.canonicalBytes()); + // This service has only the owner repository dependency, so settlement cannot trigger a HELD + // read and retry cannot resolve a newer source snapshot. + verify(fixture.repository, times(2)).findTerminal(authorization.operationId()); + } + + @Test + void absentAndAbortedOperationsFailClosed() { + var fixture = new Fixture(); + var authorization = authorization(); + var binding = request(authorization); + + assertCode( + Status.Code.FAILED_PRECONDITION, () -> asGameDesign(() -> fixture.service.read(binding))); + + var aborted = + GameLogicGameplayRuleIntakeTerminal.aborted( + new GameLogicGameplayRuleIntakeOperation(NAMESPACE, authorization)); + fixture.store(aborted); + assertCode( + Status.Code.FAILED_PRECONDITION, () -> asGameDesign(() -> fixture.service.read(binding))); + } + + @Test + void onlyExactSameNamespaceGameDesignCanReadAndAuthenticationPrecedesBindingInspection() { + var fixture = new Fixture(); + List deniedPeers = + List.of( + peer("test", "account-service"), + peer("test", "game-logic-service"), + peer("test", "world-management-service"), + peer("other", "game-design-service")); + + for (GrpcPeerIdentity peer : deniedPeers) { + assertCode( + Status.Code.PERMISSION_DENIED, () -> asPeer(peer, () -> fixture.service.read(null))); + } + assertCode(Status.Code.UNAUTHENTICATED, () -> fixture.service.read(null)); + verify(fixture.repository, never()).findTerminal(any(UUID.class)); + + assertCode(Status.Code.INVALID_ARGUMENT, () -> asGameDesign(() -> fixture.service.read(null))); + verify(fixture.repository, never()).findTerminal(any(UUID.class)); + } + + @Test + void ambientSqlOrSynchronizationIsRejectedBeforeStorageRead() { + var fixture = new Fixture(); + var authorization = authorization(); + var binding = request(authorization); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertCode( + Status.Code.FAILED_PRECONDITION, () -> asGameDesign(() -> fixture.service.read(binding))); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + TransactionSynchronizationManager.initSynchronization(); + try { + assertCode( + Status.Code.FAILED_PRECONDITION, () -> asGameDesign(() -> fixture.service.read(binding))); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + verify(fixture.repository, never()).findTerminal(any(UUID.class)); + } + + @Test + void changedOperationFenceCommitAndSelectedSourceAreRejected() { + var original = authorization(); + var stored = retained(original); + + var changedOperation = copy(original, UUID.randomUUID(), original.fenceId(), original.source()); + assertStoredMismatch(stored, changedOperation); + + var changedFence = copy(original, original.operationId(), UUID.randomUUID(), original.source()); + assertStoredMismatch(stored, changedFence); + + var originalCommit = original.source().binding(); + var changedCommit = + DraftCommitBinding.create( + originalCommit.target(), + originalCommit.requestId(), + UUID.randomUUID(), + originalCommit.baseCommitId(), + originalCommit.revisions(), + originalCommit.affectedUnits()); + var changedCommitAuthorization = + copy(original, original.operationId(), original.fenceId(), source(changedCommit, "1")); + assertStoredMismatch(stored, changedCommitAuthorization); + + var changedSource = + copy(original, original.operationId(), original.fenceId(), source(originalCommit, "2")); + assertStoredMismatch(stored, changedSource); + } + + @Test + void changedScopeAliasesAndManifestReadbackAreRejected() { + var authorization = authorization(); + var wrongNumericVersion = + PublicationDigestRequestBinding.full( + authorization.tenantId().toString(), + Long.toString(authorization.source().binding().target().gameDesignVersionRowId() + 1), + "publish-request"); + assertThatThrownBy( + () -> new GameLogicPublicationSourceReadBinding(wrongNumericVersion, authorization)) + .isInstanceOf(IllegalArgumentException.class); + + var patch = + PublicationDigestRequestBinding.patch( + authorization.tenantId().toString(), "1", "patch-v1", "publish-request"); + assertThatThrownBy(() -> new GameLogicPublicationSourceReadBinding(patch, authorization)) + .isInstanceOf(IllegalArgumentException.class); + + var fixture = new Fixture(); + var validTerminal = retained(authorization); + var corruptReadback = mock(GameLogicGameplayRuleIntakeTerminal.class); + when(corruptReadback.operation()).thenReturn(validTerminal.operation()); + when(corruptReadback.authorizationBytes()).thenReturn(validTerminal.authorizationBytes()); + when(corruptReadback.outcome()) + .thenReturn(GameLogicGameplayRuleIntakeTerminal.Outcome.RETAINED); + when(corruptReadback.selectedSourceBytes()).thenReturn(validTerminal.selectedSourceBytes()); + when(corruptReadback.manifestBytes()).thenReturn("{}".getBytes(StandardCharsets.UTF_8)); + fixture.store(corruptReadback); + + assertCode( + Status.Code.ALREADY_EXISTS, + () -> asGameDesign(() -> fixture.service.read(request(authorization)))); + } + + private static void assertStoredMismatch( + GameLogicGameplayRuleIntakeTerminal stored, + GameLogicIntakeAuthorizationBinding requestedAuthorization) { + var fixture = new Fixture(); + fixture.store(stored); + assertCode( + Status.Code.ALREADY_EXISTS, + () -> asGameDesign(() -> fixture.service.read(request(requestedAuthorization)))); + } + + private static void assertCode(Status.Code expected, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies(error -> assertThat(Status.fromThrowable(error).getCode()).isEqualTo(expected)); + } + + private static GameLogicIntakeAuthorizationBinding copy( + GameLogicIntakeAuthorizationBinding original, + UUID operationId, + UUID fenceId, + GameplayRuleSelectedSource source) { + return new GameLogicIntakeAuthorizationBinding( + operationId, + fenceId, + original.intakeRequestId(), + original.actorAccountId(), + source, + original.sources()); + } + + private static GameLogicIntakeAuthorizationBinding authorization() { + var actor = UUID.randomUUID(); + var selected = source(commitBinding(), "1"); + var accountSource = + new net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence( + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind + .ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + return new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + selected, + List.of(accountSource)); + } + + private static DraftCommitBinding commitBinding() { + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 17, "private", 29, "private", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "0", + "0"))); + } + + private static GameplayRuleSelectedSource source(DraftCommitBinding binding, String epoch) { + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", binding.canonicalJson(), + "bindingDigest", binding.digest(), + "sourceEpoch", epoch, + "inheritedCommitId", "", + "genesisReceiptId", UUID.randomUUID().toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + } + + private static GameLogicPublicationSourceReadBinding request( + GameLogicIntakeAuthorizationBinding authorization) { + var target = authorization.source().binding().target(); + return new GameLogicPublicationSourceReadBinding( + PublicationDigestRequestBinding.full( + authorization.tenantId().toString(), + Long.toString(target.gameDesignVersionRowId()), + "publish-request"), + authorization); + } + + private static GameLogicGameplayRuleIntakeTerminal retained( + GameLogicIntakeAuthorizationBinding authorization) { + return GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation(NAMESPACE, authorization), + authorization.source().canonicalBytes(), + authorization.source().manifest().canonicalBytes()); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow(); + } + + private static T asGameDesign(java.util.function.Supplier action) { + return asPeer(peer(NAMESPACE, "game-design-service"), action); + } + + private static T asPeer(GrpcPeerIdentity peer, java.util.function.Supplier action) { + return asContext(Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer), action); + } + + private static T asContext(Context context, java.util.function.Supplier action) { + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private static final class Fixture { + private final GameLogicGameplayRuleIntakeRepository repository = + mock(GameLogicGameplayRuleIntakeRepository.class); + private final AtomicReference terminal = + new AtomicReference<>(); + private final GameLogicPublicationSourceReadService service = + new GameLogicPublicationSourceReadService(repository, NAMESPACE); + + private Fixture() { + when(repository.findTerminal(any(UUID.class))) + .thenAnswer(invocation -> Optional.ofNullable(terminal.get())); + } + + private void store(GameLogicGameplayRuleIntakeTerminal value) { + terminal.set(value); + } + } +} From c8fcf362955182efb0864fb7f40551029e0490e7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 16:05:37 +1300 Subject: [PATCH 02/14] Qualify selected gameplay-rule retention and exact owner settlement --- .../game-logic-service/runtime-and-data.md | 4 +- design/project-management/ai-observations.md | 2 + .../gameplay-rules-entities-and-effects.md | 4 +- .../AccountControlUiOriginalOrderFixture.java | 14 ++ services/game-design-service/build.gradle.kts | 8 + ...ameLogicIntakePostgresIntegrationTest.java | 65 ++++----- services/game-logic-service/build.gradle.kts | 6 + .../GameLogicGameplayRuleIntakeService.java | 8 +- ...immutable_gameplay_rule_source_intake.sql} | 0 ...playRuleIntakePostgresIntegrationTest.java | 137 ++++++++++++++++++ ...ameLogicGameplayRuleIntakeServiceTest.java | 40 ++++- 11 files changed, 244 insertions(+), 44 deletions(-) rename services/game-logic-service/src/main/resources/db/migration/{V2__immutable_gameplay_rule_source_intake.sql => V1003__immutable_gameplay_rule_source_intake.sql} (100%) diff --git a/design/architecture/microservices/game-logic-service/runtime-and-data.md b/design/architecture/microservices/game-logic-service/runtime-and-data.md index aac2fdd985..f9812c20b9 100644 --- a/design/architecture/microservices/game-logic-service/runtime-and-data.md +++ b/design/architecture/microservices/game-logic-service/runtime-and-data.md @@ -4,7 +4,7 @@ This document defines the Game Logic Service runtime model, dependency ownership ## Implementation Status -The prepared selected gameplay-rule intake repository, terminal owner and publication source reader are standalone and unregistered. Their forward V2 storage does not enable runtime rule consumption or replace the existing legacy digest handler. [The implementation tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) owns qualification and composition limits. +The prepared selected gameplay-rule intake repository, terminal owner and publication source reader are standalone and unregistered. Their forward V1003 storage does not enable runtime rule consumption or replace the existing legacy digest handler. [The implementation tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) owns qualification and composition limits. The sections below define the target-state runtime contract. Current implementation and proof status is: @@ -27,7 +27,7 @@ The sections below define the target-state runtime contract. Current implementat - The target runtime contract is that every player-delegated gameplay RPC carries the complete validated typed `PlayerExecutionContext`, including `tenantId`, `playableStateNamespaceId`, server-derived `playableStateScope`, active `gameInstanceId`, and applicable region/epoch or executor fences. The live per-RPC schemas, including `SendCommunication` and its legacy `session_attestation`, remain an implementation gap; see the [PlayerExecutionContext contract](../../system-architecture-authentication.md#gameplay-player-execution-context-contract-normative). - Gameplay gRPC requests do not include JWTs. Game Session provides player identity from Redis via `SessionContext`, may refresh a JWT from Account Service if roles change, and does not validate tokens for gameplay. Service-to-service traffic still uses mutual TLS as described in the [Security Architecture](../../system-architecture-security.md). - Utilizes the [Shared Libraries](../../system-architecture-shared-libraries.md) for DTO definitions, logging interceptors, and Micrometer metrics. -- Flyway V1 is the existing empty baseline; the prepared V2 adds immutable selected gameplay-rule intake storage. Its qualification and inactive runtime consequences are recorded in the implementation tracker above. +- Flyway V1 is the existing empty baseline; the prepared V1003 follows the retained Saga V1000–V1002 history and adds immutable selected gameplay-rule intake storage. Its qualification and inactive runtime consequences are recorded in the implementation tracker above. - NPC morale and aggression-state evaluation remain part of this service's runtime behavior. When gameplay rules consume faction or reputation signals sourced from Social & Groups, the local morale logic is still owned here, including transitions such as `FLEEING` and `SURRENDERED`; cross-service reputation data informs the decision, but Game Logic owns the gameplay-state consequence. ## Workflow Participation diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 27a045011e..60f0dc94ab 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -336,3 +336,5 @@ Entry format: - Context: Document R57/R65 and Gameplay #2967 failed with a 1.4 GiB maximum heap amid repeated garbage-collection thrashing. The receiving task passed with a per-run 3 GiB heap in 1m27s, while WSL was configured with a 10 GB limit and had 5.2–6.8 GiB available without swap-out or OOM evidence. - Observation: the repeated failures support a higher shared local daemon heap for serialized work; the passing run was mostly up-to-date and does not establish cold-build speedup or a total-memory guarantee. - Qualification: the 3 GiB setting is not a restoration of an earlier default; the shared 1500m setting predates the recent guard since August 28. Worker, test, and code-generation JVM memory remains additional, and the hosted module runner's explicit 2500m setting is unchanged. + +- `2026-10-15`: Classes-only foreign-owner proof artifacts intentionally omit application and Flyway resources. A composed test that reads another owner’s migrations from disk must declare those directories as task inputs; otherwise a SQL-only change can leave the composition up-to-date. The selected Game Logic proof exposed this after its forward migration was reconciled, and Game Design now tracks the foreign Game Logic and World migration directories. diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index f1c2febc5f..5174c90b39 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -8,9 +8,9 @@ This is a non-normative implementation tracker for gameplay rules, entities, and ### Selected gameplay-rule retention and receipt composition -The prepared standalone Game Logic intake owner requires the exact Account HELD authorization and selected synchronized Game Design source before retaining an immutable terminal. The Game Design selected-intake command and receipt owners compose that retention with Account-owned terminal settlement and persist the exact receipt under existing GDS V1009. New Game Logic V2 follows the empty V1 baseline; existing Account and GDS migration history stays unchanged. None of these owners or read adapters is registered, and the current legacy digest receiver and runtime rule consumption remain separate. +The prepared standalone Game Logic intake owner requires the exact Account HELD authorization and selected synchronized Game Design source before retaining an immutable terminal. The Game Design selected-intake command and receipt owners compose that retention with Account-owned terminal settlement and persist the exact receipt under existing GDS V1009. New Game Logic V1003 follows the empty owned V1 baseline and the shared Saga V1000–V1002 history; existing Account and GDS migration history stays unchanged. None of these owners or read adapters is registered, and the current legacy digest receiver and runtime rule consumption remain separate. -Compilation, jOOQ generation, focused static/format and physical qualification remain pending. The prepared multi-owner proof uses the actual Game Design-plus-World source commit, World graph application, Account original settlement, selected source export, Game Logic retention and Account intake settlement, with test-only PKI and controlled upstream issuer/environment/source identity inputs. The durable selection is reserved directly through its owner repository; this is not proof of the separate selected-publication command, genuine deployed authoring or release authority. The actual pipeline must qualify before any launch-descriptor consumer may use its receipt. Entity schema 3, Automation schema 6, selected-full attestation 4, activation, placement and delivery remain unfinished; all genuine Gameplay handoffs and Unit 1B/corpus holds remain open. Canonical ownership remains in [Game Logic runtime/data](../../architecture/microservices/game-logic-service/runtime-and-data.md), [Game Design version control](../../architecture/microservices/game-design-service/version-control.md) and the [Account prerequisite tracker](./player-access-and-session.md#selected-gameplay-rule-intake-authorization-prerequisite). +The corrected Game Logic full gate passes in 1m49s, freshly executing nine PostgreSQL cases with zero failures, errors or skips, including the actual V1 plus Saga V1000–V1002 upgrade, unchanged parent history and retained Saga bytes/xmin. The separate Game Design full gate passes in 3m14s with all 25 composed cases freshly executed without skips after its foreign Game Logic and World migration directories were declared as task inputs. Game Logic’s 114 unit cases retain the preceding fresh result, while unchanged Game Design 575 unit and 142 ordinary native results retain their original qualification attribution. Owning jOOQ generation, static/format and documentation checks pass. The prepared multi-owner proof uses the actual Game Design-plus-World source commit, World graph application, Account original settlement, selected source export, Game Logic retention and Account intake settlement, with test-only PKI and controlled upstream issuer/environment/source identity inputs. The durable selection is reserved directly through its owner repository; this is not proof of the separate selected-publication command, genuine deployed authoring or release authority. This qualifies the controlled standalone pipeline; the launch-descriptor consumer and genuine release authority remain separate qualifications. Entity schema 3, Automation schema 6, selected-full attestation 4, activation, placement and delivery remain unfinished; all genuine Gameplay handoffs and Unit 1B/corpus holds remain open. Canonical ownership remains in [Game Logic runtime/data](../../architecture/microservices/game-logic-service/runtime-and-data.md), [Game Design version control](../../architecture/microservices/game-design-service/version-control.md) and the [Account prerequisite tracker](./player-access-and-session.md#selected-gameplay-rule-intake-authorization-prerequisite). ### Selected gameplay-rule intake prerequisite diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index 617335e9e9..065763d6e7 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -208,6 +208,20 @@ public UUID tenantId() { return f.tenant; } + /** + * Real Account-owned selected Game Logic source reads over this fixture's SQL and Coordination + * Redis owners; callers choose the clock and target namespace for their composition. + */ + public AccountGameLogicIntakeSourceReadService gameLogicIntakeSourceReadService( + Clock clock, String namespace) { + return new AccountGameLogicIntakeSourceReadService( + new AccountGameLogicIntakeAuthorizationRepository(f.dsl), + coordination, + f.manager, + clock, + namespace); + } + /** * Real Account control-UI creator retained for composition with the original StartSession proof. */ diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts index 71a13035f9..561b0e0de3 100644 --- a/services/game-design-service/build.gradle.kts +++ b/services/game-design-service/build.gradle.kts @@ -63,3 +63,11 @@ val gameDesignClassesProof by configurations.creating { extendsFrom(configurations.implementation.get()) outgoing.artifact(gameDesignClassesProofJar) } + +// Composed owner proofs load foreign migrations from disk; classes-only artifacts omit them. +tasks.named("crossServiceTest") { + inputs.dir(rootProject.layout.projectDirectory.dir("services/game-logic-service/src/main/resources/db/migration")) + .withPropertyName("gameLogicOwnerMigrations") + inputs.dir(rootProject.layout.projectDirectory.dir("services/world-management-service/src/main/resources/db/migration")) + .withPropertyName("worldOwnerMigrations") +} diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java index aa393d8d13..d00edadd7b 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java @@ -52,6 +52,7 @@ import net.firedevops.firemud.common.gamelogic.GrpcGameLogicIntakeSourceReadClient; 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.tenant.AuthoredWorldSourceClient; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; @@ -75,14 +76,15 @@ import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt; import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptRepository; import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptService; -import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldSourceReadGrpcService; import net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldVersionStateGrpcService; import net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldVersionStateService; import net.firedevops.firemud.gamedesign.service.impl.TenantIdentityGrpcService; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeGrpcService; import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeRepository; import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeService; @@ -112,7 +114,6 @@ import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceClosureDeclaration; import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamily; import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamilyCount; -import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationRevision; import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; @@ -212,12 +213,7 @@ void controlledCreatorAndWorldFixturesDriveActualOwnersThroughExactIntakeAndRece var accountRepository = new AccountGameLogicIntakeAuthorizationRepository(accountAccess.sources().dsl); var accountSourcePermissionOwner = - new AccountGameLogicIntakeSourceReadService( - accountRepository, - account.coordination(), - accountAccess.sources().manager, - Clock.systemUTC(), - NAMESPACE); + account.gameLogicIntakeSourceReadService(Clock.systemUTC(), NAMESPACE); var accountHeldReadOwner = new AccountGameLogicIntakeAuthorizationReadService( accountRepository, accountAccess.sources().manager, NAMESPACE); @@ -246,7 +242,8 @@ void controlledCreatorAndWorldFixturesDriveActualOwnersThroughExactIntakeAndRece worldServer = startServer(pki, pki.worldServer(), worldHandlers); endpoints.setWorldManagementService(loopback(worldServer)); - registerWorldSourceIdentity(local, world, endpoints, pki, gameDesignHandlers, worldHandlers); + registerWorldSourceIdentity( + local, world, endpoints, pki, gameDesignHandlers, worldHandlers); var binding = binding(local, "genuine-admission"); var reviewedBaseOwner = new GameDesignReviewedBaseRepository(local.dsl()); transaction(local) @@ -257,7 +254,8 @@ void controlledCreatorAndWorldFixturesDriveActualOwnersThroughExactIntakeAndRece local.target(), DraftBaseReference.parse(binding.baseCommitId())); new GameDesignSourceRepository(local.dsl()).claimReviewed(binding, reviewedBase); var retained = reviewedBaseOwner.requireCurrentRetained(binding); - assertThat(retained.canonicalBytes()).containsExactly(reviewedBase.canonicalBytes()); + assertThat(retained.canonicalBytes()) + .containsExactly(reviewedBase.canonicalBytes()); assertThat(retained.digest()).isEqualTo(reviewedBase.digest()); return null; }); @@ -378,9 +376,9 @@ void controlledCreatorAndWorldFixturesDriveActualOwnersThroughExactIntakeAndRece var worldFence = new WorldDesignPublicationFenceRepository(world.dsl(), worldIntakes); var mapper = new tools.jackson.databind.ObjectMapper(); var worldApplications = - new WorldDraftGraphApplicationRepository( - world.dsl(), worldFence, mapper); - var worldTerminals = new WorldDraftTerminalOutcomeRepository(world.dsl(), worldFence, mapper); + new WorldDraftGraphApplicationRepository(world.dsl(), worldFence, mapper); + var worldTerminals = + new WorldDraftTerminalOutcomeRepository(world.dsl(), worldFence, mapper); var worldApplicationService = new WorldDraftGraphApplicationService( worldApplications, @@ -393,7 +391,8 @@ void controlledCreatorAndWorldFixturesDriveActualOwnersThroughExactIntakeAndRece accountHandlers, Map.of(), account.originalDraftOrderProducer(NAMESPACE), - new net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadGrpcService( + new net.firedevops.firemud.accountservice.authordraft + .AccountDraftCommitOrderReadGrpcService( account.heldOrderOwner(NAMESPACE), NAMESPACE), new AccountGameLogicIntakeAuthorizationGrpcService( accountAuthorizationOwner, accountAccess.sources().terms, NAMESPACE), @@ -467,11 +466,12 @@ void controlledCreatorAndWorldFixturesDriveActualOwnersThroughExactIntakeAndRece assertSynchronizedSource(local, original); account.assertOriginalDraftOrderPending(original); - account.reconcileOriginalDraft( - original, - originalTerminalClient, - accountToWorldTerminal, - NAMESPACE); + var originalTerminalReconciler = + account.terminalReconciler(originalTerminalClient, accountToWorldTerminal, NAMESPACE); + assertThat(originalTerminalReconciler.reconcile(original.operationId())) + .contains(DraftAuthorizationFenceRepository.Settlement.COMMITTED); + account.assertOriginalDraftSettlement( + original, DraftAuthorizationFenceRepository.Settlement.COMMITTED); assertThat(gameDesignTerminalReads).hasValue(1); assertThat(worldTerminalReads).hasValue(1); assertThat(gameDesignSourceReads).hasValue(0); @@ -631,15 +631,10 @@ private static void assertSynchronizedSource( new GameDesignSourceRepository(local.dsl()) .readSynchronized(local.target(), original.commitId()) .orElseThrow(); - assertThat( - snapshot - .gameplay() - .manifest() - .families() - .get(GameplayRuleManifest.Family.ADMISSION_TAGS)) + var gameplay = snapshot.gameplayEvidence().orElseThrow(); + assertThat(gameplay.manifest().families().get(GameplayRuleManifest.Family.ADMISSION_TAGS)) .hasSize(1); - assertThat(snapshot.gameplay().binding().canonicalBytes()) - .containsExactly(original.gameDesignBinding()); + assertThat(gameplay.binding().canonicalBytes()).containsExactly(original.gameDesignBinding()); } private void registerWorldSourceIdentity( @@ -833,7 +828,9 @@ private WorldStore worldStore() { var schema = "world_management_" + UUID.randomUUID().toString().replace("-", ""); var data = new DriverManagerDataSource( - WORLD_POSTGRES.getJdbcUrl(), WORLD_POSTGRES.getUsername(), WORLD_POSTGRES.getPassword()); + WORLD_POSTGRES.getJdbcUrl(), + WORLD_POSTGRES.getUsername(), + WORLD_POSTGRES.getPassword()); data.setSchema(schema); Flyway.configure() .dataSource(data) @@ -849,7 +846,8 @@ private WorldStore worldStore() { } private DraftCommitBinding binding(Local local, String admissionTag) throws Exception { - var genesis = new GameDesignSourceRepository(local.dsl()).readGenesis(local.target()).orElseThrow(); + var genesis = + new GameDesignSourceRepository(local.dsl()).readGenesis(local.target()).orElseThrow(); String baseCommitId = "genesis:" + genesis.policy().receiptId(); UUID commit = UUID.randomUUID(); UUID region = UUID.randomUUID(); @@ -902,14 +900,16 @@ private DraftCommitBinding binding(Local local, String admissionTag) throws Exce .build(); var mutations = List.of( - mutation(commit, room, region, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + mutation( + commit, room, region, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) .setRoom( RoomDesignMutation.newBuilder() .setName("Controlled room") .setZoneId(zone.toString()) .setDescription("Controlled original World source fixture")) .build(), - mutation(commit, zone, region, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE) + mutation( + commit, zone, region, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE) .setZone( ZoneDesignMutation.newBuilder() .setName("Controlled zone") @@ -950,8 +950,7 @@ private DraftCommitBinding binding(Local local, String admissionTag) throws Exce UUID.fromString(mutation.getLogicalRevisionId()), DraftCommitBinding.Owner.WORLD_MANAGEMENT, JsonFormat.printer().omittingInsignificantWhitespace().print(mutation))); - var family = - mutation.getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + var family = mutation.getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); units.add( new DraftCommitBinding.AffectedUnit( DraftCommitBinding.Owner.WORLD_MANAGEMENT, diff --git a/services/game-logic-service/build.gradle.kts b/services/game-logic-service/build.gradle.kts index 963092bfd6..f453f77424 100644 --- a/services/game-logic-service/build.gradle.kts +++ b/services/game-logic-service/build.gradle.kts @@ -4,6 +4,12 @@ apply(from = "${rootDir}/gradle/proto-convention.gradle") plugins { id("net.firedevops.firemud.service-conventions") id("net.firedevops.firemud.openapi-conventions") + id("net.firedevops.firemud.sql-postgres-conventions") + id("net.firedevops.firemud.jooq-conventions") +} + +firemudJooq { + packageName.set("net.firedevops.firemud.gamelogic.jooq") } dependencies { diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java index 9a67751c45..c140b65876 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java @@ -5,6 +5,8 @@ import java.util.Arrays; import java.util.Objects; import java.util.Optional; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials; import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadClient; @@ -12,7 +14,6 @@ import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -163,9 +164,10 @@ private GameLogicGameplayRuleIntakeOperation requestOperation( .withDescription("Exact same-namespace Game Design workload required") .asRuntimeException(); } - if (AccountSelectedPublicationOrderCredentials.CONTEXT_KEY.get() != null) { + if (AccountOriginalDraftOrderCredentials.CONTEXT_KEY.get() != null + || AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY.get() != null) { throw Status.PERMISSION_DENIED - .withDescription("Creator publication credentials cannot accompany GL source intake") + .withDescription("Creator credentials cannot accompany GL source intake") .asRuntimeException(); } if (authorization == null) { diff --git a/services/game-logic-service/src/main/resources/db/migration/V2__immutable_gameplay_rule_source_intake.sql b/services/game-logic-service/src/main/resources/db/migration/V1003__immutable_gameplay_rule_source_intake.sql similarity index 100% rename from services/game-logic-service/src/main/resources/db/migration/V2__immutable_gameplay_rule_source_intake.sql rename to services/game-logic-service/src/main/resources/db/migration/V1003__immutable_gameplay_rule_source_intake.sql diff --git a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java index efe1be831c..2ee36dbed3 100644 --- a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java +++ b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java @@ -12,8 +12,11 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; @@ -38,6 +41,7 @@ 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; @@ -55,6 +59,134 @@ class GameLogicGameplayRuleIntakePostgresIntegrationTest { static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Test + void upgradesActualV1AndSagaParentWithoutChangingHistoryOrRetainedSagaData( + @TempDir Path temporary) throws Exception { + String schema = "gl_" + UUID.randomUUID().toString().replace("-", ""); + String historyTable = "flyway_schema_history_" + schema; + var dataSource = new DriverManagerDataSource(); + dataSource.setUrl(POSTGRES.getJdbcUrl()); + dataSource.setUsername(POSTGRES.getUsername()); + dataSource.setPassword(POSTGRES.getPassword()); + dataSource.setSchema(schema); + Path parentMigrationDirectory = Files.createDirectory(temporary.resolve("installed-parent")); + var v1Resource = + Objects.requireNonNull( + getClass().getClassLoader().getResourceAsStream("db/migration/V1__init.sql")); + try (v1Resource) { + Files.copy(v1Resource, parentMigrationDirectory.resolve("V1__init.sql")); + } + + org.flywaydb.core.Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .table(historyTable) + .locations("filesystem:" + parentMigrationDirectory, "classpath:db/migration/saga") + .load() + .migrate(); + + var dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var installedParents = migrationHistory(dsl, historyTable); + assertThat(installedParents) + .extracting(MigrationHistory::version) + .containsExactly("1", "1000", "1001", "1002"); + assertThat(installedParents) + .extracting(MigrationHistory::script) + .containsExactly( + "V1__init.sql", + "V1000__create_saga_schema.sql", + "V1001__saga_instance_table.sql", + "V1002__saga_step_table.sql"); + assertThat(installedParents) + .allSatisfy( + row -> { + assertThat(row.checksum()).isNotNull(); + assertThat(row.success()).isTrue(); + }); + long intakeTablesBeforeUpgrade = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM information_schema.tables " + + "WHERE table_schema = ? AND table_name = 'game_logic_gameplay_rule_intake_terminal'", + schema)) + .get(0, Long.class); + assertThat(intakeTablesBeforeUpgrade).isZero(); + // V1 is empty; retain an actual shared Saga row to detect changes to the installed parent. + var insertedSaga = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO " + + schema + + ".saga_instance (saga_name, state) VALUES (?, ?) RETURNING id", + "retained-parent-saga", + "RUNNING")); + long sagaId = insertedSaga.get("id", Long.class); + var retainedSagaBefore = sagaSnapshot(dsl, schema, sagaId); + + org.flywaydb.core.Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .table(historyTable) + .locations("classpath:db/migration", "classpath:db/migration/saga") + .load() + .migrate(); + + var upgradedHistory = migrationHistory(dsl, historyTable); + assertThat(upgradedHistory) + .extracting(MigrationHistory::version) + .containsExactly("1", "1000", "1001", "1002", "1003"); + assertThat(upgradedHistory.subList(0, installedParents.size())) + .containsExactlyElementsOf(installedParents); + var installedIntake = upgradedHistory.getLast(); + assertThat(installedIntake.script()) + .isEqualTo("V1003__immutable_gameplay_rule_source_intake.sql"); + assertThat(installedIntake.installedRank()) + .isGreaterThan(installedParents.getLast().installedRank()); + assertThat(installedIntake.checksum()).isNotNull(); + assertThat(installedIntake.success()).isTrue(); + assertThat(sagaSnapshot(dsl, schema, sagaId)).isEqualTo(retainedSagaBefore); + long intakeTablesAfterUpgrade = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM information_schema.tables " + + "WHERE table_schema = ? AND table_name = 'game_logic_gameplay_rule_intake_terminal'", + schema)) + .get(0, Long.class); + assertThat(intakeTablesAfterUpgrade).isEqualTo(1L); + assertThat(dsl.fetchCount(DSL.table("game_logic_gameplay_rule_intake_terminal"))).isZero(); + } + + private static List migrationHistory(DSLContext dsl, String historyTable) { + return dsl.fetch( + "SELECT installed_rank, version, script, checksum, success FROM " + + historyTable + + " WHERE version IS NOT NULL ORDER BY installed_rank") + .map( + row -> + new MigrationHistory( + row.get("installed_rank", Integer.class), + row.get("version", String.class), + row.get("script", String.class), + row.get("checksum", Integer.class), + row.get("success", Boolean.class))); + } + + private static SagaRowSnapshot sagaSnapshot(DSLContext dsl, String schema, long sagaId) { + var row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT encode(convert_to(to_jsonb(saga_instance)::text, 'UTF8'), 'hex') AS row_bytes, " + + "xmin::text AS xmin FROM " + + schema + + ".saga_instance WHERE id = ?", + sagaId)); + return new SagaRowSnapshot(row.get("row_bytes", String.class), row.get("xmin", String.class)); + } + @Test void exactConcurrentRetriesRetainOneImmutableOriginalTerminalAndReadItWithoutOwnerReads() throws Exception { @@ -439,6 +571,11 @@ private static void assertReadDenied( failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); } + private record MigrationHistory( + Integer installedRank, String version, String script, Integer checksum, Boolean success) {} + + private record SagaRowSnapshot(String rowBytes, String xmin) {} + private record Fixture( DSLContext dsl, DataSourceTransactionManager transactionManager, diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java index 30a8b35ef7..6bec90c034 100644 --- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java @@ -18,8 +18,10 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials; import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; @@ -30,7 +32,6 @@ import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; import org.junit.jupiter.api.Test; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; @@ -267,7 +268,7 @@ void onlyTheExactSameNamespaceGameDesignPeerCanInvokeTheOwner() { } @Test - void creatorPublicationCredentialCannotBeMixedWithTheServicePeer() { + void creatorIntakeCredentialCannotBeMixedWithTheServicePeer() { var fixture = new Fixture(); var authorization = authorization(); var peer = @@ -277,8 +278,8 @@ void creatorPublicationCredentialCannotBeMixedWithTheServicePeer() { Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) .withValue( - AccountSelectedPublicationOrderCredentials.CONTEXT_KEY, - AccountSelectedPublicationOrderCredentials.Credential.of( + AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY, + AccountGameLogicIntakeAuthorizationCredentials.Credential.of( "creator-order-credential")); Context previous = request.attach(); try { @@ -298,6 +299,37 @@ void creatorPublicationCredentialCannotBeMixedWithTheServicePeer() { .read(any(GameplayRuleSourceReadEvidence.Request.class)); } + @Test + void originalDraftCredentialCannotBeMixedWithTheServicePeer() { + var fixture = new Fixture(); + var authorization = authorization(); + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-design-service", NAMESPACE, "game-design-service"); + Context request = + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .withValue( + AccountOriginalDraftOrderCredentials.CONTEXT_KEY, + AccountOriginalDraftOrderCredentials.Credential.of("creator-order-credential")); + Context previous = request.attach(); + try { + assertThatThrownBy(() -> fixture.service.retain(authorization)) + .isInstanceOf(RuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } finally { + Context.current().detach(previous); + } + verify(fixture.repository, never()).findTerminal(any(UUID.class)); + verify(fixture.accountReader, never()) + .read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class)); + verify(fixture.gameDesignReader, never()) + .read(any(GameplayRuleSourceReadEvidence.Request.class)); + } + private static T asAccount(java.util.function.Supplier action) { var context = Context.current() From 2f20e832f1fb0803cbfecc13e754042f242bdba4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 17 Oct 2026 04:49:00 +1300 Subject: [PATCH 03/14] test: prove canonical Entity actor repository read isolation --- .../gameplay-rules-entities-and-effects.md | 6 + .../RetainedActorIdentityIntegrationTest.java | 181 ++++++++++++++++++ 2 files changed, 187 insertions(+) diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 5174c90b39..efb15005de 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -6,6 +6,12 @@ This is a non-normative implementation tracker for gameplay rules, entities, and ## Current Status +### Canonical actor repository read isolation + +One focused case in [RetainedActorIdentityIntegrationTest](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java) freshly passes against PostgreSQL with affected integration static and formatting checks. It calls the actual `ActorIdentityRepository` roster and exact-actor readers against populated tenant, account and namespace decoys, wrong scope and a quarantined actor. All five controlled actor rows share the same private numeric keys; canonical reads select only the exact UUID tuple and preserve the original row values and `xmin`. This restores focused reader coverage beyond the preceding raw-SQL tuple checks. Other cases retain their earlier execution attribution; the initial observer command-guard failure occurred before Gradle/test execution and receives no proof credit. + +These stored SQL identities prove bounded storage/read isolation, not genuine owner issuance, Account/tenant provenance, authenticated caller composition, canonical player admission or runtime quarantine activation. Existing passive owner and registration holds remain unchanged. + ### Selected gameplay-rule retention and receipt composition The prepared standalone Game Logic intake owner requires the exact Account HELD authorization and selected synchronized Game Design source before retaining an immutable terminal. The Game Design selected-intake command and receipt owners compose that retention with Account-owned terminal settlement and persist the exact receipt under existing GDS V1009. New Game Logic V1003 follows the empty owned V1 baseline and the shared Saga V1000–V1002 history; existing Account and GDS migration history stays unchanged. None of these owners or read adapters is registered, and the current legacy digest receiver and runtime rule consumption remain separate. diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java index df51b1a7b4..ec60f964b5 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java @@ -381,6 +381,187 @@ private List storedActorUuids( scope.name()); } + @Test + void canonicalOwnerRepositoryReadsExactScopedActorsAndExcludesQuarantine() { + // These stored identities are controlled SQL inputs, not owner issuance or player admission. + var shared = PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED; + var isolated = PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED; + UUID otherAccount = UUID.randomUUID(); + UUID otherTenant = UUID.randomUUID(); + UUID otherNamespace = UUID.randomUUID(); + UUID targetActor = UUID.randomUUID(); + UUID accountActor = UUID.randomUUID(); + UUID tenantActor = UUID.randomUUID(); + UUID namespaceActor = UUID.randomUUID(); + UUID quarantinedActor = UUID.randomUUID(); + insertNamespace(tenantUuid, namespaceUuid, shared); + insertNamespace(tenantUuid, otherNamespace, isolated); + insertNamespace(otherTenant, namespaceUuid, shared); + // Identical private numeric keys deliberately do not grant canonical tuple equivalence. + insertActor( + "reader-target", + targetActor, + accountUuid, + tenantUuid, + namespaceUuid, + shared, + "shared-live", + "OWNER_RESOLVED", + null, + accountId, + tenantId); + insertActor( + "reader-account", + accountActor, + otherAccount, + tenantUuid, + namespaceUuid, + shared, + "shared-live", + "OWNER_RESOLVED", + null, + accountId, + tenantId); + insertActor( + "reader-tenant", + tenantActor, + accountUuid, + otherTenant, + namespaceUuid, + shared, + "shared-live", + "OWNER_RESOLVED", + null, + accountId, + tenantId); + insertActor( + "reader-namespace", + namespaceActor, + accountUuid, + tenantUuid, + otherNamespace, + isolated, + "shared-live", + "OWNER_RESOLVED", + null, + accountId, + tenantId); + insertActor( + "reader-quarantine", + quarantinedActor, + accountUuid, + tenantUuid, + namespaceUuid, + shared, + "shared-live", + "QUARANTINED", + "TEST_ONLY_UNQUALIFIED", + accountId, + tenantId); + var originalRows = + jdbcTemplate.queryForList( + "SELECT to_jsonb(actor)::text || ':' || xmin::text FROM characters actor " + + "WHERE id IN (SELECT id FROM characters WHERE tenant_id = ? AND account_id = ?) " + + "ORDER BY character_uuid", + String.class, + tenantId, + accountId); + assertThat(originalRows).hasSize(5); + + assertThat( + actorIdentityRepository.findOwnerResolvedRoster( + tenantUuid.toString(), accountUuid.toString(), namespaceUuid.toString(), shared)) + .extracting(identity -> identity.characterUuid()) + .containsExactly(targetActor); + assertThat( + actorIdentityRepository.findOwnerResolvedRoster( + tenantUuid.toString(), otherAccount.toString(), namespaceUuid.toString(), shared)) + .extracting(identity -> identity.characterUuid()) + .containsExactly(accountActor); + assertThat( + actorIdentityRepository.findOwnerResolvedRoster( + otherTenant.toString(), accountUuid.toString(), namespaceUuid.toString(), shared)) + .extracting(identity -> identity.characterUuid()) + .containsExactly(tenantActor); + assertThat( + actorIdentityRepository.findOwnerResolvedRoster( + tenantUuid.toString(), accountUuid.toString(), otherNamespace.toString(), isolated)) + .extracting(identity -> identity.characterUuid()) + .containsExactly(namespaceActor); + assertThat( + actorIdentityRepository.findOwnerResolvedRoster( + tenantUuid.toString(), accountUuid.toString(), namespaceUuid.toString(), isolated)) + .isEmpty(); + assertThat( + actorIdentityRepository.findOwnerResolvedActor( + tenantUuid.toString(), + accountUuid.toString(), + namespaceUuid.toString(), + shared, + targetActor.toString())) + .get() + .satisfies( + identity -> { + assertThat(identity.characterUuid()).isEqualTo(targetActor); + assertThat(identity.accountUuid()).isEqualTo(accountUuid); + assertThat(identity.tenantUuid()).isEqualTo(tenantUuid); + assertThat(identity.playableStateNamespaceId()).isEqualTo(namespaceUuid); + assertThat(identity.playableStateScope()).isEqualTo(shared); + assertThat(identity.status().name()).isEqualTo("OWNER_RESOLVED"); + }); + for (UUID excluded : List.of(accountActor, tenantActor, namespaceActor, quarantinedActor)) { + assertThat( + actorIdentityRepository.findOwnerResolvedActor( + tenantUuid.toString(), + accountUuid.toString(), + namespaceUuid.toString(), + shared, + excluded.toString())) + .isEmpty(); + } + assertThat( + actorIdentityRepository.findOwnerResolvedActor( + tenantUuid.toString(), + otherAccount.toString(), + namespaceUuid.toString(), + shared, + targetActor.toString())) + .isEmpty(); + assertThat( + actorIdentityRepository.findOwnerResolvedActor( + otherTenant.toString(), + accountUuid.toString(), + namespaceUuid.toString(), + shared, + targetActor.toString())) + .isEmpty(); + assertThat( + actorIdentityRepository.findOwnerResolvedActor( + tenantUuid.toString(), + accountUuid.toString(), + otherNamespace.toString(), + isolated, + targetActor.toString())) + .isEmpty(); + assertThat( + actorIdentityRepository.findOwnerResolvedActor( + tenantUuid.toString(), + accountUuid.toString(), + namespaceUuid.toString(), + isolated, + targetActor.toString())) + .isEmpty(); + assertThat( + jdbcTemplate.queryForList( + "SELECT to_jsonb(actor)::text || ':' || xmin::text FROM characters actor " + + "WHERE id IN (SELECT id FROM characters WHERE tenant_id = ? AND account_id = ?) " + + "ORDER BY character_uuid", + String.class, + tenantId, + accountId)) + .isEqualTo(originalRows); + } + @Test void namespaceIdentityAndScopeAreImmutableWithoutActorReferences() { for (PlayableStateScope scope : From e3ae7694a4aee5ce961a73b7798e4916e38ff350 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 17 Oct 2026 21:07:52 +1300 Subject: [PATCH 04/14] docs(account): distinguish hosted gate foundations from authority --- .../adr-0180-account-owned-hosted-terms-acceptance-gate.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md b/design/architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md index 73871f1b5e..6af87ab1c1 100644 --- a/design/architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md +++ b/design/architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -This decision is target state only. FireMUD currently has no hosted-creator-party registry, immutable hosted-terms catalog, individual or organization acceptance API/storage, signer-authority evidence, creator acceptance UI, Game Design hosted-content gate, durable party/evidence binding, creator-party transfer workflow, route-matrix coverage/proof for the gate, material-change reacceptance invalidation, or focused tests for these behaviors. The [Hosted Content Terms](../../../HOSTED_CONTENT_TERMS.md) file remains a pre-launch policy baseline and is not an operative contract. Until the organization path is implemented and legally reviewed, official hosting may enable only individuals aged 18 years or older acting in their own capacity and must reject organization acceptance rather than infer it. +The complete hosted creator gate remains target state. Account has unregistered individual-party persistence, immutable hosted-terms catalog and individual acceptance storage, environment-binding primitives and focused test definitions. These foundations do not establish authenticated creator-party provisioning, operative legal publication, production identity or signer verification, a registered creator acceptance API/UI, organization acceptance, creator-party transfer, or a genuine commit-bound Game Design hosted-content gate. Current capability and proof limits belong to [Account API implementation status](../microservices/account-service/api-contracts.md#implementation-status) and the [authoring implementation tracker](../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status); storage and test-source presence alone are not physical or authority proof. The [Hosted Content Terms](../../../HOSTED_CONTENT_TERMS.md) file remains a pre-launch policy baseline and is not an operative contract. Until the organization path is implemented and legally reviewed, official hosting may enable only individuals aged 18 years or older acting in their own capacity and must reject organization acceptance rather than infer it. ## Decision Record From e8f5d3748ebff0ccee6c8aedef8322f39d23ee27 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 05:27:27 +1300 Subject: [PATCH 05/14] Preserve sanitized intake statuses and align prepared owner capability documentation --- .../account-service/api-contracts.md | 2 +- design/project-management/ai-observations.md | 6 +- .../gameplay-rules-entities-and-effects.md | 2 +- ...tedDraftGameLogicIntakeCommandService.java | 6 +- ...raftGameLogicIntakeCommandServiceTest.java | 46 ++++- ...ameLogicGameplayRuleIntakeGrpcService.java | 2 + ...playRuleIntakeTerminalReadGrpcService.java | 2 + ...ogicGameplayRuleIntakeGrpcServiceTest.java | 92 +++++++++- ...RuleIntakeTerminalReadGrpcServiceTest.java | 169 ++++++++++++++++++ 9 files changed, 309 insertions(+), 18 deletions(-) create mode 100644 services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcServiceTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 66e8c718c3..93d1772a31 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -76,7 +76,7 @@ Current explicit JOIN status: the local `/auth/bootstrap/join` controller and op Explicit playtest grants remain partial: current Account persistence and internal lookup can support a grant-backed admission read, but expiry bounded by fork lifecycle, tenant-admin create/extend/list/revoke, distinct audited platform break-glass, stable request-idempotent outcomes, retained revocation tombstones, and active-binding ejection are not implemented or end-to-end proved. The target owner contract is [Account-Owned Playtest Grant Contract](#account-owned-playtest-grant-contract); the links in authentication, session behavior, journeys, and trackers retain only their local consequences. -The hosted Creator Party, terms catalog, acceptance/currentness evidence, and changed-term lifecycle are target-only. No current Account route, proto/schema, storage, signer/transfer operation, creator UI, or focused proof implements them; Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. +Account has unregistered individual Creator Party, hosted-terms catalog, and individual acceptance storage in V84/V85 through `IndividualCreatorPartyRepository` and `HostedTermsRepository`, with focused repository test sources. These are storage foundations only: authenticated party provisioning and signer verification, operative legal publication, a registered acceptance API/UI, organization acceptance, party transfer, and a commit-bound currentness gate for Game Design writes remain unavailable or unproved. The canonical authority and capability limits are recorded in [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status); Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. `CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 777f9a31d4..3af472648c 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -103,7 +103,11 @@ Entry format: - Expected pattern: treat the setting as a qualified local choice, not a repository-wide memory guarantee or a change to hosted sizing. - Reconsideration trigger: fresh OOM/GC thrashing or a concrete need to measure cold-build memory. -- `2026-10-15`: Classes-only foreign-owner proof artifacts intentionally omit application and Flyway resources. A composed test that reads another owner’s migrations from disk must declare those directories as task inputs; otherwise a SQL-only change can leave the composition up-to-date. The selected Game Logic proof exposed this after its forward migration was reconciled, and Game Design now tracks the foreign Game Logic and World migration directories. +- `2026-10-15`: Declare foreign migration inputs for classes-only compositions + - Context: A composed proof can read another owner’s Flyway migrations from disk while its classes-only test artifacts omit application and Flyway resources. + - Observation: Without declaring those migration directories as task inputs, a SQL-only change can leave the composition up-to-date. + - Expected pattern: Declare every foreign migration directory read by a composed test as a task input so SQL changes invalidate that proof. + - Reconsideration trigger: The composition no longer reads foreign migration files from disk, or its execution model tracks those files through another verified dependency. - `2026-10-15`: Verify the complete absolute patch destination after the first write - Context: Gameplay’s World digest-guard helper verified its checkout but mistyped the absolute migration path, creating a file in a similarly named sibling directory outside Git. This is distinct from the earlier relative-path incident: an absolute path alone does not identify the intended checkout. diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index efb15005de..fc313ac00f 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -20,7 +20,7 @@ The corrected Game Logic full gate passes in 1m49s, freshly executing nine Postg ### Selected gameplay-rule intake prerequisite -The prepared typed Account intake boundary carries a complete selected gameplay-rule source binding and immutable authorization, recovery and terminal-settlement evidence. It preserves the current stricter gameplay-rule manifest validation, including numeric stat values. Its Account unit/static/format and five PostgreSQL cases pass, and the corrected Common socket/static/format gate passes; exact scopes and earlier failed large-wire fixtures are attributed in the Account prerequisite tracker. Controlled upstream evidence is not genuine Game Design authoring or Game Logic retention. The actual Game Logic storage/terminal owner and Game Design selected-source/receipt pipeline remain absent from this cut and must qualify before the launch-descriptor producer can consume an intake receipt. Selected-full Entity schema 3 and Automation schema 6 convergence remains a separate unfinished producer/consumer obligation; retained release attestations 1–3 keep their original meaning. See the [Account prerequisite tracker](./player-access-and-session.md#selected-gameplay-rule-intake-authorization-prerequisite) for owner and proof scope. +The prepared typed Account intake boundary carries a complete selected gameplay-rule source binding and immutable authorization, recovery and terminal-settlement evidence. It preserves the current stricter gameplay-rule manifest validation, including numeric stat values. Its Account unit/static/format and five PostgreSQL cases pass, and the corrected Common socket/static/format gate passes; exact scopes and earlier failed large-wire fixtures are attributed in the Account prerequisite tracker. Controlled upstream evidence is not genuine Game Design authoring or Game Logic retention. The prepared Game Logic retention owner and Game Design selected-source/receipt pipeline now have controlled standalone composition proof, as described in [Selected gameplay-rule retention and receipt composition](#selected-gameplay-rule-retention-and-receipt-composition); they remain unregistered and do not qualify the launch-descriptor consumer or genuine release authority. Selected-full Entity schema 3 and Automation schema 6 convergence remains a separate unfinished producer/consumer obligation; retained release attestations 1–3 keep their original meaning. See the [Account prerequisite tracker](./player-access-and-session.md#selected-gameplay-rule-intake-authorization-prerequisite) for owner and proof scope. The live implementation is strongest in item containment and transfer, durable effect replay for requests carrying a nonblank `effectId`, and the first evaluated actor-state/effect seams. Entity mutation requests with a blank `effectId` still execute directly without the replay ledger; this compatibility path is not safe gameplay-admission proof, and focused replay/readiness remains blocked until ingress rejects blank IDs or supplies a valid trusted ID. Entity Management also has crafting-oriented query structures and version-scoped recipe rows, but there is no complete player crafting/material-consumption flow yet. The broader authored-action, generic actor, targeting, resource-cost, and combat models remain incomplete. Cross-service proof is strongest on the bounded item, LOOK, movement, and nonblank-effect replay paths; broader gameplay orchestration is still represented more by service-level tests and slice-oriented fixtures than by full production integration. diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandService.java index c3e90c2837..46e89d5ed2 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandService.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamedesign.publication; +import io.grpc.Status; import java.util.Arrays; import java.util.Objects; import java.util.Optional; @@ -89,7 +90,10 @@ private SelectedDraftGameLogicReceipt produce( result = call.invoke(request, originalCreatorCredential); } catch (RuntimeException denied) { // The protected original credential must never be reflected by an injected client error. - throw new IllegalStateException("Account intake authorization denied or unavailable"); + throw new IllegalStateException( + "Account intake authorization denied or unavailable (" + + Status.fromThrowable(denied).getCode() + + ")"); } var authorization = requireFinalized(request, result); return receipts.retain(selection, authorization); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandServiceTest.java index 2ddf72cc8b..824ee7bbee 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandServiceTest.java @@ -10,6 +10,7 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import io.grpc.Status; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Optional; @@ -201,10 +202,19 @@ void rejectsAuthorizationWhoseSourceDoesNotMatchExactRequest() { } @Test - void sanitizesProducerFailuresWithoutReflectingProtectedCredential() { + void sanitizesProducerStatusCodesWithoutReflectingProtectedCredentialOrCause() { var value = SelectedDraftGameLogicReceiptTest.fixture(); var account = mock(GameLogicIntakeAuthorizationClient.class); - when(account.authorize(any(), anyString())).thenThrow(new IllegalStateException(CREDENTIAL)); + var failures = + new RuntimeException[] { + Status.UNAVAILABLE.withDescription(CREDENTIAL).asRuntimeException(), + Status.DEADLINE_EXCEEDED.withDescription(CREDENTIAL).asRuntimeException(), + Status.PERMISSION_DENIED.withDescription(CREDENTIAL).asRuntimeException(), + Status.FAILED_PRECONDITION.withDescription(CREDENTIAL).asRuntimeException(), + new RuntimeException(CREDENTIAL) + }; + when(account.authorize(any(), anyString())).thenThrow(failures); + when(account.recover(any(), anyString())).thenThrow(failures); var service = new SelectedDraftGameLogicIntakeCommandService( ignored -> Optional.of(value.selection()), @@ -212,13 +222,31 @@ void sanitizesProducerFailuresWithoutReflectingProtectedCredential() { (selected, authorization) -> value, "test"); - assertThatThrownBy( - () -> - service.authorizeAndRetain( - value.selection(), request(value.selection()), CREDENTIAL)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Account intake authorization denied or unavailable") - .hasMessageNotContaining(CREDENTIAL); + Status.Code[] expectedCodes = { + Status.Code.UNAVAILABLE, + Status.Code.DEADLINE_EXCEEDED, + Status.Code.PERMISSION_DENIED, + Status.Code.FAILED_PRECONDITION, + Status.Code.UNKNOWN + }; + for (boolean recover : new boolean[] {false, true}) { + for (Status.Code expectedCode : expectedCodes) { + assertThatThrownBy( + () -> { + var selection = value.selection(); + var request = request(selection); + if (recover) { + service.recoverAndRetain(selection, request, CREDENTIAL); + } else { + service.authorizeAndRetain(selection, request, CREDENTIAL); + } + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account intake authorization denied or unavailable (" + expectedCode + ")") + .hasMessageNotContaining(CREDENTIAL) + .hasNoCause(); + } + } } @Test diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcService.java index abea6e6c67..c7d46ad885 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcService.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcService.java @@ -57,6 +57,8 @@ public void retainGameplayRuleIntake( observer.onCompleted(); } catch (StatusRuntimeException failure) { observer.onError(failure); + } catch (IllegalArgumentException | IllegalStateException permanent) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); } catch (RuntimeException unavailable) { observer.onError(Status.UNAVAILABLE.asRuntimeException()); } diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcService.java index b572a1f0c6..426aa4dd68 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcService.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcService.java @@ -47,6 +47,8 @@ public void readGameplayRuleIntakeTerminal( observer.onCompleted(); } catch (StatusRuntimeException failure) { observer.onError(failure); + } catch (IllegalArgumentException | IllegalStateException permanent) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); } catch (RuntimeException unavailable) { observer.onError(Status.UNAVAILABLE.asRuntimeException()); } diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcServiceTest.java index 6a1474180c..cbaaf672b7 100644 --- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcServiceTest.java +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcServiceTest.java @@ -22,15 +22,19 @@ import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadEvidence; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeRetainEvidence; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeRetainProtoCodec; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.gamelogic.v1.RetainGameplayRuleIntakeRequest; import net.firedevops.firemud.gamelogic.v1.RetainGameplayRuleIntakeResponse; import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.transaction.CannotCreateTransactionException; import org.springframework.transaction.PlatformTransactionManager; class GameLogicGameplayRuleIntakeGrpcServiceTest { @@ -136,6 +140,85 @@ void authenticatedMalformedRequestIsRejectedBeforeAnyOwnerRead() { verify(fixture.gameDesignReader, never()).read(any()); } + @Test + void mapsPermanentOwnerFailuresToSanitizedFailedPrecondition() { + String secret = "private owner detail and credential"; + for (RuntimeException failure : + List.of(new IllegalArgumentException(secret), new IllegalStateException(secret))) { + var fixture = new Fixture(); + when(fixture.repository.findTerminal(any(UUID.class))).thenThrow(failure); + var request = GameLogicIntakeRetainEvidence.Request.create(NAMESPACE, fixture.authorization); + var observer = new RecordingObserver(); + + asGameDesign( + () -> + fixture.transport.retainGameplayRuleIntake( + GameLogicIntakeRetainProtoCodec.toRequest(request), observer)); + + assertSanitizedFailure(observer, Status.Code.FAILED_PRECONDITION, secret); + verify(fixture.accountReader, never()).read(any()); + verify(fixture.gameDesignReader, never()).read(any()); + } + } + + @Test + void keepsStorageAndTransactionCreationFailuresRetryableAndSanitized() { + String secret = "private storage detail and credential"; + var storageFixture = new Fixture(); + when(storageFixture.repository.findTerminal(any(UUID.class))) + .thenThrow(new DataAccessResourceFailureException(secret)); + var storageObserver = new RecordingObserver(); + var storageRequest = + GameLogicIntakeRetainEvidence.Request.create(NAMESPACE, storageFixture.authorization); + + asGameDesign( + () -> + storageFixture.transport.retainGameplayRuleIntake( + GameLogicIntakeRetainProtoCodec.toRequest(storageRequest), storageObserver)); + + assertSanitizedFailure(storageObserver, Status.Code.UNAVAILABLE, secret); + + var transactionFixture = new Fixture(); + when(transactionFixture.repository.findTerminal(any(UUID.class))).thenReturn(Optional.empty()); + when(transactionFixture.accountReader.read(any())) + .thenAnswer( + invocation -> { + var request = + invocation.getArgument(0, GameLogicIntakeAuthorizationReadEvidence.Request.class); + return new GameLogicIntakeAuthorizationReadEvidence(request); + }); + when(transactionFixture.gameDesignReader.read(any())) + .thenAnswer( + invocation -> { + var request = invocation.getArgument(0, GameplayRuleSourceReadEvidence.Request.class); + return new GameplayRuleSourceReadEvidence( + request, transactionFixture.authorization.source()); + }); + when(transactionFixture.transactions.getTransaction(any())) + .thenThrow(new CannotCreateTransactionException(secret)); + var transactionObserver = new RecordingObserver(); + var transactionRequest = + GameLogicIntakeRetainEvidence.Request.create(NAMESPACE, transactionFixture.authorization); + + asGameDesign( + () -> + transactionFixture.transport.retainGameplayRuleIntake( + GameLogicIntakeRetainProtoCodec.toRequest(transactionRequest), + transactionObserver)); + + assertSanitizedFailure(transactionObserver, Status.Code.UNAVAILABLE, secret); + } + + private static void assertSanitizedFailure( + RecordingObserver observer, Status.Code expectedCode, String secret) { + assertThat(observer.error).isEqualTo(expectedCode); + assertThat(observer.failure).isInstanceOf(StatusRuntimeException.class).hasNoCause(); + assertThat(observer.failure.toString()).doesNotContain(secret); + assertThat(Status.fromThrowable(observer.failure).getDescription()).isNull(); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + } + private static void assertCode(Status.Code error, Status.Code expected) { assertThat(error).isEqualTo(expected); } @@ -157,6 +240,7 @@ private static void withPeer(String uri, Runnable action) { private static final class RecordingObserver implements StreamObserver { private T value; private Status.Code error; + private Throwable failure; private boolean completed; @Override @@ -168,6 +252,7 @@ public void onNext(T next) { public void onError(Throwable failure) { assertThat(failure).isInstanceOf(StatusRuntimeException.class); error = Status.fromThrowable(failure).getCode(); + this.failure = failure; } @Override @@ -183,6 +268,7 @@ private static final class Fixture { mock(GameLogicIntakeAuthorizationReadClient.class); private final GameplayRuleSourceReadClient gameDesignReader = mock(GameplayRuleSourceReadClient.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); private final GameLogicIntakeAuthorizationBinding authorization = authorization(); private final GameLogicGameplayRuleIntakeTerminal terminal = GameLogicGameplayRuleIntakeTerminal.retained( @@ -191,11 +277,7 @@ private static final class Fixture { authorization.source().manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); private final GameLogicGameplayRuleIntakeService owner = new GameLogicGameplayRuleIntakeService( - repository, - mock(PlatformTransactionManager.class), - accountReader, - gameDesignReader, - NAMESPACE); + repository, transactions, accountReader, gameDesignReader, NAMESPACE); private final GameLogicGameplayRuleIntakeGrpcService transport = new GameLogicGameplayRuleIntakeGrpcService(owner, NAMESPACE); diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcServiceTest.java new file mode 100644 index 0000000000..29caa9c0e5 --- /dev/null +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcServiceTest.java @@ -0,0 +1,169 @@ +package net.firedevops.firemud.gamelogic.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeTerminalReadGrpcCodec; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamelogic.v1.ReadGameplayRuleIntakeTerminalResponse; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.transaction.CannotCreateTransactionException; + +class GameLogicGameplayRuleIntakeTerminalReadGrpcServiceTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + + @Test + void mapsPermanentOwnerFailuresToFailedPreconditionAndStorageFailuresToUnavailable() { + String secret = "private storage detail and credential"; + var cause = new IllegalStateException("underlying " + secret); + var failures = + List.of( + new IllegalArgumentException(secret, cause), + new IllegalStateException(secret, cause), + new DataAccessResourceFailureException(secret, cause), + new CannotCreateTransactionException(secret, cause)); + var expectedCodes = + List.of( + Status.Code.FAILED_PRECONDITION, + Status.Code.FAILED_PRECONDITION, + Status.Code.UNAVAILABLE, + Status.Code.UNAVAILABLE); + + for (int index = 0; index < failures.size(); index++) { + var repository = mock(GameLogicGameplayRuleIntakeRepository.class); + when(repository.findTerminal(any(UUID.class))).thenThrow(failures.get(index)); + var transport = + new GameLogicGameplayRuleIntakeTerminalReadGrpcService( + new GameLogicGameplayRuleIntakeTerminalReadService(repository, NAMESPACE), NAMESPACE); + var evidenceRequest = + GameLogicIntakeTerminalReadEvidence.Request.create(NAMESPACE, authorization()); + var observer = new RecordingObserver(); + + asAccount( + () -> + transport.readGameplayRuleIntakeTerminal( + GameLogicIntakeTerminalReadGrpcCodec.toRequest(evidenceRequest), observer)); + + assertThat(observer.error).isEqualTo(expectedCodes.get(index)); + assertThat(observer.failure).isInstanceOf(StatusRuntimeException.class).hasNoCause(); + assertThat(observer.failure.toString()).doesNotContain(secret); + assertThat(Status.fromThrowable(observer.failure).getDescription()).isNull(); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + } + } + + private static void asAccount(Runnable action) { + var peer = GrpcPeerIdentity.parseUri(ACCOUNT_URI).orElseThrow(); + Context previous = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).attach(); + try { + action.run(); + } finally { + Context.current().detach(previous); + } + } + + private static GameLogicIntakeAuthorizationBinding authorization() { + UUID actor = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "private", 2, "private", "NEW_GAME_ROW"); + var selectedBinding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var source = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selectedBinding.canonicalJson(), + "bindingDigest", + selectedBinding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))); + var accountSource = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + return new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + source, + List.of(accountSource)); + } + + private static final class RecordingObserver implements StreamObserver { + private T value; + private Status.Code error; + private Throwable failure; + private boolean completed; + + @Override + public void onNext(T next) { + value = next; + } + + @Override + public void onError(Throwable failure) { + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + this.failure = failure; + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} From 97fd206758ac1870a430a7446fef7ac1a01003cf Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 05:30:59 +1300 Subject: [PATCH 06/14] Document intentional exception capture in intake RPC tests --- .../GameLogicGameplayRuleIntakeGrpcServiceTest.java | 4 ++++ ...ameLogicGameplayRuleIntakeTerminalReadGrpcServiceTest.java | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcServiceTest.java index cbaaf672b7..d7e9ea7f9f 100644 --- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcServiceTest.java +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcServiceTest.java @@ -249,6 +249,10 @@ public void onNext(T next) { } @Override + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "The test intentionally retains the RPC failure to assert diagnostic and cause sanitization.") public void onError(Throwable failure) { assertThat(failure).isInstanceOf(StatusRuntimeException.class); error = Status.fromThrowable(failure).getCode(); diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcServiceTest.java index 29caa9c0e5..3e79b5d4c6 100644 --- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcServiceTest.java +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcServiceTest.java @@ -155,6 +155,10 @@ public void onNext(T next) { } @Override + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "The test intentionally retains the RPC failure to assert diagnostic and cause sanitization.") public void onError(Throwable failure) { assertThat(failure).isInstanceOf(StatusRuntimeException.class); this.failure = failure; From 9849ce308d4cfa78abedc0edae044fd57074ee19 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 05:33:51 +1300 Subject: [PATCH 07/14] Capture immutable RPC failure details in focused intake tests --- ...LogicGameplayRuleIntakeGrpcServiceTest.java | 18 +++++++++--------- ...yRuleIntakeTerminalReadGrpcServiceTest.java | 18 +++++++++--------- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcServiceTest.java index d7e9ea7f9f..b81e916712 100644 --- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcServiceTest.java +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcServiceTest.java @@ -212,9 +212,9 @@ void keepsStorageAndTransactionCreationFailuresRetryableAndSanitized() { private static void assertSanitizedFailure( RecordingObserver observer, Status.Code expectedCode, String secret) { assertThat(observer.error).isEqualTo(expectedCode); - assertThat(observer.failure).isInstanceOf(StatusRuntimeException.class).hasNoCause(); - assertThat(observer.failure.toString()).doesNotContain(secret); - assertThat(Status.fromThrowable(observer.failure).getDescription()).isNull(); + assertThat(observer.failureHasCause).isFalse(); + assertThat(observer.failureText).doesNotContain(secret); + assertThat(observer.failureDescription).isNull(); assertThat(observer.value).isNull(); assertThat(observer.completed).isFalse(); } @@ -240,7 +240,9 @@ private static void withPeer(String uri, Runnable action) { private static final class RecordingObserver implements StreamObserver { private T value; private Status.Code error; - private Throwable failure; + private String failureText; + private String failureDescription; + private boolean failureHasCause; private boolean completed; @Override @@ -249,14 +251,12 @@ public void onNext(T next) { } @Override - @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = - "The test intentionally retains the RPC failure to assert diagnostic and cause sanitization.") public void onError(Throwable failure) { assertThat(failure).isInstanceOf(StatusRuntimeException.class); error = Status.fromThrowable(failure).getCode(); - this.failure = failure; + failureText = failure.toString(); + failureDescription = Status.fromThrowable(failure).getDescription(); + failureHasCause = failure.getCause() != null; } @Override diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcServiceTest.java index 3e79b5d4c6..b825a3cde3 100644 --- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcServiceTest.java +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcServiceTest.java @@ -62,9 +62,9 @@ void mapsPermanentOwnerFailuresToFailedPreconditionAndStorageFailuresToUnavailab GameLogicIntakeTerminalReadGrpcCodec.toRequest(evidenceRequest), observer)); assertThat(observer.error).isEqualTo(expectedCodes.get(index)); - assertThat(observer.failure).isInstanceOf(StatusRuntimeException.class).hasNoCause(); - assertThat(observer.failure.toString()).doesNotContain(secret); - assertThat(Status.fromThrowable(observer.failure).getDescription()).isNull(); + assertThat(observer.failureHasCause).isFalse(); + assertThat(observer.failureText).doesNotContain(secret); + assertThat(observer.failureDescription).isNull(); assertThat(observer.value).isNull(); assertThat(observer.completed).isFalse(); } @@ -146,7 +146,9 @@ private static GameLogicIntakeAuthorizationBinding authorization() { private static final class RecordingObserver implements StreamObserver { private T value; private Status.Code error; - private Throwable failure; + private String failureText; + private String failureDescription; + private boolean failureHasCause; private boolean completed; @Override @@ -155,14 +157,12 @@ public void onNext(T next) { } @Override - @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = - "The test intentionally retains the RPC failure to assert diagnostic and cause sanitization.") public void onError(Throwable failure) { assertThat(failure).isInstanceOf(StatusRuntimeException.class); - this.failure = failure; error = Status.fromThrowable(failure).getCode(); + failureText = failure.toString(); + failureDescription = Status.fromThrowable(failure).getDescription(); + failureHasCause = failure.getCause() != null; } @Override From e4fd70a9f4790735f37006a3174750f93608b1d7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 06:27:01 +1300 Subject: [PATCH 08/14] fix: preserve retryable intake transport lifecycle and isolate namespace proof --- design/project-management/ai-observations.md | 1 + ...ameLogicIntakeAuthorizationReadClient.java | 14 ++++++- .../GameplayRuleSourceReadClient.java | 13 +++++- ...IntakeAuthorizationReadClientMtlsTest.java | 27 ++++++++++++ ...ameLogicIntakeSourceReadTransportTest.java | 42 +++++++++++++++++++ .../RetainedActorIdentityIntegrationTest.java | 8 ++-- 6 files changed, 97 insertions(+), 8 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 3af472648c..ab07388dda 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -169,6 +169,7 @@ Entry format: - `2026-10-18`: Retain admission context for independent review refusals - Context: a CLI request returned `review-threads:1:0` while peer Hosted findings were recorded as accepted and fix preparation was underway; no provider call occurred. - Observation: the short error does not establish why the documented peer-channel exception was not applied. Preserve the command result and any existing admission-audit pointer; no Controller defect or cause was established here. + - Expected pattern: retain the CLI result and admission-audit pointer for each independent review refusal, then inspect the recorded admission decision before assigning a cause. - Outcome: ordinary qualified publication and thread resolution cleared admission, and the next request reached the provider. Overseer confirmed that independent-channel guidance remains valid and requested no new investigation or Controller change from this error alone. - Reconsideration trigger: if this recurs, retain the existing admission context for adjudication rather than infer a cause from the short refusal. diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClient.java index ba3783904e..23e7e71005 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClient.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.common.gamelogic; import io.grpc.ManagedChannel; +import io.grpc.Status; import java.io.IOException; import java.util.Objects; import java.util.concurrent.TimeUnit; @@ -57,9 +58,18 @@ public GameLogicIntakeAuthorizationReadEvidence read( throw new IllegalArgumentException( "Account GL intake authorization read must use the configured workload namespace"); } + AccountGameLogicIntakeAuthorizationReadServiceGrpc + .AccountGameLogicIntakeAuthorizationReadServiceBlockingStub + initializedStub; + try { + initializedStub = + requireInitializedStub( + "Account GL intake authorization read client is not initialized and available"); + } catch (IllegalStateException unavailable) { + throw Status.UNAVAILABLE.asRuntimeException(); + } var response = - requireInitializedStub( - "Account GL intake authorization read client is not initialized and available") + initializedStub .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) .readHeldGameLogicIntakeAuthorization( GameLogicIntakeAuthorizationReadGrpcCodec.toRequest(request)); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadClient.java index ea246e3bf4..df328a49a6 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadClient.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.common.gamelogic; import io.grpc.ManagedChannel; +import io.grpc.Status; import java.io.IOException; import java.util.Objects; import java.util.concurrent.TimeUnit; @@ -54,9 +55,17 @@ public GameplayRuleSourceReadEvidence read(GameplayRuleSourceReadEvidence.Reques throw new IllegalArgumentException( "Game Design complete gameplay source read must use the configured workload namespace"); } + GameDesignGameplayRuleSourceReadServiceGrpc.GameDesignGameplayRuleSourceReadServiceBlockingStub + initializedStub; + try { + initializedStub = + requireInitializedStub( + "Game Design complete gameplay source read client is not initialized and available"); + } catch (IllegalStateException unavailable) { + throw Status.UNAVAILABLE.asRuntimeException(); + } var response = - requireInitializedStub( - "Game Design complete gameplay source read client is not initialized and available") + initializedStub .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) .readSelectedGameplayRuleSource(GameplayRuleSourceReadGrpcCodec.toRequest(request)); try { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java index e9682baa5f..3d81fba34c 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java @@ -30,6 +30,7 @@ import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -131,6 +132,20 @@ void pinsAccountServerAndRejectsOtherAuthenticatedCaller() throws Exception { assertThat(calls).hasValue(0); } + @Test + void reportsUnavailableBeforeInitializationAndAfterClose() throws Exception { + start(pki.server()); + client = newClient(gameLogicClient()); + var request = + GameLogicIntakeAuthorizationReadEvidence.Request.create(NAMESPACE, authorizationBinding()); + + assertUnavailable(() -> client.read(request)); + client.init(); + client.close(); + assertUnavailable(() -> client.read(request)); + assertThat(calls).hasValue(0); + } + private void start(IntakeTestPki.Identity identity) throws Exception { var service = new AccountGameLogicIntakeAuthorizationReadServiceGrpc @@ -291,4 +306,16 @@ private void close() throws Exception { server = null; } } + + private static void assertUnavailable(ThrowingCallable call) { + assertThatThrownBy(call) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> { + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + assertThat(Status.fromThrowable(failure).getDescription()).isNull(); + assertThat(failure.getCause()).isNull(); + }); + } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java index 8c974627e3..1ad00424c8 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java @@ -31,6 +31,7 @@ import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -46,6 +47,7 @@ class GameLogicIntakeSourceReadTransportTest { private static IntakeTestPki pki; private Server server; private GrpcGameLogicIntakeSourceReadClient client; + private GameplayRuleSourceReadClient sourceClient; private final AtomicInteger calls = new AtomicInteger(); private volatile boolean stall; private volatile boolean substitute; @@ -64,6 +66,10 @@ static void certificates() throws Exception { @AfterEach void close() throws Exception { + if (sourceClient != null) { + sourceClient.close(); + sourceClient = null; + } if (client != null) { client.close(); client = null; @@ -147,6 +153,30 @@ void pinsAccountServerAndAuthenticatedGdClientForBothMethods() throws Exception assertThat(calls).hasValue(2); } + @Test + void gameplayRuleSourceClientReportsUnavailableBeforeInitializationAndAfterClose() + throws Exception { + start(pki.server()); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + server.getPort()); + sourceClient = + new GameplayRuleSourceReadClient( + endpoints, + pki.clientProperties(tempDirectory, pki.client()), + new GrpcChannelFactory(), + NAMESPACE); + var authorization = + ((GameplayRuleSourceReadEvidence.Finalized) requests().getLast().proof()).authorization(); + var request = + GameplayRuleSourceReadEvidence.Request.forFinalizedIntake(NAMESPACE, authorization); + + assertUnavailable(() -> sourceClient.read(request)); + sourceClient.init(); + sourceClient.close(); + assertUnavailable(() -> sourceClient.read(request)); + assertThat(calls).hasValue(0); + } + @Test void rejectsNamespaceAmbientSqlMissingTlsAndSubstitutedResponse() throws Exception { var endpoints = new ServiceEndpointsProperties(); @@ -528,4 +558,16 @@ private static GameplayRuleSelectedSource selectedSource(DraftCommitBinding bind "revisionId", binding.revisions().getFirst().revisionId().toString()))))); } + + private static void assertUnavailable(ThrowingCallable call) { + assertThatThrownBy(call) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> { + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + assertThat(Status.fromThrowable(failure).getDescription()).isNull(); + assertThat(failure.getCause()).isNull(); + }); + } } diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java index ec60f964b5..6a211e4f2d 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java @@ -395,7 +395,7 @@ void canonicalOwnerRepositoryReadsExactScopedActorsAndExcludesQuarantine() { UUID namespaceActor = UUID.randomUUID(); UUID quarantinedActor = UUID.randomUUID(); insertNamespace(tenantUuid, namespaceUuid, shared); - insertNamespace(tenantUuid, otherNamespace, isolated); + insertNamespace(tenantUuid, otherNamespace, shared); insertNamespace(otherTenant, namespaceUuid, shared); // Identical private numeric keys deliberately do not grant canonical tuple equivalence. insertActor( @@ -440,7 +440,7 @@ void canonicalOwnerRepositoryReadsExactScopedActorsAndExcludesQuarantine() { accountUuid, tenantUuid, otherNamespace, - isolated, + shared, "shared-live", "OWNER_RESOLVED", null, @@ -485,7 +485,7 @@ void canonicalOwnerRepositoryReadsExactScopedActorsAndExcludesQuarantine() { .containsExactly(tenantActor); assertThat( actorIdentityRepository.findOwnerResolvedRoster( - tenantUuid.toString(), accountUuid.toString(), otherNamespace.toString(), isolated)) + tenantUuid.toString(), accountUuid.toString(), otherNamespace.toString(), shared)) .extracting(identity -> identity.characterUuid()) .containsExactly(namespaceActor); assertThat( @@ -540,7 +540,7 @@ void canonicalOwnerRepositoryReadsExactScopedActorsAndExcludesQuarantine() { tenantUuid.toString(), accountUuid.toString(), otherNamespace.toString(), - isolated, + shared, targetActor.toString())) .isEmpty(); assertThat( From 7a6685ac6a7cb5d44cad3a454bdeb03726d3518d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 06:50:25 +1300 Subject: [PATCH 09/14] Document selected receipt owner cardinality and align PostgreSQL fixture --- .../publication/SelectedDraftGameLogicReceiptRepository.java | 2 ++ .../SelectedDraftGameLogicReceiptPostgresIntegrationTest.java | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptRepository.java index 9aeaf52828..776ce973bc 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptRepository.java @@ -144,6 +144,8 @@ public SelectedDraftGameLogicReceipt retain(SelectedDraftGameLogicReceipt candid == null) { throw new IllegalStateException("Selected Version source proof unavailable"); } + // V50.2's primary key permits one immutable selection per canonical tenant/version, so + // fetchOne intentionally reflects that owner cardinality. dsl.fetchOne( "SELECT canonical_tenant_id FROM game_design_authored_draft_publish_selection WHERE canonical_tenant_id = ? AND canonical_version_id = ? FOR UPDATE", selection.target().canonicalTenantId(), diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java index cb8b8d8174..3e59adfca3 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java @@ -269,7 +269,7 @@ private static Fixture fixture(SelectedDraftGameLogicReceipt value) { POSTGRES.getPassword()); var dsl = DSL.using(new TransactionAwareDataSourceProxy(scoped), SQLDialect.POSTGRES); dsl.execute( - "CREATE TABLE game_design_authored_draft_publish_selection (canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, publish_request_id TEXT NOT NULL, selection_digest TEXT NOT NULL, selection_json TEXT NOT NULL, game_design_version_row_id BIGINT NOT NULL, game_design_version_tenant_key TEXT NOT NULL, source_game_row_id BIGINT NOT NULL, source_game_tenant_key TEXT NOT NULL, source_provenance_kind TEXT NOT NULL, version_state_epoch BIGINT NOT NULL, selected_commit_request_id UUID NOT NULL, selected_commit_id UUID NOT NULL, selected_commit_digest TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (canonical_tenant_id, canonical_version_id, publish_request_id))"); + "CREATE TABLE game_design_authored_draft_publish_selection (canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, publish_request_id TEXT NOT NULL, selection_digest TEXT NOT NULL, selection_json TEXT NOT NULL, game_design_version_row_id BIGINT NOT NULL, game_design_version_tenant_key TEXT NOT NULL, source_game_row_id BIGINT NOT NULL, source_game_tenant_key TEXT NOT NULL, source_provenance_kind TEXT NOT NULL, version_state_epoch BIGINT NOT NULL, selected_commit_request_id UUID NOT NULL, selected_commit_id UUID NOT NULL, selected_commit_digest TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (canonical_tenant_id, canonical_version_id), UNIQUE (canonical_tenant_id, canonical_version_id, publish_request_id))"); dsl.execute( "CREATE TABLE game (id BIGINT PRIMARY KEY, tenant_id TEXT, canonical_tenant_id UUID, tenant_identity_provenance_kind TEXT, tenant_identity_source_game_id BIGINT, tenant_identity_source_legacy_tenant_id TEXT)"); dsl.execute( From 5c51fea721870cd8b688b8ac2e3dccb0f720fff0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 07:33:04 +1300 Subject: [PATCH 10/14] Return retryable unavailable for intake client lifecycle failures --- .../GameLogicIntakeTerminalReadClient.java | 14 ++++++- ...ntGameLogicIntakeSettlementReadClient.java | 13 ++++++- ...rpcGameLogicIntakeAuthorizationClient.java | 9 ++++- .../GrpcGameLogicIntakeRetainClient.java | 12 +++++- .../GrpcGameLogicIntakeSourceReadClient.java | 15 ++++++-- ...GameLogicIntakeSettlementReadGrpcTest.java | 32 ++++++++++++++++ ...ameLogicIntakeSourceReadTransportTest.java | 14 +++++++ .../GameLogicIntakeTerminalReadGrpcTest.java | 32 ++++++++++++++++ ...ogicIntakeAuthorizationClientMtlsTest.java | 33 +++++++++++++++++ ...pcGameLogicIntakeRetainClientMtlsTest.java | 37 +++++++++++++++++++ 10 files changed, 201 insertions(+), 10 deletions(-) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadClient.java index b9c0cb9104..4b81754237 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadClient.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.common.gamelogic; import io.grpc.ManagedChannel; +import io.grpc.Status; import java.io.IOException; import java.util.Objects; import java.util.concurrent.TimeUnit; @@ -58,9 +59,18 @@ public GameLogicIntakeTerminalReadEvidence read( throw new IllegalArgumentException( "Game Logic intake terminal read must use the configured workload namespace"); } + GameLogicGameplayRuleIntakeTerminalReadServiceGrpc + .GameLogicGameplayRuleIntakeTerminalReadServiceBlockingStub + initializedStub; + try { + initializedStub = + requireInitializedStub( + "Game Logic intake terminal read client is not initialized and available"); + } catch (IllegalStateException unavailable) { + throw Status.UNAVAILABLE.asRuntimeException(); + } var response = - requireInitializedStub( - "Game Logic intake terminal read client is not initialized and available") + initializedStub .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) .readGameplayRuleIntakeTerminal( GameLogicIntakeTerminalReadGrpcCodec.toRequest(request)); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcAccountGameLogicIntakeSettlementReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcAccountGameLogicIntakeSettlementReadClient.java index f42df27c1a..9a65eaa0a2 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcAccountGameLogicIntakeSettlementReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcAccountGameLogicIntakeSettlementReadClient.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.common.gamelogic; import io.grpc.ManagedChannel; +import io.grpc.Status; import java.io.IOException; import java.util.Objects; import java.util.concurrent.TimeUnit; @@ -59,9 +60,17 @@ public AccountGameLogicIntakeSettlementReadEvidence read( throw new IllegalArgumentException( "Account intake settlement read must use the configured workload namespace"); } + AccountGameLogicIntakeSettlementServiceGrpc.AccountGameLogicIntakeSettlementServiceBlockingStub + initializedStub; + try { + initializedStub = + requireInitializedStub( + "Account intake settlement read client is not initialized and available"); + } catch (IllegalStateException unavailable) { + throw Status.UNAVAILABLE.asRuntimeException(); + } var response = - requireInitializedStub( - "Account intake settlement read client is not initialized and available") + initializedStub .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) .settleGameLogicIntake(AccountGameLogicIntakeSettlementProtoCodec.toRequest(request)); try { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClient.java index 697dd179a2..4a38105443 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClient.java @@ -75,7 +75,14 @@ private GameLogicIntakeAuthorizationEvidence.Result invoke( Objects.requireNonNull(request); if (!workloadNamespace.equals(request.targetNamespace())) throw new IllegalArgumentException("Account intake authorization namespace mismatch"); - var current = requireInitializedStub("Account intake authorization client unavailable"); + AccountGameLogicIntakeAuthorizationServiceGrpc + .AccountGameLogicIntakeAuthorizationServiceBlockingStub + current; + try { + current = requireInitializedStub("Account intake authorization client unavailable"); + } catch (IllegalStateException unavailable) { + throw Status.UNAVAILABLE.asRuntimeException(); + } var credentials = credentials(originalCreatorCredential, operation); var wireRequest = GameLogicIntakeAuthorizationGrpcCodec.toRequest(request); try { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClient.java index 3310988261..a91716b0fc 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClient.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.common.gamelogic; import io.grpc.ManagedChannel; +import io.grpc.Status; import java.io.IOException; import java.util.Objects; import java.util.concurrent.TimeUnit; @@ -53,8 +54,17 @@ public GameLogicIntakeRetainEvidence retain(GameLogicIntakeRetainEvidence.Reques throw new IllegalArgumentException( "Game Logic intake retain must use the configured workload namespace"); } + GameLogicGameplayRuleIntakeServiceGrpc.GameLogicGameplayRuleIntakeServiceBlockingStub + initializedStub; + try { + initializedStub = + requireInitializedStub( + "Game Logic intake retain client is not initialized and available"); + } catch (IllegalStateException unavailable) { + throw Status.UNAVAILABLE.asRuntimeException(); + } var response = - requireInitializedStub("Game Logic intake retain client is not initialized and available") + initializedStub .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) .retainGameplayRuleIntake(GameLogicIntakeRetainProtoCodec.toRequest(request)); try { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeSourceReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeSourceReadClient.java index f6982db838..c19e63ba3a 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeSourceReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeSourceReadClient.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.common.gamelogic; import io.grpc.ManagedChannel; +import io.grpc.Status; import java.io.IOException; import java.util.Objects; import java.util.concurrent.TimeUnit; @@ -57,10 +58,16 @@ public GameLogicIntakeSourceReadEvidence read(GameLogicIntakeSourceReadEvidence. throw new IllegalArgumentException( "Account GL intake source permission must use the configured workload namespace"); } - var stub = - requireInitializedStub( - "Account GL intake source permission client is not initialized and available") - .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS); + AccountGameLogicIntakeSourceReadServiceGrpc.AccountGameLogicIntakeSourceReadServiceBlockingStub + initializedStub; + try { + initializedStub = + requireInitializedStub( + "Account GL intake source permission client is not initialized and available"); + } catch (IllegalStateException unavailable) { + throw Status.UNAVAILABLE.asRuntimeException(); + } + var stub = initializedStub.withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS); var wire = GameLogicIntakeSourceReadProtoCodec.toRequest(request); var response = request.proof() instanceof GameplayRuleSourceReadEvidence.Preliminary diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java index 197bbb3f8a..a5396ed8d2 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java @@ -37,6 +37,7 @@ import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -298,6 +299,25 @@ void actualMtlsCarriesReceiptAboveFourMiBAndRejectsSubstitutedServerBeforeDispat assertThat(bodies).hasValue(0); } + @Test + void uninitializedAndClosedLifecycleFailuresAreSanitizedUnavailableWithoutRpc() throws Exception { + var evidence = evidence(NAMESPACE, 1, Outcome.RETAINED); + startServer(pki.server(), evidence); + client = newClient(server, pki.client()); + + assertSanitizedUnavailable(() -> client.read(evidence.request())); + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + + client.init(); + var closedClient = client; + client.close(); + client = null; + assertSanitizedUnavailable(() -> closedClient.read(evidence.request())); + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + } + private enum Outcome { RETAINED, ABORTED @@ -360,6 +380,18 @@ private GrpcAccountGameLogicIntakeSettlementReadClient newClient( endpoints, pki.clientProperties(tempDirectory, local), new GrpcChannelFactory(), NAMESPACE); } + private static void assertSanitizedUnavailable(ThrowingCallable operation) { + assertThatThrownBy(operation) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> { + var status = Status.fromThrowable(failure); + assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(status.getDescription()).isNull(); + assertThat(failure.getCause()).isNull(); + }); + } + /** These canonical bytes are deliberately synthetic transport evidence, not owner provenance. */ private static AccountGameLogicIntakeSettlementReadEvidence evidence( String namespace, int entryCount, Outcome outcome) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java index 1ad00424c8..fd9514170f 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java @@ -177,6 +177,20 @@ void gameplayRuleSourceClientReportsUnavailableBeforeInitializationAndAfterClose assertThat(calls).hasValue(0); } + @Test + void reportsSanitizedUnavailableBeforeInitializationAndAfterCloseForBothReadBranches() + throws Exception { + start(pki.server()); + client = newClient(pki.client()); + var requests = requests(); + + for (var request : requests) assertUnavailable(() -> client.read(request)); + client.init(); + client.close(); + for (var request : requests) assertUnavailable(() -> client.read(request)); + assertThat(calls).hasValue(0); + } + @Test void rejectsNamespaceAmbientSqlMissingTlsAndSubstitutedResponse() throws Exception { var endpoints = new ServiceEndpointsProperties(); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java index 20723c7e9e..9901ffc7ff 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java @@ -57,6 +57,7 @@ import net.firedevops.firemud.gamelogic.v1.GameLogicGameplayRuleIntakeTerminalReadServiceGrpc; import net.firedevops.firemud.gamelogic.v1.ReadGameplayRuleIntakeTerminalRequest; import net.firedevops.firemud.gamelogic.v1.ReadGameplayRuleIntakeTerminalResponse; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -327,6 +328,25 @@ void rejectsUnknownFieldsChangedOperationDigestAndTerminalPayload() { .isInstanceOf(IllegalArgumentException.class); } + @Test + void uninitializedAndClosedLifecycleFailuresAreSanitizedUnavailableWithoutRpc() throws Exception { + var evidence = evidence(NAMESPACE, 1, Outcome.RETAINED); + startServer(pki.server(), evidence); + client = newClient(server, pki.client()); + + assertSanitizedUnavailable(() -> client.read(evidence.request())); + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + + client.init(); + var closedClient = client; + client.close(); + client = null; + assertSanitizedUnavailable(() -> closedClient.read(evidence.request())); + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + } + @Test void loopbackStrictMtlsTransportsLargeCanonicalTerminalAndPinsBothPeerIdentities() throws Exception { @@ -422,6 +442,18 @@ private GameLogicIntakeTerminalReadClient newClient(Server target, IntakeTestPki endpoints, pki.clientProperties(tempDirectory, local), new GrpcChannelFactory(), NAMESPACE); } + private static void assertSanitizedUnavailable(ThrowingCallable operation) { + assertThatThrownBy(operation) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> { + var status = Status.fromThrowable(failure); + assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(status.getDescription()).isNull(); + assertThat(failure.getCause()).isNull(); + }); + } + /** These canonical bytes are deliberately synthetic transport evidence, not owner provenance. */ private static GameLogicIntakeTerminalReadEvidence evidence( String namespace, int entryCount, Outcome outcome) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java index 7fa474ef0e..894d6a57c7 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java @@ -111,6 +111,20 @@ void callsAuthorizeRecoverAndAbortWithExactPeerAndProtectedCredential() throws E assertThat(observedMethods).containsExactly("AuthorizeIntake", "RecoverIntake", "AbortIntake"); } + @Test + void reportsSanitizedUnavailableBeforeInitializationAndAfterCloseForEveryOperation() + throws Exception { + start(pki.server()); + client = newClient(pki.client()); + var request = request(selected(1)); + + assertOperationsUnavailable(request); + client.init(); + client.close(); + assertOperationsUnavailable(request); + assertThat(calls).hasValue(0); + } + @Test void pinsAccountServerAndRejectsWrongServerAndWrongAuthenticatedCaller() throws Exception { start(pki.wrongServer()); @@ -357,6 +371,25 @@ private GrpcGameLogicIntakeAuthorizationClient newClient(IntakeTestPki.Identity NAMESPACE); } + private void assertOperationsUnavailable(GameLogicIntakeAuthorizationEvidence.Request request) { + assertUnavailable(() -> client.authorize(request, CREDENTIAL)); + assertUnavailable(() -> client.recover(request, CREDENTIAL)); + assertUnavailable(() -> client.abort(request, CREDENTIAL)); + } + + private static void assertUnavailable( + org.assertj.core.api.ThrowableAssert.ThrowingCallable call) { + assertThatThrownBy(call) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> { + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + assertThat(Status.fromThrowable(failure).getDescription()).isNull(); + assertThat(failure.getCause()).isNull(); + }); + } + private static GameLogicIntakeAuthorizationEvidence.Request request(DraftCommitBinding selected) { return GameLogicIntakeAuthorizationEvidence.Request.create( NAMESPACE, UUID.randomUUID(), selected); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClientMtlsTest.java index 2829ab80aa..840b5fa553 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClientMtlsTest.java @@ -25,6 +25,7 @@ import net.firedevops.firemud.gamelogic.v1.GameLogicGameplayRuleIntakeServiceGrpc; import net.firedevops.firemud.gamelogic.v1.RetainGameplayRuleIntakeRequest; import net.firedevops.firemud.gamelogic.v1.RetainGameplayRuleIntakeResponse; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -105,6 +106,30 @@ void acceptsLargeTerminalFromExactGameLogicServerAndRejectsSubstitutedServer() t assertThat(clientPeer.get()).isNull(); } + @Test + void uninitializedAndClosedLifecycleFailuresAreSanitizedUnavailableWithoutRpc() throws Exception { + var authorization = GameLogicIntakeRetainProtoCodecTest.largeAuthorization(1); + var request = GameLogicIntakeRetainEvidence.Request.create(NAMESPACE, authorization); + var source = authorization.source(); + var terminal = + GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation(NAMESPACE, authorization), + source.canonicalBytes(), + source.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + startServer(pki.server(), request, terminal); + client = newClient(server.getPort()); + + assertSanitizedUnavailable(() -> client.retain(request)); + assertThat(calls).hasValue(0); + + client.init(); + var closedClient = client; + client.close(); + client = null; + assertSanitizedUnavailable(() -> closedClient.retain(request)); + assertThat(calls).hasValue(0); + } + private void startServer( IntakeTestPki.Identity identity, GameLogicIntakeRetainEvidence.Request expectedRequest, @@ -152,4 +177,16 @@ private GrpcGameLogicIntakeRetainClient newClient(int port) throws Exception { new GrpcChannelFactory(), NAMESPACE); } + + private static void assertSanitizedUnavailable(ThrowingCallable operation) { + assertThatThrownBy(operation) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> { + var status = Status.fromThrowable(failure); + assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(status.getDescription()).isNull(); + assertThat(failure.getCause()).isNull(); + }); + } } From 778bb21731d007acc5392b4e15ddb6eff2fe20ad Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 07:35:21 +1300 Subject: [PATCH 11/14] Align existing settlement lifecycle assertion with retryable status --- .../AccountGameLogicIntakeSettlementReadGrpcTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java index a5396ed8d2..998d13be94 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java @@ -244,8 +244,7 @@ endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) new GrpcChannelFactory(), NAMESPACE); var evidence = evidence("test", 1, Outcome.ABORTED); - assertThatThrownBy(() -> client.read(evidence.request())) - .isInstanceOf(IllegalStateException.class); + assertSanitizedUnavailable(() -> client.read(evidence.request())); assertThatThrownBy( () -> client.read( From 555379d8c0965897e8e4877f3326ebc5efbdd73d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 08:16:55 +1300 Subject: [PATCH 12/14] Share selected Game Logic receipt provenance readers --- ...tedDraftGameLogicIntakeCommandService.java | 9 +- ...lectedDraftGameLogicReceiptRepository.java | 119 ++++++++++-------- .../SelectedDraftGameLogicReceiptService.java | 11 +- 3 files changed, 68 insertions(+), 71 deletions(-) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandService.java index 46e89d5ed2..96ed587ffe 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandService.java @@ -9,8 +9,6 @@ import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; -import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; -import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; import org.jooq.DSLContext; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -149,12 +147,7 @@ private static boolean sameRequest( private static SelectionReader repositoryReader(DSLContext dsl) { Objects.requireNonNull(dsl, "dsl"); return selection -> - new AuthoredDraftPublishSelectionRepository(dsl, new DraftCommitCoordinatorRepository(dsl)) - .read( - selection.intent().canonicalTenantId(), - selection.intent().canonicalVersionId(), - selection.intent().publishRequestId()) - .map(AuthoredDraftPublishSelectionRepository.SelectionSnapshot::selection); + SelectedDraftGameLogicReceiptRepository.readRetainedSelection(dsl, selection); } private static void requireNoTransaction() { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptRepository.java index 776ce973bc..34f469316f 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptRepository.java @@ -20,6 +20,22 @@ /** Unregistered immutable derived-receipt storage, separate from publication-operation bytes. */ public class SelectedDraftGameLogicReceiptRepository { + private static final String VERSION_SOURCE_PROOF_QUERY = + "SELECT v.id FROM version v JOIN game g " + + "ON g.id = v.identity_source_game_row_id " + + "AND g.tenant_id = v.identity_source_game_tenant_key " + + "AND g.canonical_tenant_id = v.canonical_tenant_id " + + "AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind " + + "AND g.tenant_identity_source_game_id = g.id " + + "AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id " + + "WHERE v.id = ? AND v.tenant_id = ? AND v.canonical_tenant_id = ? " + + "AND v.canonical_version_id = ? AND v.identity_source_game_row_id = ? " + + "AND v.identity_source_game_tenant_key = ? AND v.identity_source_provenance_kind = ? " + + "AND v.identity_source_game_row_id > 0 " + + "AND v.identity_source_game_tenant_key = v.tenant_id " + + "AND v.identity_source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') " + + "AND v.version_state_epoch > 0"; + private final DSLContext dsl; @SuppressFBWarnings( @@ -86,29 +102,13 @@ public Optional readForPublication( // Version row, selected commit and source correlation without creating read authority. new GameLogicPublicationSourceReadBinding(publicationRequest, retained.authorization()); - if (dsl.fetchOne( - "SELECT v.id FROM version v JOIN game g " - + "ON g.id = v.identity_source_game_row_id " - + "AND g.tenant_id = v.identity_source_game_tenant_key " - + "AND g.canonical_tenant_id = v.canonical_tenant_id " - + "AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind " - + "AND g.tenant_identity_source_game_id = g.id " - + "AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id " - + "WHERE v.id = ? AND v.tenant_id = ? AND v.canonical_tenant_id = ? " - + "AND v.canonical_version_id = ? AND v.identity_source_game_row_id = ? " - + "AND v.identity_source_game_tenant_key = ? AND v.identity_source_provenance_kind = ? " - + "AND v.identity_source_game_row_id > 0 " - + "AND v.identity_source_game_tenant_key = v.tenant_id " - + "AND v.identity_source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') " - + "AND v.version_state_epoch > 0", - Long.parseLong(publicationRequest.versionId()), - target.gameDesignVersionTenantKey(), - canonicalTenantId, - selection.intent().canonicalVersionId(), - target.sourceGameRowId(), - target.sourceGameTenantKey(), - target.sourceProvenanceKind()) - == null) { + if (!hasVersionSourceProof( + selection, + Long.parseLong(publicationRequest.versionId()), + target.gameDesignVersionTenantKey(), + canonicalTenantId, + selection.intent().canonicalVersionId(), + false)) { throw new IllegalStateException("Selected Game Design Version row proof unavailable"); } return Optional.of(retained); @@ -119,29 +119,13 @@ public SelectedDraftGameLogicReceipt retain(SelectedDraftGameLogicReceipt candid var selection = candidate.selection(); // Keep the existing owner lock order: Version before immutable selection. var target = selection.target(); - if (dsl.fetchOne( - "SELECT v.id FROM version v JOIN game g " - + "ON g.id = v.identity_source_game_row_id " - + "AND g.tenant_id = v.identity_source_game_tenant_key " - + "AND g.canonical_tenant_id = v.canonical_tenant_id " - + "AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind " - + "AND g.tenant_identity_source_game_id = g.id " - + "AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id " - + "WHERE v.id = ? AND v.tenant_id = ? AND v.canonical_tenant_id = ? " - + "AND v.canonical_version_id = ? AND v.identity_source_game_row_id = ? " - + "AND v.identity_source_game_tenant_key = ? AND v.identity_source_provenance_kind = ? " - + "AND v.identity_source_game_row_id > 0 " - + "AND v.identity_source_game_tenant_key = v.tenant_id " - + "AND v.identity_source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') " - + "AND v.version_state_epoch > 0 FOR UPDATE OF v", - target.gameDesignVersionRowId(), - target.gameDesignVersionTenantKey(), - target.canonicalTenantId(), - target.canonicalVersionId(), - target.sourceGameRowId(), - target.sourceGameTenantKey(), - target.sourceProvenanceKind()) - == null) { + if (!hasVersionSourceProof( + selection, + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.canonicalTenantId(), + target.canonicalVersionId(), + true)) { throw new IllegalStateException("Selected Version source proof unavailable"); } // V50.2's primary key permits one immutable selection per canonical tenant/version, so @@ -151,14 +135,9 @@ public SelectedDraftGameLogicReceipt retain(SelectedDraftGameLogicReceipt candid selection.target().canonicalTenantId(), selection.target().canonicalVersionId()); var retainedSelection = - new AuthoredDraftPublishSelectionRepository(dsl, new DraftCommitCoordinatorRepository(dsl)) - .read( - selection.intent().canonicalTenantId(), - selection.intent().canonicalVersionId(), - selection.intent().publishRequestId()) + readRetainedSelection(dsl, selection) .orElseThrow( - () -> new IllegalStateException("SELECTED_PUBLICATION_SELECTION_UNAVAILABLE")) - .selection(); + () -> new IllegalStateException("SELECTED_PUBLICATION_SELECTION_UNAVAILABLE")); if (!Arrays.equals(selection.canonicalBytes(), retainedSelection.canonicalBytes())) { throw new IllegalStateException("Selected publication changed before receipt retention"); } @@ -187,6 +166,40 @@ private static SelectedDraftGameLogicReceipt requireSameReceipt( return retained; } + static Optional readRetainedSelection( + DSLContext dsl, AuthoredDraftPublishSelection selection) { + Objects.requireNonNull(dsl, "dsl"); + Objects.requireNonNull(selection, "selection"); + return new AuthoredDraftPublishSelectionRepository( + dsl, new DraftCommitCoordinatorRepository(dsl)) + .read( + selection.intent().canonicalTenantId(), + selection.intent().canonicalVersionId(), + selection.intent().publishRequestId()) + .map(AuthoredDraftPublishSelectionRepository.SelectionSnapshot::selection); + } + + private boolean hasVersionSourceProof( + AuthoredDraftPublishSelection selection, + long versionRowId, + long versionTenantKey, + UUID canonicalTenantId, + UUID canonicalVersionId, + boolean lockVersion) { + var target = selection.target(); + String query = VERSION_SOURCE_PROOF_QUERY + (lockVersion ? " FOR UPDATE OF v" : ""); + return dsl.fetchOne( + query, + versionRowId, + versionTenantKey, + canonicalTenantId, + canonicalVersionId, + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind()) + != null; + } + private static SelectedDraftGameLogicReceipt decode(Record row) { byte[] selectionBytes = row.get("selection_bytes", byte[].class); var selection = diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptService.java index d5a93c4a87..bc71298056 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptService.java @@ -10,8 +10,6 @@ import net.firedevops.firemud.common.gamelogic.GameLogicIntakeRetainEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; -import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; -import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; import org.jooq.DSLContext; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; @@ -38,14 +36,7 @@ public SelectedDraftGameLogicReceiptService( String namespace) { this( new SelectedDraftGameLogicReceiptRepository(dsl), - selection -> - new AuthoredDraftPublishSelectionRepository( - dsl, new DraftCommitCoordinatorRepository(dsl)) - .read( - selection.intent().canonicalTenantId(), - selection.intent().canonicalVersionId(), - selection.intent().publishRequestId()) - .map(AuthoredDraftPublishSelectionRepository.SelectionSnapshot::selection), + selection -> SelectedDraftGameLogicReceiptRepository.readRetainedSelection(dsl, selection), transactions, gameLogic, account, From e99af6200cc19ad7bd38162ca93d1d46eeeaf4d9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 08:19:59 +1300 Subject: [PATCH 13/14] Preserve selected receipt tenant SQL binding type --- .../publication/SelectedDraftGameLogicReceiptRepository.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptRepository.java index 34f469316f..1f71d35a90 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptRepository.java @@ -182,7 +182,7 @@ dsl, new DraftCommitCoordinatorRepository(dsl)) private boolean hasVersionSourceProof( AuthoredDraftPublishSelection selection, long versionRowId, - long versionTenantKey, + String versionTenantKey, UUID canonicalTenantId, UUID canonicalVersionId, boolean lockVersion) { From 65709c0d0d4c5dac842cf803da0c8d8d42e62932 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 08:56:36 +1300 Subject: [PATCH 14/14] Classify and sanitize selected-intake dependency failures --- ...meDesignGameplayRuleSourceReadService.java | 21 +++- ...signGameplayRuleSourceReadServiceTest.java | 97 +++++++++++++++++++ .../GameLogicGameplayRuleIntakeService.java | 25 ++++- ...ameLogicGameplayRuleIntakeServiceTest.java | 89 ++++++++++++++++- 4 files changed, 227 insertions(+), 5 deletions(-) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadService.java index 26b43d858c..bde5647a7e 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadService.java @@ -1,7 +1,9 @@ package net.firedevops.firemud.gamedesign.publication; import io.grpc.Status; +import io.grpc.StatusRuntimeException; import java.util.Objects; +import java.util.function.Supplier; import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; @@ -53,7 +55,7 @@ public GameplayRuleSourceReadEvidence read(GameplayRuleSourceReadEvidence.Reques var permissionRequest = net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadEvidence.Request.create( namespace, reader, request.purpose(), request.proof()); - var permission = permissions.read(permissionRequest); + var permission = readDependency(() -> permissions.read(permissionRequest)); if (permission == null || !permissionRequest.equals(permission.request())) throw Status.FAILED_PRECONDITION .withDescription("Exact Account source permission required") @@ -86,4 +88,21 @@ static void requirePeer(String namespace) { && !(prefix + "game-logic-service").equals(peer.uri())) throw Status.PERMISSION_DENIED.asRuntimeException(); } + + private static T readDependency(Supplier read) { + try { + return read.get(); + } catch (StatusRuntimeException failure) { + throw sanitize(failure); + } + } + + private static StatusRuntimeException sanitize(StatusRuntimeException failure) { + var code = Status.fromThrowable(failure).getCode(); + return switch (code) { + case UNAVAILABLE, DEADLINE_EXCEEDED, CANCELLED, RESOURCE_EXHAUSTED, INTERNAL, UNKNOWN -> + Status.fromCode(code).asRuntimeException(); + default -> Status.UNAVAILABLE.asRuntimeException(); + }; + } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadServiceTest.java index 5ec5b3b4e6..eec9ef0f00 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadServiceTest.java @@ -8,19 +8,50 @@ import static org.mockito.Mockito.when; import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; import java.util.List; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Stream; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionStatus; class GameDesignGameplayRuleSourceReadServiceTest { + @ParameterizedTest + @MethodSource("permissionFailures") + void sanitizesForeignPermissionStatuses(Status.Code foreignCode, Status.Code expectedCode) { + var repository = mock(GameplayRuleSourceRepository.class); + var transactions = mock(PlatformTransactionManager.class); + var permissions = + mock(net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadClient.class); + org.mockito.Mockito.doThrow(foreignFailure(foreignCode)).when(permissions).read(any()); + var owner = + new GameDesignGameplayRuleSourceReadService(repository, transactions, permissions, "test"); + + assertThatThrownBy(() -> asAccount(() -> owner.read(accountScopeRequest()))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> { + var status = Status.fromThrowable(error); + assertThat(status.getCode()).isEqualTo(expectedCode); + assertThat(status.getDescription()).isNull(); + assertThat(error.getCause()).isNull(); + assertThat(((StatusRuntimeException) error).getTrailers()).isNull(); + }); + org.mockito.Mockito.verifyNoInteractions(transactions, repository); + } + @Test void exportsOnlyTheCompleteOwnerReadForTheExactSynchronizedBinding() { var repository = mock(GameplayRuleSourceRepository.class); @@ -184,6 +215,72 @@ private static void asAccount(Runnable action) { .run(action); } + private static GameplayRuleSourceReadEvidence.Request accountScopeRequest() { + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "private", 2, "private", "NEW_GAME_ROW"); + var selected = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload( + new GameplayRuleManifest.AdmissionTag("gameplay")))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.SCOPE, + target.canonicalVersionId().toString(), + GameplayRuleSource.SCOPE, + GameplayRuleSource.SCOPE_ID, + "0"))); + return GameplayRuleSourceReadEvidence.Request.forAccountSourceScope( + "test", + new net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadScope( + "test", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + selected, + "spiffe://firemud/ns/test/sa/account-service", + "GAME_LOGIC_INTAKE_SOURCE")); + } + + private static Stream permissionFailures() { + return Stream.of( + Arguments.of(Status.Code.UNAUTHENTICATED, Status.Code.UNAVAILABLE), + Arguments.of(Status.Code.PERMISSION_DENIED, Status.Code.UNAVAILABLE), + Arguments.of(Status.Code.FAILED_PRECONDITION, Status.Code.UNAVAILABLE), + Arguments.of(Status.Code.ABORTED, Status.Code.UNAVAILABLE), + Arguments.of(Status.Code.NOT_FOUND, Status.Code.UNAVAILABLE), + Arguments.of(Status.Code.ALREADY_EXISTS, Status.Code.UNAVAILABLE), + Arguments.of(Status.Code.INVALID_ARGUMENT, Status.Code.UNAVAILABLE), + Arguments.of(Status.Code.OUT_OF_RANGE, Status.Code.UNAVAILABLE), + Arguments.of(Status.Code.UNAVAILABLE, Status.Code.UNAVAILABLE), + Arguments.of(Status.Code.DEADLINE_EXCEEDED, Status.Code.DEADLINE_EXCEEDED), + Arguments.of(Status.Code.CANCELLED, Status.Code.CANCELLED), + Arguments.of(Status.Code.RESOURCE_EXHAUSTED, Status.Code.RESOURCE_EXHAUSTED), + Arguments.of(Status.Code.INTERNAL, Status.Code.INTERNAL), + Arguments.of(Status.Code.DATA_LOSS, Status.Code.UNAVAILABLE), + Arguments.of(Status.Code.UNKNOWN, Status.Code.UNKNOWN)); + } + + private static StatusRuntimeException foreignFailure(Status.Code code) { + var trailers = new Metadata(); + trailers.put(Metadata.Key.of("foreign-detail", Metadata.ASCII_STRING_MARSHALLER), "secret"); + return Status.fromCode(code) + .withDescription("foreign description") + .withCause(new IllegalStateException("foreign cause")) + .asRuntimeException(trailers); + } + private static void asGameLogic(Runnable action) { Context.current() .withValue( diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java index c140b65876..457478aa5c 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java @@ -1,10 +1,12 @@ package net.firedevops.firemud.gamelogic.sourceintake; import io.grpc.Status; +import io.grpc.StatusRuntimeException; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Objects; import java.util.Optional; +import java.util.function.Supplier; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials; import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials; import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; @@ -64,7 +66,7 @@ public GameLogicGameplayRuleIntakeTerminal retain( var authorizationRequest = GameLogicIntakeAuthorizationReadEvidence.Request.create(workloadNamespace, authorization); - var held = accountAuthorizationReader.read(authorizationRequest); + var held = readDependency(() -> accountAuthorizationReader.read(authorizationRequest)); if (held == null || !authorizationRequest.equals(held.request())) { throw Status.FAILED_PRECONDITION .withDescription("Exact HELD Account intake authorization required") @@ -73,7 +75,7 @@ public GameLogicGameplayRuleIntakeTerminal retain( var sourceRequest = GameplayRuleSourceReadEvidence.Request.forFinalizedIntake(workloadNamespace, authorization); - var sourceEvidence = gameDesignSourceReader.read(sourceRequest); + var sourceEvidence = readDependency(() -> gameDesignSourceReader.read(sourceRequest)); if (sourceEvidence == null || !sourceRequest.equals(sourceEvidence.request()) || !Arrays.equals( @@ -126,7 +128,7 @@ public GameLogicGameplayRuleIntakeTerminal abort( var authorizationRequest = GameLogicIntakeAuthorizationReadEvidence.Request.create(workloadNamespace, authorization); - var held = accountAuthorizationReader.read(authorizationRequest); + var held = readDependency(() -> accountAuthorizationReader.read(authorizationRequest)); if (held == null || !authorizationRequest.equals(held.request())) { throw Status.FAILED_PRECONDITION .withDescription("Exact HELD Account intake authorization required for explicit abort") @@ -197,4 +199,21 @@ private static void requireNoActiveTransaction() { .asRuntimeException(); } } + + private static T readDependency(Supplier read) { + try { + return read.get(); + } catch (StatusRuntimeException failure) { + throw sanitize(failure); + } + } + + private static StatusRuntimeException sanitize(StatusRuntimeException failure) { + var code = Status.fromThrowable(failure).getCode(); + return switch (code) { + case UNAVAILABLE, DEADLINE_EXCEEDED, CANCELLED, RESOURCE_EXHAUSTED, INTERNAL, UNKNOWN -> + Status.fromCode(code).asRuntimeException(); + default -> Status.UNAVAILABLE.asRuntimeException(); + }; + } } diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java index 6bec90c034..4a948abe56 100644 --- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java @@ -10,6 +10,7 @@ import static org.mockito.Mockito.when; import io.grpc.Context; +import io.grpc.Metadata; import io.grpc.Status; import io.grpc.StatusRuntimeException; import java.nio.charset.StandardCharsets; @@ -18,6 +19,7 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Stream; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; @@ -33,6 +35,9 @@ import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; @@ -127,7 +132,7 @@ void explicitAbortRequiresAnExactHeldAccountReadAndDoesNotWriteOnAbsence() { .satisfies( error -> assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .isEqualTo(Status.Code.UNAVAILABLE)); assertThat(fixture.stored.get()).isNull(); verify(fixture.repository, never()) .insertTerminal(any(GameLogicGameplayRuleIntakeTerminal.class)); @@ -212,6 +217,88 @@ void unavailableAccountReadLeavesNoTerminalAndDoesNotInferAbort() { .insertTerminal(any(GameLogicGameplayRuleIntakeTerminal.class)); } + @ParameterizedTest + @MethodSource("dependencyFailures") + void sanitizesOnlyForeignDependencyStatuses( + DependencyCall call, Status.Code foreignCode, Status.Code expectedCode) { + var fixture = new Fixture(); + var authorization = authorization(); + var failure = foreignFailure(foreignCode); + if (call == DependencyCall.RETAIN_ACCOUNT || call == DependencyCall.ABORT_ACCOUNT) { + when(fixture.accountReader.read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class))) + .thenThrow(failure); + } else { + fixture.respondAuthorizationOnly(authorization); + when(fixture.gameDesignReader.read(any(GameplayRuleSourceReadEvidence.Request.class))) + .thenThrow(failure); + } + + assertThatThrownBy( + () -> + asGameDesign( + () -> { + if (call == DependencyCall.ABORT_ACCOUNT) + fixture.service.abort(authorization); + else fixture.service.retain(authorization); + return null; + })) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> { + var status = Status.fromThrowable(error); + assertThat(status.getCode()).isEqualTo(expectedCode); + assertThat(status.getDescription()).isNull(); + assertThat(error.getCause()).isNull(); + assertThat(((StatusRuntimeException) error).getTrailers()).isNull(); + }); + verify(fixture.repository, never()) + .insertTerminal(any(GameLogicGameplayRuleIntakeTerminal.class)); + } + + private static Stream dependencyFailures() { + var calls = + List.of( + DependencyCall.RETAIN_ACCOUNT, + DependencyCall.RETAIN_SOURCE, + DependencyCall.ABORT_ACCOUNT); + var cases = + List.of( + Arguments.of(Status.Code.UNAUTHENTICATED, Status.Code.UNAVAILABLE), + Arguments.of(Status.Code.PERMISSION_DENIED, Status.Code.UNAVAILABLE), + Arguments.of(Status.Code.FAILED_PRECONDITION, Status.Code.UNAVAILABLE), + Arguments.of(Status.Code.ABORTED, Status.Code.UNAVAILABLE), + Arguments.of(Status.Code.NOT_FOUND, Status.Code.UNAVAILABLE), + Arguments.of(Status.Code.ALREADY_EXISTS, Status.Code.UNAVAILABLE), + Arguments.of(Status.Code.INVALID_ARGUMENT, Status.Code.UNAVAILABLE), + Arguments.of(Status.Code.OUT_OF_RANGE, Status.Code.UNAVAILABLE), + Arguments.of(Status.Code.UNAVAILABLE, Status.Code.UNAVAILABLE), + Arguments.of(Status.Code.DEADLINE_EXCEEDED, Status.Code.DEADLINE_EXCEEDED), + Arguments.of(Status.Code.CANCELLED, Status.Code.CANCELLED), + Arguments.of(Status.Code.RESOURCE_EXHAUSTED, Status.Code.RESOURCE_EXHAUSTED), + Arguments.of(Status.Code.INTERNAL, Status.Code.INTERNAL), + Arguments.of(Status.Code.DATA_LOSS, Status.Code.UNAVAILABLE), + Arguments.of(Status.Code.UNKNOWN, Status.Code.UNKNOWN)); + return calls.stream() + .flatMap( + call -> + cases.stream().map(values -> Arguments.of(call, values.get()[0], values.get()[1]))); + } + + private static StatusRuntimeException foreignFailure(Status.Code code) { + var trailers = new Metadata(); + trailers.put(Metadata.Key.of("foreign-detail", Metadata.ASCII_STRING_MARSHALLER), "secret"); + return Status.fromCode(code) + .withDescription("foreign description") + .withCause(new IllegalStateException("foreign cause")) + .asRuntimeException(trailers); + } + + private enum DependencyCall { + RETAIN_ACCOUNT, + RETAIN_SOURCE, + ABORT_ACCOUNT + } + @Test void changedOrderUnderExistingOperationIdentityIsDeniedBeforeRemoteReads() { var fixture = new Fixture();