diff --git a/.github/scripts/run-gradle-module-checks.sh b/.github/scripts/run-gradle-module-checks.sh index 4e074f4bbf..e2f4e32cf3 100644 --- a/.github/scripts/run-gradle-module-checks.sh +++ b/.github/scripts/run-gradle-module-checks.sh @@ -15,8 +15,10 @@ if [[ $# -lt 1 || $# -gt 2 || ! "$MODULE" =~ ^[a-z0-9]+(-[a-z0-9]+)*$ || \ fi declare -a CHECK_ARGS=(-PfullCheck) +require_physical_proof=false # These required physical suites must execute, not restore cached JUnit results. -if [[ "$MODULE" == "logging-admin-service" || "$MODULE" == "social-groups-service" ]]; then +if [[ "$MODULE" == "game-design-service" || "$MODULE" == "logging-admin-service" || "$MODULE" == "social-groups-service" ]]; then + require_physical_proof=true CHECK_ARGS+=(--no-build-cache --no-configuration-cache ":${MODULE}:integrationTest" --rerun) # A skipped/no-source task must not satisfy this invocation from old XML. # Invalidate only generated JUnit reports for this module before Gradle runs. @@ -37,8 +39,15 @@ if [[ "$MODULE" == "logging-admin-service" || "$MODULE" == "social-groups-servic fi fi -verify_required_database_proof() { +verify_required_physical_proof() { case "$MODULE" in + game-design-service) + local suite="net.firedevops.firemud.gamedesign.service.VersionAssetPublicationMinioPostgresIntegrationTest" + bash "$ROOT_DIR/dev-tools/validation/inspect-test-results.sh" --strict \ + --require-suite "$suite" \ + --require-case "$suite#composesPostgresSnapshotAndCandidateWithMinioBeforeWriteAndRetriesAfterLostAcknowledgement()" \ + "$MODULE" + ;; logging-admin-service) local moderation="net.firedevops.firemud.loggingadmin.ModerationAccountUuidMigrationPostgresIntegrationTest" local report="net.firedevops.firemud.loggingadmin.ReportAccountUuidMigrationPostgresIntegrationTest" @@ -120,7 +129,7 @@ trap 'rm -f -- "$CHECK_LOG"' EXIT if [[ -z "$CHECK_LOG" ]]; then printf 'FIREMUD_STALL_ACTIVATION status=disabled-capture-unavailable\n' >&2 echo "Compile-failure log unavailable; running the original check without capture" >&2 - if [[ "$MODULE" != "logging-admin-service" && "$MODULE" != "social-groups-service" ]]; then + if [[ "$require_physical_proof" == false ]]; then # Preserve the existing exec/process boundary for every unaffected module. exec bash "$ROOT_DIR/dev-tools/validation/run-gradle-with-dependency-recovery.sh" \ --runner "$ROOT_DIR/gradlew" -- \ @@ -133,7 +142,7 @@ if [[ -z "$CHECK_LOG" ]]; then --max-workers=2 \ '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' \ ":${MODULE}:check" "${CHECK_ARGS[@]}" --profile; then - verify_required_database_proof + verify_required_physical_proof exit 0 else exit "$?" @@ -179,6 +188,6 @@ if (( check_status > 0 && check_status < 128 )); then echo "Compile-failure evidence collection unavailable; preserving check exit $check_status" >&2 fi if (( check_status == 0 )); then - verify_required_database_proof + verify_required_physical_proof fi exit "$check_status" diff --git a/design/architecture/microservices/automation-scripting-service/api-contracts.md b/design/architecture/microservices/automation-scripting-service/api-contracts.md index 0f775e99ac..3700cb9a68 100644 --- a/design/architecture/microservices/automation-scripting-service/api-contracts.md +++ b/design/architecture/microservices/automation-scripting-service/api-contracts.md @@ -221,7 +221,7 @@ Retry identity and timer catch-up behavior follow the linked scripting contract. The service exposes control-plane read and lifecycle surfaces for script patch visibility and plugin runtime lifecycle management: -- `GetScriptPatchStatus(tenantId, scriptPatchVersion)` – returns the current runtime-readiness lifecycle state plus the published script patch `baseVersionId`, compatibility digest metadata, timestamps, and any last-error details. Target `abilitySchemaDigest` must come only from the dedicated Game Logic-owned release attestation; if that attestation is missing or unavailable, the status/compatibility result must fail closed or report an explicit unavailable compatibility state, never fall back to Automation's aggregate participant digest. The current response is not compliant: it returns an empty digest when release-attestation lookup fails and otherwise derives the field from Automation's aggregate participant digest, so it does not prove ability-schema compatibility. +- `GetScriptPatchStatus(tenantId, scriptPatchVersion)` – returns the current runtime-readiness lifecycle state plus the published script patch `baseVersionId`, compatibility digest metadata, timestamps, and any last-error details. The `abilitySchemaDigest` comes from one supported Game Logic participant in the exact full base Version release bundle. An empty digest denotes unavailable compatibility evidence. Malformed, conflicting or unavailable evidence produces an empty digest for status reads and refuses plugin activation. The registered Game Design release read remains held. The local selector alone does not verify the canonical tenant UUID association. - `ListScriptPatchStatuses(tenantId, status?, changedAfter?, changedBefore?)` – lists known tenant patch statuses with the same publication metadata fields used by the single-patch read. - `ScriptPatchTenantStatusChanged` – emitted whenever `` transitions between tenant readiness lifecycle states. - `ScriptPatchPinChanged` – consumed only as a non-authoritative notification to refresh Automation's observed pin/convergence projection. Game Session's direct current-pin and bounded rollout-history reads remain authoritative. Any legacy patch-only `PINNED`, `REPINNED`, and `ROLLED_BACK` projection statuses/events are internal migration diagnostics only; they must never be exposed or consumed as public rollout status/event semantics. The target projection remains exact-epoch observed state and must not derive rollout history locally. @@ -297,3 +297,20 @@ The selected-empty service also requires the complete incoming publication reque For publication-gate calls, `GetDraftDesignDigest` is not an admin or user operation. The target receiver authorization is a method-level allowlist for the authenticated Game Design workload identity, under the shared [Security Architecture](../../system-architecture-security.md) and [Authentication & Authorization](../../system-architecture-authentication.md) owner rules. The call must carry and validate the exact `{tenantId, scope}` (`versionId` or `scriptPatchVersion`) together with the stable caller `publishRequestId`, derived workflow identity, and canonical `requestDigest`; omitted or changed binding fails closed. This context is authorization and replay evidence, not a digest input. Other internal workloads are denied, and no user/admin JWT is accepted as a substitute. Game Design's Temporal activities must never forward the initiating human operator JWT; operator authority terminates at workflow admission. **Current status:** `GetDraftDesignDigest` invokes `PublicationReadGuard` for the exact Automation publication-read method. The guard requires the authenticated exact Game Design workload mTLS peer in the configured trusted namespace and denies account, global-role, or scoped-role context. It does not add an end-user JWT requirement; a role-free internal identity is neither workload authorization nor an independent denial condition when the exact peer is present. The request proto carries tenant, typed scope, the patch `baseVersionId` when applicable, stable `publishRequestId`, derived workflow identity, and canonical `requestDigest`; the handler validates that complete binding before returning `UNSUPPORTED_SCOPE` for either selector. Focused unit proof covers the allowlisted peer without end-user context, missing/wrong peer, account/global/scoped-role context denial, and changed request digest. This does not claim live mounted-certificate or real Temporal-activity proof. The selected-empty schema-6 primitive remains unregistered; exact version mapping and the base-bound patch manifest are still required before a publication digest can be returned. See the [Game Design publication/Temporal contract](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) for the coordinator-side boundary. + +### Private script-patch content seal + +The standalone, unregistered `ScriptPatchPublicationSealService` captures exact +definitions and event bindings in a physically verified writable READ COMMITTED +transaction under the same PostgreSQL patch-row lock acquired +by raw writes to definitions, bindings and retained base bindings. Forward V1006 +stores a numeric base, schema-5 content digest and immutable snapshot with the +canonical publication request and workflow binding. Identical replay retains the +original bytes; changed content, request or base refuses. Historical authored rows +are not assigned a seal, and catalog epoch 3 explicitly classifies the new source +family while retaining preceding catalog epochs and evidence. + +This is a private content-storage primitive, not an authenticated publication +receiver or affected-handler readiness manifest. It deliberately does not infer +`onLoadHandlerIds` from script names. Existing `UNSUPPORTED_SCOPE` and +`SCRIPT_PATCH_MANIFEST_UNAVAILABLE` boundaries remain unchanged. diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index f96a030967..441b381eec 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -87,6 +87,10 @@ The existing default-off run-owned fixture configuration registers operation-sco The owner-local foundation persists authored-world source operations and delivery outbox rows, canonical Version and bundle identity, opaque release references, optional manifest/artifact metadata, and additive launch-descriptor bindings. There is no creator source-registration RPC. The complete fixture successor activates only the claimed run-owned producer and source-bound descriptor handlers described above; production launch-read authorization remains deny-only. Ordinary new Version and bundle writes derive identity from the exact persisted Game row; retained all-null descriptor reads and inserts remain supported. State-changing `CompareAndSetVersionState` calls return `VERSION_STATE_MUTATION_UNAVAILABLE` after tenant/version and expected-epoch checks; exact same-state requests remain no-ops. This containment does not establish legal lifecycle transitions, Account authorization, or database CAS proof. +Genuine fresh `NEW_GAME_ROW` registration commits one durable World delivery intent in the same owner transaction. The intent binds the immutable source evidence and original `intakeRequestId`. Exact source retries and delivery recovery reuse that identity. Historical source-only operations retain their original source receipt and receive no inferred or backfilled delivery claim. + +The standalone delivery service invokes [authenticated World intake and readback](../world-management-service/api-contracts.md#grpc-apis) outside the Game Design transaction. It compares the complete original intake and independent readback before retaining an acknowledgement. Concurrent exact acknowledgements converge on the same receipt, and a conflicting receipt is refused. A post-commit failure is reconciled through an independent Game Design read; a completed retry returns that receipt before contacting World. An unresolved response leaves the original claim pending. This is source delivery without creator, publication or admission authority. + The fresh-tenant owner source includes V29 canonical UUID/provenance storage, V30 exact creation-operation persistence, the owner-local transaction producer and source readback, and the exact Account/Game Session peer receipt read RPC. Validation evidence and remaining gaps belong to the linked implementation tracker. No creator RPC or authenticated creator authority is wired, and no Account association, membership, JOIN, or runtime admission is enabled by this source. The release-attestation, launch-resolution, version-state, settings, asset-purge, script-patch publication read APIs, and plugin publication workflow remain in the current proto/service path. `PublishVersion` carries the selected existing Version, expected state epoch, and synchronized commit request/commit/digest. Public and registered Temporal ingress deny fresh and PENDING full-version requests before mutation: current Account authorization, authenticated World owner-freeze production, and a production version-to-Draft association are unavailable. The orchestrator does not start a workflow, and activities propagate the refusal without writes or synthetic terminal outcomes. The legacy no-selection shape supports exact retained terminal replay only: FAILED returns its stored result, while SUCCEEDED requires exact immutable release readback. @@ -95,7 +99,7 @@ The conditional selected-publication command also requires World confirmation af Selected source capture, staging, export, finalization, and sealing remain non-ingress package-private conditional mechanics, not production publication. The selected path freezes an immutable asset-export candidate and validates its origin/snapshot integrity; the finalizer requires a captured publication operation and same-transaction terminal seal. These mechanics and their local readback proofs do not establish Account authority, a production World freeze, public capability, or reachable publication success. The four owner-to-owner digest handlers retain exact Game Design workload identity and tenant/scope/request binding, but end-to-end publication also lacks Game Logic owner-local manifest/provenance for rule inputs, exact-version Automation content mapping, and live mounted-certificate, Temporal-activity, and multi-version owner proof (see [Game Logic API Contracts](../game-logic-service/api-contracts.md#implementation-status)). Release storage retains canonical Version identity, an opaque owner reference, manifest schema, artifact digests, and exact persisted readback; those fields do not establish selected commit provenance or a public tenant projection. The canonical digest and candidate rules are owned by [Version Control](version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) and [Asset Storage](asset-storage.md#asset-lifecycle-and-publish-workflow). -`UploadPluginBundle` persists signed plugin bundles and one allowlisted `signerKeyId`, but not the complete target `verifiedSignatures[]` set or an append-only signature-evidence ledger. `PublishPluginVersion` exports version-scoped plugin assets and checks `abilitySchemaDigest` against the `AUTOMATION_SCRIPTING` aggregate participant digest; the target Game Logic-owned ability-schema attestation for the same base version remains absent. Design-time revoke transitions and publication-event reads are present, while broader activation-time alias/binding validation remains incomplete. Account currentness and durable tenant/evidence binding required by [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) are not implemented for creator mutations. +`UploadPluginBundle` persists signed plugin bundles and one allowlisted `signerKeyId`, but not the complete target `verifiedSignatures[]` set or an append-only signature-evidence ledger. `PublishPluginVersion` requires one successful Game Logic participant with a dedicated ability-schema digest for the exact full base Version and compares it before exporting plugin assets. This check requires already retained release evidence; it grants no authority to publish the base Version. Design-time revoke transitions and publication-event reads are present, while broader activation-time alias/binding validation remains incomplete. Account currentness and durable tenant/evidence binding required by [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) are not implemented for creator mutations. The shared deny-only owner-proof boundary also refuses `POST /assets` with HTTP `503 Service Unavailable` and its stable structured owner-proof error before multipart access or persistence and refuses state-changing `CompareAndSetVersionState` requests before a Version write. Reads and an exact same-state no-op remain available. These refusals do not implement Account authorization, the legal lifecycle transition matrix, release evidence, or retirement predicates; full-version fresh/PENDING denial and exact terminal replay retain their existing behavior. diff --git a/design/architecture/system-architecture-gateway.md b/design/architecture/system-architecture-gateway.md index 54b351aa8d..f02fe56c9e 100644 --- a/design/architecture/system-architecture-gateway.md +++ b/design/architecture/system-architecture-gateway.md @@ -11,7 +11,7 @@ Gateway does not validate ordinary REST or admin JWTs; the consuming Account, ad Unless otherwise noted, this document describes target-state gateway behavior. Current rollout and implementation boundaries are: - The target-state declarative `routes.yml` catalog has not yet converged as the implemented route authority. The current authority is the Java `CanonicalGatewayRoutesConfiguration`, with route-specific environment overrides `FIREMUD_GATEWAY_ROUTE_SESSION_URI`, `FIREMUD_GATEWAY_ROUTE_ADMIN_URI`, `FIREMUD_GATEWAY_ROUTE_DESIGN_URI`, `FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI`, and `FIREMUD_GATEWAY_ROUTE_SOCIAL_URI`. These are distinct from the `FIREMUD_SERVICES_*` service-discovery variables used by other microservices. See [Environment Variables & Secrets Management](./infrastructure/environment-and-secrets.md#service-discovery). -- **Current Game Design route consequence:** the Java route catalog's coarse `/api/design/**` entry forwards `/api/design/assets` through `StripPrefix=2` to Game Design's live `POST /assets` controller. The controller currently checks only privileged JWT/tenant access and has no Account hosted-terms/currentness gate; official-hosted asset-upload readiness is blocked until Gateway denies this route or the exact Account-owned gate is implemented and proved. +- **Current Game Design route consequence:** the Java route catalog exposes only `GET /api/design/ping` and `GET /api/design/templates`; it has no coarse `/api/design/**` or `/api/design/assets` mutation route, so edge asset writes are denied. The Game Design owner-side Account hosted-terms/currentness gate is still absent. This route restriction makes no readiness claim; official-hosted asset-upload readiness remains unproved pending the exact Account-owned gate and its proof. - Published `/assets/**` delivery is target-only pending a separate approved public origin/provisioner. The current Gateway route catalog has no `/assets/**` route or asset-store route ID, and private MinIO is not public delivery. The reserved `/assets/**` family remains separate from the first-party static-host `/frontend-assets/**` family. - The current TCP Proxy → Gateway runtime implements the dedicated internal WSS listener, one environment-bound trust profile selected by the exclusive matcher described by [ADR 0169](./decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md), and TCP Proxy client-credential reload for new bridges. The private Helm candidate is owned by #2713; public activation and proof remain owned by #2795. Gateway listener TLS watches coherent certificate/key/CA material for new-handshake renewal and fails new traffic/readiness closed on an unhealthy watcher; this is not emergency revocation or live trust-profile replacement. Certificate-bound profiles use mTLS with the exact URI SAN for steady-state player-facing traffic, named expiring DNS migration, or named expiring leaf-fingerprint break-glass; development/test-only `development_cidr` uses TLS without client authentication plus the exact configured source-CIDR predicate. Controller issuance/projection, hosted rotation/readiness proof, emergency withdrawal evidence, and exact-head hosted peer-handshake proof remain incomplete boundaries. - The target replay domain remains a Gateway-owned Coordination Redis contract defined by the Redis ownership and recovery documents. Its non-secret `FIREMUD_GATEWAY_REPLAY_DOMAIN` pin and shared hash-tag contract remain unimplemented. The current `GameplayHandshakeFilter` denies a presented first-party cookie with `CONNECT_REPLAY_PROTECTION_UNAVAILABLE` before validation, context signing, replay consumption, or upstream admission; it no longer authorizes handshakes through a legacy Cache-bound replay marker. Dedicated signing-key delivery, shared readiness/fence/consume writers, browser-deny state, and qualified Account source production remain open. Removing the old writer does not establish legacy-state cleanup: retain prior markers through their original acceptance windows and use the owner-defined inventory/readback and recovery contract before target admission. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index da01ecd184..d77eb4f00a 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,6 +6,16 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +### Old-stack source delivery receiving preparation + +The standalone [GameAuthoredWorldSourceDeliveryService](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredWorldSourceDeliveryService.java) receives the source-delivery remainder from #3014 against the current durable claim repository and authenticated World client. It rejects ambient transactions, dispatches the original immutable claim, independently reads the World receipt, and acknowledges and rereads the exact owner result. An ambiguous Game Design acknowledgement triggers an independent owner read without redispatching in the same call. The Creator comparison at head `9a07a18a2d` over Player base `465a9623a9` passed nine focused units, six Game Design PostgreSQL delivery cases and five cross-service PostgreSQL/mTLS cases with zero failures, errors or skips. The physical delivery case verified the committed World receipt, durable Game Design acknowledgement, exact retry and preservation of an unrelated queued claim over authenticated sockets. Production scheduling, registration and activation remain open, along with the disposition of the other #3014 source obligations. [Creator Game Design validation](https://github.com/benhook1013/FireMUD/actions/runs/46035099192/job/140633573928) + +The standalone [authored-world delivery worker](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredWorldSourceDeliveryWorker.java) runs one explicit namespace-bounded page outside ambient transactions. One pass per worker instance advances past an ambiguous item and later retries its original claim. The worker has no scheduled or application registration. + +The #3065 authored-source read proof is separately received against the current standalone owner adapter. Thirty-one focused cases pass, including nine real loopback mTLS socket cases with the shared client, eight owner-adapter units and fourteen current Account-fenced association transport/owner cases. The source reader admits the exact same-namespace World identity and rejects Game Session, wrong namespace/workload/server identity, missing client certificates, JWT-only authority, malformed evidence and the obsolete legacy RPC. Repositories remain mocked in the socket proof: this does not establish PostgreSQL source persistence, intake/delivery composition, public registration or whole-donor retirement. + +The #3097 receiving slice passed fifteen hosted-terms service and environment-binding unit cases during initial preparation. Creator head `9a07a18a2d` over Player base `465a9623a9` subsequently passed all 34 required PostgreSQL cases with zero failures, errors or skips. The physical proof covers 26 required-owner cases, five hosted-terms cases and three environment-binding cases. Historical migration assertions cover the current V75–V76 and V84–V85 boundaries, and operational fixtures use the current schema. The donor’s other mixed-owner JOIN, issuer, tenant, logout and reset proof obligations and runtime activation remain open. [Creator Account coverage aggregate](https://github.com/benhook1013/FireMUD/actions/runs/46035099192/job/140669431934) + ### Selected Entity and Automation intake prerequisite The Entity and Automation owner-local empty selected-source intake commands, terminal and digest primitives, shared codecs and security clients remain source-prepared, standalone, unregistered and default-denied. Exact namespace, workload, current Account and World binding guards remain part of the owner boundary. This work grants no fresh public publication, finalizer registration, continuous protection, genuine issuer or creator authority, admission or activation. Controlled selected-full Game Design and Game Logic publication composition and its five-store proof are recorded in [Selected-full owner publication preparation](#selected-full-owner-publication-preparation), with their source attribution and authority limits. Canonical behavior remains in the [Entity contract](../../architecture/microservices/entity-management-service/api-contracts.md), [Automation contract](../../architecture/microservices/automation-scripting-service/api-contracts.md) and [Game Design selected-full profile](../../architecture/microservices/game-design-service/version-control.md#selected-full-publication-profile). @@ -132,6 +142,8 @@ The existing Game Design source PostgreSQL owner test now exercises reviewed cla All twenty-one owning native cases freshly pass with zero failures, errors or skips, including the five restored claim cases and the sixteen existing source and storage-race cases. Canonical formatting, style, Integration Checkstyle and SpotBugs pass. Passive capture identifies the one run-owned PostgreSQL container and independently confirms its absence after completion. The concurrent launch latches establish the submitted competing operations and retained outcomes; they do not independently measure precommit blocking. This is current-default local storage and reviewed-source proof, without authenticated creator or issuer, Account currentness, remote owner application, public publication enablement, a genuine immutable release, activation or a Gameplay handoff. No production code, installed migration, finalizer, recovery composer or registration is changed. +The #3004 receiving proof at `ff954fe3123cd80dcd7ae41a7cc75c94fce37ed6` additionally measures precommit blocking at the coordinator's underlying Draft claim. In both cases in the [terminal outcome PostgreSQL suite](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomePostgresIntegrationTest.java), PostgreSQL identifies the original transaction as the competing claim's blocker. One Version/commit cannot be claimed with a different request, and one request cannot be claimed again with different revision bytes. After the original commits, the competing call returns the typed conflict. Exact replay preserves the original binding and all owner rows, including their `xmin`. Both cases passed on current Flyway migrations. Reviewed-source authorization and remote owner execution remain separate proof. + ### Template create and tenant-qualified updates The existing create service rejects a caller-supplied template ID before mapping or repository access. The repository updates only the exact tenant and template ID, never writes a replacement tenant binding and requires exactly one affected row before its tenant-qualified readback. No new public update API, migration, registration or hosted-content authority is introduced. @@ -298,9 +310,11 @@ The published run-owned fixture successor in #3171 consolidated local affected-c Game Design's script-patch and plugin transition implementation remains partial: design-time publication metadata and bounded local activation-preflight seams exist, but dedicated Game Logic ability-schema compatibility, tenant runtime readiness, exact instance pin/epoch propagation, rollout/rollback history, and end-to-end recovery proof remain absent or unproved. The ownership and lifecycle contracts for these gaps are recorded in [ADR 0103](../../architecture/decisions/adr-0103-single-authority-script-pins-with-exact-version-execution.md), [ADR 0106](../../architecture/decisions/adr-0106-epoch-fenced-script-rollback-without-routine-gameplay-pause.md), [ADR 0107](../../architecture/decisions/adr-0107-stage-aware-script-dead-letter-recovery.md), [ADR 0108](../../architecture/decisions/adr-0108-no-degraded-script-admission-without-authoritative-pin.md), [ADR 0109](../../architecture/decisions/adr-0109-game-session-owned-script-rollout-history.md), [ADR 0110](../../architecture/decisions/adr-0110-explicit-opt-in-schedule-continuity-across-script-transitions.md), [ADR 0111](../../architecture/decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md), and [ADR 0119](../../architecture/decisions/adr-0119-epoch-fenced-per-instance-plugin-activation.md). This tracker records only current implementation and proof status. +Game Design plugin publication and Automation's candidate script-patch status and plugin activation readers consume the dedicated Game Logic digest from exact full-Version release evidence. The script status surface exposes unavailable evidence as an empty digest, and the plugin path refuses activation on unavailable or mismatched evidence. The registered Game Design release read remains held, so the local readers do not qualify production compatibility or activation. + AR-1.5 full-version publication remains fail-closed at public and registered Temporal ingress. The selected request carries an exact existing Version, expected state epoch, and synchronized commit identity, but current Account authorization, authenticated World owner-freeze production, and a production version-to-Draft association are unavailable. The shared command guard denies fresh and PENDING requests before mutation; the configured orchestrator does not start a workflow, and registered activities propagate the refusal without writes or synthetic terminal outcomes. Exact terminal replay remains available: FAILED returns its stored result, while SUCCEEDED requires exact immutable bundle readback. -Selected source capture, candidate staging/export, finalization, and terminal sealing remain non-ingress package-private conditional mechanics, not production publication. The asset candidate retains its frozen origin and snapshot-integrity checks; the selected finalizer requires a captured publication operation and same-transaction terminal seal. The private asset path uses immutable content-addressed keys, conditional writes, and exact readback, while physical deletion is hard-disabled. Local transaction, participant, and ambiguous-readback proof does not establish authorization, a production World freeze, or a reachable success path. PostgreSQL rollback, physical object-store behavior, live Temporal-owner publication, cross-phase recovery, and historical revision/version lineage remain unproved. Current ingress status is owned by [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status); digest and candidate rules are owned by [Version Control](../../architecture/microservices/game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow). +Selected source capture, candidate staging/export, finalization, and terminal sealing remain non-ingress package-private conditional mechanics, not production publication. The asset candidate retains its frozen origin and snapshot-integrity checks; the selected finalizer requires a captured publication operation and same-transaction terminal seal. The private asset path uses immutable content-addressed keys, conditional writes, and exact readback, while physical deletion is hard-disabled. Local transaction, participant, and ambiguous-readback proof does not establish authorization, a production World freeze, or a reachable success path. The isolated [asset publication proof](#published-asset-lifecycle) covers the private snapshot-to-object-store export and exact retry. PostgreSQL rollback across the full publication workflow, live Temporal-owner publication, cross-phase recovery, and historical revision/version lineage remain unproved. Current ingress status is owned by [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status); digest and candidate rules are owned by [Version Control](../../architecture/microservices/game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow). The local canonical-assignment/source-key coexistence correction is implemented in Entity's V1011 guard. Child writers and gameplay admission remain disabled; see [Entity Management API Contracts](../../architecture/microservices/entity-management-service/api-contracts.md#digest-input-manifest) for the owning implementation status. @@ -339,7 +353,7 @@ The published `888f` GDS foundation slice contains source-operation/outbox stora | `AR-1.1` World, entity, rule, and content authoring | `partial` | `proven` for the owner-local World mutation algorithm, authored help/command, and entity-template validation seams; the registered revision-to-World ingress is denied, and complete world, entity, rule, and content authoring remains unproved. | [Game Design ownership](../../architecture/microservices/game-design-service/README.md); [world editing tools](../../architecture/microservices/game-design-service/world-editing-tools.md); [ability/action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [item and equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [GameAuthoredHelpTopicServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImpl.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql); [EntityTemplateReferenceServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityTemplateReferenceServiceImpl.java) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [GameAuthoredHelpTopicServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImplTest.java); [EntityTemplateReferenceServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityTemplateReferenceServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md) | Partial: authored help/commands and entity template/runtime validation seams exist, but the registered typed World mutation ingress is denied, and complete rule/action/effect catalogs and creator-facing authoring workflows are not implemented. Accepted procedural-generation decisions now define World-owned typed ingress and preview-bound replacement, but typed generation ingress, destructive plan protocol, and identity/reference proof remain incomplete. | | `AR-1.2` Procedural, LLM-assisted, and external authoring tools | `partial` | `proven` for bounded procedural generation and the owner-local typed generation mutation algorithm; registered typed generation ingress, LLM-assisted authoring, destructive plans, staging bounds, and large-grid behavior remain unproved. Whole-game package import/export, filesystem/Git interchange, and portable snapshots are outside the current target per [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md), not merely unproved. The [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) typed creator-API/scoped-proposal path is target-only and remains unimplemented/unproved. | [LLM content tools](../../architecture/system-architecture-llm-content-tools.md); [procedural generation](../../architecture/system-architecture-procedural-generation.md); [generation control](../../architecture/microservices/world-management-service/procedural-generation-control.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md); [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) | [GenerationServiceImpl.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImpl.java); [DungeonGenerator.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/DungeonGenerator.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java) | [GenerationServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImplTest.java); [DungeonGeneratorTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/DungeonGeneratorTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md) | Partial: bounded procedural generation and owner-local typed generation mutation tests exist, but registered typed generation ingress, destructive plan protocol, staging bounds, and large-grid proof remain incomplete. Whole-game portability remains non-target under ADR 0125; model-assisted authoring remains target-only under ADR 0126 with no production contract or focused proof. | | `AR-1.3` Script, plugin, mod, and extension packaging | `partial` | `proven` only for signed plugin intake and bounded local activation-preflight/control-plane seams; new script-patch publication is contained pending manifest authority; full activation admission and canonical compatibility remain unproved because the dedicated Game Logic ability-schema attestation, tenant runtime readiness, and exact instance pin/epoch gates are not wired. Broader mod/extension packaging, creator tooling, and distribution lifecycle also remain unproved. | [Modding framework](../../architecture/microservices/game-design-service/modding-framework.md); [scripting control-plane API](../../architecture/system-architecture-scripting-control-plane-api.md); [scripting rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md) | [PluginBundleIntakeServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleIntakeServiceImpl.java); [PluginBundleStorageServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleStorageServiceImpl.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [V18 published plugins](../../../services/game-design-service/src/main/resources/db/migration/V18__published_plugin_versions.sql) | [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java); [PluginActivationPreflightServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [AutomationScriptingControlPlaneGrpcServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingControlPlaneGrpcServiceTest.java) | [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: signed plugin and script-patch publication/readiness seams exist, but live compatibility preflight uses Automation's aggregate participant digest instead of the required dedicated Game Logic-owned ability-schema attestation. Canonical ability-schema compatibility, broader mod/extension package formats, creator tooling, distribution lifecycle, complete runtime readiness convergence, and complete target signature-set persistence/exposure remain incomplete. Current live intake selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set. ADR 0111 owns the accepted target provenance and lifecycle boundary. | -| `AR-1.4` Game-authored assets, branding, and release manifests | `partial` | `proven` only for controlled-input ordinary asset-source creation and synchronized projection, with focused proof in `GameDesignSourcePostgresIntegrationTest` and `VersionAssetExportSnapshotIntegrationTest`; production authoring ingress and the full publication workflow, durable object-store proof, purge, and runtime delivery remain absent or unproved. Earlier frozen-origin, snapshot-integrity, candidate export/readback, and release-v2 selector migration proof retains its exact historical attribution below. | [Game Design asset storage](../../architecture/microservices/game-design-service/asset-storage.md); [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md); [game customization](../../architecture/system-architecture-game-customization.md); [versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md) | [AssetExportServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java); [VersionAssetArtifactServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java); [VersionAssetExportCandidateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java); [VersionAssetPublicationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [PublishedReleaseBundleContract.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java); [V8 release bundle](../../../services/game-design-service/src/main/resources/db/migration/V8__published_release_bundle.sql); [V10 asset artifact](../../../services/game-design-service/src/main/resources/db/migration/V10__version_asset_artifact.sql); [V35.2 canonical release version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V37 mapping and export snapshot](../../../services/game-design-service/src/main/resources/db/migration/V37__version_asset_export_snapshot.sql); [V38 published asset digest evidence](../../../services/game-design-service/src/main/resources/db/migration/V38__published_asset_digest_evidence.sql); [V49 published-world selector evidence](../../../services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql); [V49.1 selected-world release participant schema](../../../services/game-design-service/src/main/resources/db/migration/V49.1__selected_world_release_participant_schema.sql); [V50 frozen candidate origin](../../../services/game-design-service/src/main/resources/db/migration/V50__freeze_asset_export_candidate_public_origin.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java); [AssetSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java); [GameDesignSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java); [V1003 ordinary asset source](../../../services/game-design-service/src/main/resources/db/migration/V1003__ordinary_asset_source.sql); [V1024 asset-bound reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V1024__asset_bound_reviewed_draft_base.sql) | [AssetExportServiceImplTest.java](../../../services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java); [VersionAssetExportCandidateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java); [VersionAssetArtifactServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [PublishedReleaseBundleContractTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [PublishedWorldSelectorSchemaMigrationIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [GameDesignSourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java); [VersionAssetExportSnapshotIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java) | [platform operations](./platform-operations-and-delivery.md); [player experience](./player-experience-commands-and-communication.md) | Partial: the current source includes Draft `version_asset` mappings, a durable version-scoped export snapshot with independent readback, candidate export/readback, and immutable v1 bundle storage with canonical identity, opaque reference, manifest-schema metadata, and artifact digests. Release-v2 selector binding is enforced by `PublishedReleaseBundleContract.requireSelectorBinding`; current pinned-source physical proof covers V49 and V49.1, the frozen V50 candidate origin, and database-computed snapshot hash/length verification. Normal export consumes the frozen snapshot and records candidate manifest/artifact digest evidence before object writes; published repair independently reads the immutable candidate and checks it against the exact release bundle before object writes. Production authoring ingress remains absent, so public and registered Temporal full-version ingress fails closed before mutation. Complete Draft quota admission, unbounded whole-selection hash work, durable object-store candidate isolation, integrated lifecycle migration closure, global publication/purge fencing, destructive lifecycle safety, complete creator UX, approved external delivery, and runtime launch readiness remain incomplete or unproved. Ordinary asset-source creation and synchronized projection are owned by `AssetSourceRepository` and `GameDesignSourceRepository`; direct `associateDraftAsset` fails closed. Migration V1003 establishes ordinary asset source storage and V1024 binds reviewed-base evidence to its asset. | +| `AR-1.4` Game-authored assets, branding, and release manifests | `partial` | `proven` for controlled-input ordinary asset-source creation and synchronized projection, with focused proof in `GameDesignSourcePostgresIntegrationTest` and `VersionAssetExportSnapshotIntegrationTest`, and for private immutable export and exact retry in the [isolated asset publication proof](#published-asset-lifecycle). Production authoring ingress, the full publication workflow, purge, and runtime delivery remain absent or unproved. Earlier frozen-origin, snapshot-integrity, candidate export/readback, and release-v2 selector migration proof retains its exact historical attribution below. | [Game Design asset storage](../../architecture/microservices/game-design-service/asset-storage.md); [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md); [game customization](../../architecture/system-architecture-game-customization.md); [versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md) | [AssetExportServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java); [VersionAssetArtifactServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java); [VersionAssetExportCandidateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java); [VersionAssetPublicationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [PublishedReleaseBundleContract.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java); [V8 release bundle](../../../services/game-design-service/src/main/resources/db/migration/V8__published_release_bundle.sql); [V10 asset artifact](../../../services/game-design-service/src/main/resources/db/migration/V10__version_asset_artifact.sql); [V35.2 canonical release version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V37 mapping and export snapshot](../../../services/game-design-service/src/main/resources/db/migration/V37__version_asset_export_snapshot.sql); [V38 published asset digest evidence](../../../services/game-design-service/src/main/resources/db/migration/V38__published_asset_digest_evidence.sql); [V49 published-world selector evidence](../../../services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql); [V49.1 selected-world release participant schema](../../../services/game-design-service/src/main/resources/db/migration/V49.1__selected_world_release_participant_schema.sql); [V50 frozen candidate origin](../../../services/game-design-service/src/main/resources/db/migration/V50__freeze_asset_export_candidate_public_origin.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java); [AssetSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java); [GameDesignSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java); [V1003 ordinary asset source](../../../services/game-design-service/src/main/resources/db/migration/V1003__ordinary_asset_source.sql); [V1024 asset-bound reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V1024__asset_bound_reviewed_draft_base.sql) | [AssetExportServiceImplTest.java](../../../services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java); [VersionAssetExportCandidateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java); [VersionAssetArtifactServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [PublishedReleaseBundleContractTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [PublishedWorldSelectorSchemaMigrationIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [GameDesignSourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java); [VersionAssetExportSnapshotIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java) | [platform operations](./platform-operations-and-delivery.md); [player experience](./player-experience-commands-and-communication.md) | Partial: the current source includes Draft `version_asset` mappings, a durable version-scoped export snapshot with independent readback, candidate export/readback, and immutable v1 bundle storage with canonical identity, opaque reference, manifest-schema metadata, and artifact digests. Release-v2 selector binding is enforced by `PublishedReleaseBundleContract.requireSelectorBinding`; current pinned-source physical proof covers V49 and V49.1, the frozen V50 candidate origin, and database-computed snapshot hash/length verification. Normal export consumes the frozen snapshot and records candidate manifest/artifact digest evidence before object writes; published repair independently reads the immutable candidate and checks it against the exact release bundle before object writes. Production authoring ingress remains absent, so public and registered Temporal full-version ingress fails closed before mutation. Complete Draft quota admission, unbounded whole-selection hash work, durable object-store candidate isolation, integrated lifecycle migration closure, global publication/purge fencing, destructive lifecycle safety, complete creator UX, approved external delivery, and runtime launch readiness remain incomplete or unproved. Ordinary asset-source creation and synchronized projection are owned by `AssetSourceRepository` and `GameDesignSourceRepository`; direct `associateDraftAsset` fails closed. Migration V1003 establishes ordinary asset source storage and V1024 binds reviewed-base evidence to its asset. | | `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` for focused immutable-source unit/static boundaries and the fail-closed publish gate, exact terminal replay, release-bundle readback, and bounded participant-digest seams; controlled five-store selected-full qualification commits the v4 bundle with the exact 4/3/1/6/2 participant vector and proves immutable readback/retry, as recorded above; public fresh/PENDING full-version publication and legacy bundle creation remain refused; this does not prove historical revision/version lineage. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. Historical published source proof checkpoint `9bf78e22f742c3830821c920e70570eb1bc03e2b`: Validation `38354137185` (source job `115153084495`) physically executed 473 unit and 109 physical PostgreSQL cases with zero skips. The local primary log `gameplay3120-cli4-full-gds-proof.log` covers 05:45:24–05:49:53; after the nullable-query assertion fixes, `gameplay3120-cli4-final-affected-proof.log` records 27 affected physical PostgreSQL cases with zero skips at 05:52–05:54. Formatting/fullCheck, Checkstyle, and all three SpotBugs tasks passed on those matching postimages. The combined local proof described above covers the V50.15 owner-list guard and exact publication-terminal denial assertions; current-head source Validation `38361682862` (job `115177242916`) independently confirms all 476 unit and 114 physical PostgreSQL cases pass without skips on published `3e8126217206419bc379497988884739a8e1fda0`. This checkpoint does not claim new-head CI, packaged-runtime, full-workflow, or runtime-activation completion. The bounded Entity/Automation selected-source intake and terminal-read slice has focused source/storage/transport proof at `f9e3f879d137b9a6fa54085e9c0b797586636a00`. The shared selected-source digest helper was introduced at `fdcc676597d33a154c92967baf33ad540387ddf8`; it is absent at `f9e3f879d137b9a6fa54085e9c0b797586636a00` and present at the later `a5d501ca95f30a6dd86fc7a24290d443fb75fba4` Entity checkpoint. The current-source Entity execution at `17c82ab6462868a2f66dfe8a3cbc737bdd013383` passed 44 cases across seven suites in 67.986 seconds with zero failures, errors, or skips. Its 11-case physical PostgreSQL `EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest` included `selectedEmptyPublicationReaderResolvesOnlyTheValidatedReceiptForTenantAndGameDesignRow`; that test calls the Entity digest reader and compares the returned digest with an independently framed expected value. This was a focused gate, not a fresh whole-service Entity run. Separately, the exact-source Automation gate at `f2d3142214654736c224cb02f817d33f751b744d` passed 33 cases across eight suites in 75.453 seconds with zero failures, errors, or skips: 20 unit cases, nine physical PostgreSQL repository cases, three mocked service-integration cases, and one actual terminal-read mTLS/PostgreSQL case. The six-case physical PostgreSQL `AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest` included `selectedEmptyPublicationReaderUsesTheRetainedTargetProofAndReturnsSchemaSixDigest`. The earlier Entity attribution at `a5d501ca95f30a6dd86fc7a24290d443fb75fba4` remains a separate historical checkpoint and is not part of the Automation aggregate. The Entity digest receiver unit result belongs to initial `e2c38ec63dc3664877ee0f7c8fb62ef6574777ce`: 917 Common, 187 Common Security, and 23 Entity unit cases passed on unchanged postimages, but that aggregate failed at test compilation. The receiver result does not establish a fresh whole-service aggregate. The slice remains standalone and unregistered; this proof does not establish complete owner publication, registration, or runtime activation. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [Entity selected-source contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Automation selected-source contracts](../../architecture/microservices/automation-scripting-service/api-contracts.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql); [V35.1 canonical Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql); [V35.2 canonical release Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V39 publication evidence text](../../../services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java) ; [CommandSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java); [RealmPolicySourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java); [RealmPolicyPublicationGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java); [GameDesignPublicationOperationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java); [GameDesignReviewedBaseRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseRepository.java); [V50.1 Draft coordination](../../../services/game-design-service/src/main/resources/db/migration/V50.1__durable_draft_commit_coordination.sql); [V50.2 authored selection](../../../services/game-design-service/src/main/resources/db/migration/V50.2__authored_draft_publish_selection.sql); [V50.6 terminal seal](../../../services/game-design-service/src/main/resources/db/migration/V50.6__publication_operation_terminal_seal.sql); [V50.8 realm-policy source](../../../services/game-design-service/src/main/resources/db/migration/V50.8__immutable_realm_policy_source.sql); [V50.9 policy publication evidence](../../../services/game-design-service/src/main/resources/db/migration/V50.9__sealed_realm_policy_publication_evidence.sql); [V50.10 command source](../../../services/game-design-service/src/main/resources/db/migration/V50.10__immutable_command_source.sql); [V50.11 reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V50.11__immutable_reviewed_draft_base.sql); [V50.12 policy head transitions](../../../services/game-design-service/src/main/resources/db/migration/V50.12__realm_policy_source_head_transition_guard.sql); [V50.13 stable publication release-row receipt evidence](../../../services/game-design-service/src/main/resources/db/migration/V50.13__stable_publication_release_row_evidence.sql); [V50.14 Draft visibility and realm-policy source-head guards](../../../services/game-design-service/src/main/resources/db/migration/V50.14__draft_visibility_and_realm_policy_source_insert_guards.sql) ; [V50.15 required-owner binding guards](../../../services/game-design-service/src/main/resources/db/migration/V50.15__draft_commit_required_owner_guards.sql); [V50.16 reviewed source-application guards](../../../services/game-design-service/src/main/resources/db/migration/V50.16__reviewed_source_application_guards.sql); [AssetSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java); [GameDesignSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java); [V1003 ordinary asset source](../../../services/game-design-service/src/main/resources/db/migration/V1003__ordinary_asset_source.sql); [V1024 asset-bound reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V1024__asset_bound_reviewed_draft_base.sql); [EntityEmptySelectedSourceIntakeService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeService.java); [EntityEmptySelectedSourceIntakeTerminalReadService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeTerminalReadService.java); [EntitySelectedEmptyPublicationDigestService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestService.java); [AutomationEmptySelectedSourceIntakeService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java); [AutomationEmptySelectedSourceIntakeTerminalReadService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeTerminalReadService.java); [AutomationSelectedEmptyPublicationDigestService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestService.java); [PublishedReleaseBundleContract.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java) ; [RealmPolicyPublicationPostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java); [RealmPolicySourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java); [GameDesignSourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java); [CommandSourceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java); [RealmPolicyPublicationGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java); [VersionAssetExportSnapshotIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java); [EntityRetainedAuthoredActorCoreSourceServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceServiceTest.java); [AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java](../../../services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java); [EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java); [AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java); [EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java); [AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java](../../../services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java); [SelectedFullOwnerPublicationPostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java); [PublishedReleaseBundleContractTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial immutable command/realm-policy source, reviewed-base and terminal-seal capability with focused unit/static proof; Partial: fresh and PENDING full-version publication and legacy bundle creation fail closed; exact terminal replay and bundle readback seams exist. Controlled selected-full qualification uses World digest schema 4 and a v4 bundle; exact retained v2/World-3 history remains readable. The owner components remain standalone and unregistered, with controlled authority inputs; public fresh/PENDING publication remains denied. The bundle read projects optional manifest-schema and artifact-digest fields, but canonical target-commit provenance and actual-byte producer population remain unproved, so same-commit attestation convergence is not established. Historical revision/version lineage remains a retained-data deployment blocker requiring exact readback before migration cleanup or any completion claim. Complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. | | `AR-2.1` Typed settings, defaults, scopes, and precedence | `partial` | `proven` for typed settings metadata/defaults, persisted overrides, effective resolution, and command-capability resolution seams; selected presets, operator bootstrap/runtime layers, safety caps, complete precedence proof, and all scoped consumers remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedEffectiveSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolver.java); [FiremudCommandCapabilitiesProperties.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/FiremudCommandCapabilitiesProperties.java); [platform settings publication](../../../config/settings/platform-settings-publication.json); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [platform operations](./platform-operations-and-delivery.md); [world runtime](./world-runtime-and-movement.md) | Partial: typed defaults, scopes, persisted overrides, and effective resolution exist, but selected presets, operator bootstrap/runtime layers, caps, and their precedence proof are not implemented. ADR 0012 is accepted and owns the target precedence and constraint contract. | | `AR-2.2` Feature, command, profile, and capability policy | `partial` | `proven` for command-capability resolution, feature-flag, published-command admission, and interpreter seams; complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [player command model](../../architecture/system-architecture-player-command-model.md); [feature flags](../../architecture/microservices/game-design-service/feature-flags.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0124](../../architecture/decisions/adr-0124-materialized-starter-profiles-with-conservative-draft-upgrades.md) | [EffectiveCommandCapabilitiesSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolver.java); [FeatureFlagServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/FeatureFlagServiceImpl.java); [AggregatingTextCommandRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistry.java); [AdmittedTextCommandRegistryResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java); [AggregatingTextCommandRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java); [AdmittedTextCommandRegistryResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolverTest.java); [TextCommandInterpreterCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java) | [player experience](./player-experience-commands-and-communication.md); [player access](./player-access-and-session.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: command capability resolution, feature flags, and published command admission exist, but the complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage are not implemented. ADR 0124 defines materialized starter-profile content and conservative Draft upgrades; implementation and focused proof remain incomplete. | @@ -431,9 +445,9 @@ Focused regression sources cover manifest refusal and retained failure/tuple cus ### Published Asset Lifecycle -Current source/evidence status: Game Design has durable `version_asset` mappings and a version-scoped export snapshot with independent readback. Normal export consumes the frozen snapshot and records candidate manifest/artifact digests before object writes. Published repair independently reads an immutable candidate and checks it against the exact release bundle before object writes; this composed exporter/candidate/repair implementation has local source and unit proof, while migration closure and physical database/object-store execution remain unproved. Retired-version handling and end-to-end version-scoped readiness also remain unproved. +Current source/evidence status: Game Design has durable `version_asset` mappings and a version-scoped export snapshot with independent readback. Normal export consumes the frozen snapshot and records candidate manifest/artifact digests before object writes. At receiving head `d935ecbcda59e643efcf040a43a0b2e8ef58d7ac`, the [focused asset publication test](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationMinioPostgresIntegrationTest.java) passed against Flyway-backed PostgreSQL and isolated, run-owned MinIO. The test observes the committed snapshot and candidate before the first object write, loses the write acknowledgement and first readback, and retries with reconstructed owner services. It verifies the exact stored asset and manifest, an unchanged candidate row version, and refusal to overwrite a conflicting object. The Version remains DRAFT. Published repair independently reads an immutable candidate and checks it against the exact release bundle before object writes. That repair composition has unit proof. Physical repair, migration closure, retired-version handling, and end-to-end version-scoped readiness remain unproved. -Lifecycle status/proof is also incomplete: artifact saves implement an epoch predicate and affected-row check, but physical database execution/concurrency proof is unavailable; Version saves still lack database CAS. Tombstone eligibility and failed-candidate abandonment are not fully implemented; post-bundle publish-failure reconciliation and durable ADR 0048 operation identity are absent. The canonical state, transition, purge, repair, and reachability rules remain owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow) and the [Asset Store Runbook](../../architecture/system-architecture-asset-store-runbook.md#removing-published-versions); this tracker records only implementation status and proof gaps. +At receiving head `1c756178acf55587cf1695f7785fbe5218fb65e3`, normal Game Design module validation requires the exact physical MinIO case with the repository's digest-pinned Compose image in a disposable fixture. Four focused cases passed with no failures or skips. PostgreSQL proved candidate write-failure rollback with unchanged row bytes and epoch, convergence under concurrent exact candidate retries, and refusal to overflow the artifact epoch. Version saves still lack database CAS. Tombstone eligibility and failed-candidate abandonment are not fully implemented; post-bundle publish-failure reconciliation and durable ADR 0048 operation identity are absent. The canonical state, transition, purge, repair, and reachability rules remain owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow) and the [Asset Store Runbook](../../architecture/system-architecture-asset-store-runbook.md#removing-published-versions); this tracker records only implementation status and proof gaps. ### Launch, Activation, Cutover, and Termination diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLogoutAllDraftSettlementPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLogoutAllDraftSettlementPostgresIntegrationTest.java new file mode 100644 index 0000000000..09c9a5f782 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLogoutAllDraftSettlementPostgresIntegrationTest.java @@ -0,0 +1,764 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.LocalDateTime; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Ordering; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.PasswordResetToken; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository.LogoutAllReceipt; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountLogoutAllAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountLogoutAllAuthorityEventProducer.LogoutAllResult; +import net.firedevops.firemud.accountservice.service.AccountLogoutAllDraftSourceChangeRepository; +import net.firedevops.firemud.accountservice.service.AccountLogoutAllDraftSourceChangeRepository.PendingIntentSnapshot; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class AccountLogoutAllDraftSettlementPostgresIntegrationTest { + private static final String SCHEMA_PREFIX = "logout_src"; + private static final String STREAM_PREFIX = "account:auth-authority:v1:account/"; + private static final String EVENT_ID_PREFIX = "account-logout-all-event-v1:"; + private static final String TOKEN_PROFILE = "control-ui"; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void commitsAccountGenerationFenceClosedEventCheckpointAndImmutableReceiptTogether() { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + UUID requestId = UUID.randomUUID(); + String tokenHash = digest("presented-token:" + requestId); + String requestDigest = logoutAllDigest(seed.accountUuid(), TOKEN_PROFILE, tokenHash); + + LogoutAllResult result = + commit(fixture, seed, requestId, requestDigest, tokenHash, seed.initialState()); + + ScopeState current = authority(fixture, seed); + LogoutAllReceipt receipt = logoutReceipt(fixture, requestId); + var event = + transaction( + fixture.transaction(), + () -> fixture.outbox().findEvent(streamKey(seed.accountUuid()), 1L).orElseThrow()); + var checkpoint = + transaction( + fixture.transaction(), + () -> fixture.outbox().readCheckpoint(streamKey(seed.accountUuid())).orElseThrow()); + var decoded = + AccountLogoutAllAuthorityEventV1Codec.verify( + new String(event.payload(), StandardCharsets.UTF_8)); + + assertThat(result).isEqualTo(LogoutAllResult.LOGOUT_ALL_COMMITTED); + assertThat(current.generation()).isEqualTo(2L); + assertThat(current.sourceVersion()).isEqualTo(2L); + assertThat(current.issuanceFence().value()).isEqualTo(2L); + assertThat(current.issuanceFence().sourceVersion()).isEqualTo(2L); + assertThat(receipt.accountId()).isEqualTo(seed.accountId()); + assertThat(receipt.accountUuid()).isEqualTo(seed.accountUuid()); + assertThat(receipt.requestId()).isEqualTo(requestId); + assertThat(receipt.requestDigestVersion()).isEqualTo(1); + assertThat(receipt.requestDigest()).isEqualTo(requestDigest); + assertThat(receipt.presentedTokenHash()).isEqualTo(tokenHash); + assertThat(receipt.tokenProfile()).isEqualTo(TOKEN_PROFILE); + assertThat(receipt.operationKind()).isEqualTo("ACCOUNT_LOGOUT_ALL"); + assertThat(receipt.lifecycleResult()).isEqualTo("LOGOUT_ALL_COMMITTED"); + assertThat(receipt.accountAuthorityGeneration()).isEqualTo(2L); + assertThat(receipt.accountSourceVersion()).isEqualTo(2L); + assertThat(receipt.issuanceFence()).isEqualTo(2L); + assertThat(receipt.issuanceFenceSourceVersion()).isEqualTo(2L); + assertThat(receipt.outboxSequence()).isEqualTo(1L); + assertThat(receipt.eventId()).isEqualTo(EVENT_ID_PREFIX + requestId); + assertThat(checkpoint.outboxSequence()).isEqualTo(receipt.outboxSequence()); + assertThat(checkpoint.sourceEventId()).isEqualTo(receipt.eventId()); + assertThat(checkpoint.sourceEventDigest()).isEqualTo(receipt.eventDigest()); + assertThat(decoded.requestId()).isEqualTo(requestId.toString()); + assertThat(decoded.accountId()).isEqualTo(seed.accountUuid().toString()); + assertThat(decoded.accountAuthorityGeneration()).isEqualTo("2"); + assertThat(decoded.sourceVersion()).isEqualTo("2"); + assertThat(new String(event.payload(), StandardCharsets.UTF_8)).doesNotContain(tokenHash); + assertThat(count(fixture, "account_logout_all_operation_receipts")).isEqualTo(1L); + assertThat(count(fixture, "account_authority_outbox_events")).isEqualTo(1L); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "UPDATE account_logout_all_operation_receipts " + + "SET request_digest = request_digest WHERE request_id = ?", + requestId)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "DELETE FROM account_logout_all_operation_receipts WHERE request_id = ?", + requestId)) + .isInstanceOf(DataAccessException.class); + assertThat(logoutReceipt(fixture, requestId)).isEqualTo(receipt); + } + + /** + * These cases connect real PostgreSQL Account source writes to the V57 fence tables. The Draft + * bindings and owner readbacks below are synthetic test evidence; they do not authenticate a real + * Draft operation or prove the absent Game Design/World owner readback producers. + */ + @Test + void revokeOrderWaitsForBothExactAbortsBeforeOneLogoutAdvanceAndNeverAdmitsDelayedCommit() { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + DraftAuthorizationFenceBinding binding = + syntheticDraftBinding(seed, seed.initialState(), 0L, null); + transaction( + fixture.transaction(), + () -> { + draftFences(fixture).reserve(binding); + return null; + }); + UUID requestId = UUID.randomUUID(); + String tokenHash = digest("revocation-wins-token:" + requestId); + String requestDigest = logoutAllDigest(seed.accountUuid(), TOKEN_PROFILE, tokenHash); + StoredState before = snapshot(fixture, seed); + + assertPending(fixture, seed, requestId, requestDigest, tokenHash, seed.initialState()); + PendingIntentSnapshot waiting = pendingIntent(fixture, requestId).orElseThrow(); + assertThat(waiting.status()).isEqualTo("WAITING"); + assertThat(waiting.expectedGeneration()).isEqualTo(1L); + assertThat(waiting.expectedSourceVersion()).isEqualTo(1L); + assertThat(waiting.expectedIssuanceFence()).isEqualTo(1L); + assertThat(waiting.expectedIssuanceFenceSourceVersion()).isEqualTo(1L); + assertThat(waiting.checkpointSequence()).isZero(); + SourceChange sourceChange = sourceChange(waiting); + assertThat(sourceChange.sources()).hasSize(1); + assertThat(sourceChange.sources().getFirst().kind()).isEqualTo(SourceKind.ACCOUNT); + assertThat(sourceChange.sources().getFirst().scopeId()) + .isEqualTo(seed.accountUuid().toString()); + assertThat( + transaction(fixture.transaction(), () -> draftFences(fixture).read(binding).ordering())) + .isEqualTo(Ordering.REVOKE_ORDER); + assertThatThrownBy( + () -> + transaction( + fixture.transaction(), () -> draftFences(fixture).claimCommitOrder(binding))) + .isInstanceOf(IllegalStateException.class); + + syntheticOwnerReadback( + fixture, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {31}); + assertPending(fixture, seed, requestId, requestDigest, tokenHash, seed.initialState()); + assertThat(snapshot(fixture, seed)).isEqualTo(before); + assertThat(pendingIntent(fixture, requestId).orElseThrow().sourceChangeBinding()) + .containsExactly(waiting.sourceChangeBinding()); + assertThat( + transaction(fixture.transaction(), () -> draftFences(fixture).readSettlement(binding))) + .isEqualTo(Settlement.PENDING); + + syntheticOwnerReadback( + fixture, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {32}); + assertThat( + transaction(fixture.transaction(), () -> draftFences(fixture).readSettlement(binding))) + .isEqualTo(Settlement.FAILED_NONPUBLICATION); + assertThat( + transaction( + fixture.transaction(), + () -> draftFences(fixture).sourceMutationPermitted(sourceChange))) + .isTrue(); + + assertThat(commit(fixture, seed, requestId, requestDigest, tokenHash, seed.initialState())) + .isEqualTo(LogoutAllResult.LOGOUT_ALL_COMMITTED); + assertThat(authority(fixture, seed).generation()).isEqualTo(2L); + assertThat(authority(fixture, seed).sourceVersion()).isEqualTo(2L); + assertThat(authority(fixture, seed).issuanceFence().value()).isEqualTo(2L); + assertThat(authority(fixture, seed).issuanceFence().sourceVersion()).isEqualTo(2L); + assertThat(logoutReceipt(fixture, requestId).outboxSequence()).isEqualTo(1L); + assertThat(event(fixture, seed, 1L).requestId()).isEqualTo(requestId.toString()); + assertThat(pendingIntent(fixture, requestId).orElseThrow().status()) + .isEqualTo("SOURCE_COMMITTED"); + assertThat( + transaction( + fixture.transaction(), + () -> draftFences(fixture).readSourceChange(sourceChange).status())) + .isEqualTo("SOURCE_COMMITTED"); + assertThatThrownBy( + () -> + transaction( + fixture.transaction(), () -> draftFences(fixture).claimCommitOrder(binding))) + .isInstanceOf(IllegalStateException.class); + assertThat(snapshot(fixture, seed).generation()).isEqualTo(2L); + assertThat(count(fixture, "account_authority_outbox_events")).isEqualTo(1L); + assertThat(count(fixture, "account_logout_all_operation_receipts")).isEqualTo(1L); + } + + @Test + void mixedCommitOrderHoldsLogoutAuthorityAndPreservesOriginalOwnerResult() { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + DraftAuthorizationFenceBinding binding = + syntheticDraftBinding(seed, seed.initialState(), 0L, null); + transaction( + fixture.transaction(), + () -> { + draftFences(fixture).reserve(binding); + draftFences(fixture).claimCommitOrder(binding); + return null; + }); + UUID requestId = UUID.randomUUID(); + String tokenHash = digest("commit-order-token:" + requestId); + String requestDigest = logoutAllDigest(seed.accountUuid(), TOKEN_PROFILE, tokenHash); + StoredState before = snapshot(fixture, seed); + + assertPending(fixture, seed, requestId, requestDigest, tokenHash, seed.initialState()); + PendingIntentSnapshot waiting = pendingIntent(fixture, requestId).orElseThrow(); + SourceChange sourceChange = sourceChange(waiting); + assertThat( + transaction(fixture.transaction(), () -> draftFences(fixture).read(binding).ordering())) + .isEqualTo(Ordering.COMMIT_ORDER); + + OwnerReadback expectedWorldReadback = + syntheticOwnerReadback(fixture, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {41}); + byte[] expectedWorldReadbackBytes = expectedWorldReadback.canonicalBytes(); + assertPending(fixture, seed, requestId, requestDigest, tokenHash, seed.initialState()); + assertThat(snapshot(fixture, seed)).isEqualTo(before); + assertThat( + transaction(fixture.transaction(), () -> draftFences(fixture).readSettlement(binding))) + .isEqualTo(Settlement.PENDING); + + syntheticOwnerReadback( + fixture, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {42}); + assertThat( + transaction(fixture.transaction(), () -> draftFences(fixture).readSettlement(binding))) + .isEqualTo(Settlement.PENDING); + var originalWorldResult = + transaction( + fixture.transaction(), + () -> draftFences(fixture).readOwnerResult(binding, Owner.WORLD)) + .orElseThrow(); + assertThat(originalWorldResult.outcome()).isEqualTo(Outcome.COMMITTED); + assertThat(originalWorldResult.readback()).containsExactly(expectedWorldReadbackBytes); + + assertPending(fixture, seed, requestId, requestDigest, tokenHash, seed.initialState()); + assertThat(snapshot(fixture, seed)).isEqualTo(before); + assertThat(pendingIntent(fixture, requestId).orElseThrow().status()).isEqualTo("WAITING"); + assertThat( + transaction( + fixture.transaction(), + () -> draftFences(fixture).readSourceChange(sourceChange).status())) + .isEqualTo("WAITING"); + var replayedWorldResult = + transaction( + fixture.transaction(), + () -> draftFences(fixture).readOwnerResult(binding, Owner.WORLD)) + .orElseThrow(); + assertThat(replayedWorldResult.outcome()).isEqualTo(originalWorldResult.outcome()); + assertThat(replayedWorldResult.readback()).containsExactly(expectedWorldReadbackBytes); + assertThat(replayedWorldResult.recordedAt()).isEqualTo(originalWorldResult.recordedAt()); + assertThat(count(fixture, "account_authority_outbox_events")).isZero(); + assertThat(count(fixture, "account_logout_all_operation_receipts")).isZero(); + } + + @Test + void pendingRetryKeepsOriginalCaptureAndConflictsOnlyOnChangedCallerBindings() { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + Seed otherAccount = seedAccount(fixture); + DraftAuthorizationFenceBinding binding = + syntheticDraftBinding(seed, seed.initialState(), 0L, null); + transaction( + fixture.transaction(), + () -> { + draftFences(fixture).reserve(binding); + return null; + }); + UUID requestId = UUID.randomUUID(); + String tokenHash = digest("original-pending-token:" + requestId); + String requestDigest = logoutAllDigest(seed.accountUuid(), TOKEN_PROFILE, tokenHash); + assertPending(fixture, seed, requestId, requestDigest, tokenHash, seed.initialState()); + PendingIntentSnapshot original = pendingIntent(fixture, requestId).orElseThrow(); + StoredState before = snapshot(fixture, seed); + ScopeState changedServerCounters = + new ScopeState( + seed.initialState().scope(), + 81L, + 82L, + new AccountAuthorityGenerationRepository.IssuanceFence(seed.accountUuid(), 83L, 84L)); + + assertPending(fixture, seed, requestId, requestDigest, tokenHash, changedServerCounters); + assertPendingIntentEquals(pendingIntent(fixture, requestId).orElseThrow(), original); + assertThat(snapshot(fixture, seed)).isEqualTo(before); + + assertThatThrownBy( + () -> + commit( + fixture, + seed, + requestId, + digest("changed-pending-caller-digest:" + requestId), + tokenHash, + seed.initialState())) + .isInstanceOf(AccountLogoutAllAuthorityEventProducer.OperationConflictException.class); + assertThatThrownBy( + () -> + commit( + fixture, + seed, + requestId, + logoutAllDigest(seed.accountUuid(), "player-bootstrap", tokenHash), + "player-bootstrap", + tokenHash, + seed.initialState())) + .isInstanceOf(AccountLogoutAllAuthorityEventProducer.OperationConflictException.class); + assertThatThrownBy( + () -> + commit( + fixture, + seed, + requestId, + requestDigest, + digest("changed-pending-token:" + requestId), + seed.initialState())) + .isInstanceOf(AccountLogoutAllAuthorityEventProducer.OperationConflictException.class); + assertThatThrownBy( + () -> + producer(fixture) + .commit( + requestId, + 1, + requestDigest, + TOKEN_PROFILE, + tokenHash, + account(fixture, otherAccount), + authority(fixture, otherAccount))) + .isInstanceOf(AccountLogoutAllAuthorityEventProducer.OperationConflictException.class); + assertThatThrownBy( + () -> + commit( + fixture, + seed, + UUID.randomUUID(), + logoutAllDigest(seed.accountUuid(), TOKEN_PROFILE, tokenHash), + tokenHash, + seed.initialState())) + .isInstanceOf(AccountLogoutAllAuthorityEventProducer.OperationConflictException.class); + + assertPendingIntentEquals(pendingIntent(fixture, requestId).orElseThrow(), original); + assertThat(snapshot(fixture, seed)).isEqualTo(before); + assertThat(count(fixture, "account_logout_all_operation_receipts")).isZero(); + assertThat(count(fixture, "account_authority_outbox_events")).isZero(); + } + + private DraftAuthorizationFenceRepository draftFences(Fixture fixture) { + return new DraftAuthorizationFenceRepository(fixture.transactionDsl()); + } + + private Optional pendingIntent(Fixture fixture, UUID requestId) { + return transaction( + fixture.transaction(), + () -> + new AccountLogoutAllDraftSourceChangeRepository(fixture.transactionDsl()) + .readPendingIntent(requestId)); + } + + private SourceChange sourceChange(PendingIntentSnapshot intent) { + return SourceChange.fromStored(intent.sourceChangeBinding()); + } + + private void assertPending( + Fixture fixture, + Seed seed, + UUID requestId, + String requestDigest, + String tokenHash, + ScopeState expectedState) { + assertThatThrownBy( + () -> commit(fixture, seed, requestId, requestDigest, tokenHash, expectedState)) + .isInstanceOf( + AccountLogoutAllDraftSourceChangeRepository.PendingSourceChangeException.class); + } + + private void assertPendingIntentEquals( + PendingIntentSnapshot actual, PendingIntentSnapshot expected) { + assertThat(actual.requestId()).isEqualTo(expected.requestId()); + assertThat(actual.sourceChangeId()).isEqualTo(expected.sourceChangeId()); + assertThat(actual.requestPayload()).containsExactly(expected.requestPayload()); + assertThat(actual.captureEvidence()).containsExactly(expected.captureEvidence()); + assertThat(actual.sourceEvidence()).containsExactly(expected.sourceEvidence()); + assertThat(actual.sourceChangeRequest()).containsExactly(expected.sourceChangeRequest()); + assertThat(actual.sourceChangeBinding()).containsExactly(expected.sourceChangeBinding()); + assertThat(actual.status()).isEqualTo(expected.status()); + assertThat(actual.expectedGeneration()).isEqualTo(expected.expectedGeneration()); + assertThat(actual.expectedSourceVersion()).isEqualTo(expected.expectedSourceVersion()); + assertThat(actual.expectedIssuanceFence()).isEqualTo(expected.expectedIssuanceFence()); + assertThat(actual.expectedIssuanceFenceSourceVersion()) + .isEqualTo(expected.expectedIssuanceFenceSourceVersion()); + assertThat(actual.checkpointSequence()).isEqualTo(expected.checkpointSequence()); + } + + private DraftAuthorizationFenceBinding syntheticDraftBinding( + Seed seed, ScopeState sourceState, long checkpointSequence, byte[] sourceEvidence) { + byte[] evidence = + sourceEvidence == null + ? "synthetic-authenticated-owner-source-readback".getBytes(StandardCharsets.UTF_8) + : sourceEvidence.clone(); + SourceEvidence accountSource = + new SourceEvidence( + SourceKind.ACCOUNT, + seed.accountUuid().toString(), + Long.toString(sourceState.generation()), + Long.toString(sourceState.sourceVersion()), + streamKey(seed.accountUuid()), + Long.toString(checkpointSequence), + evidence); + UUID tenantId = UUID.randomUUID(); + UUID versionId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID commitId = UUID.randomUUID(); + DraftCommitBinding complete = + DraftCommitBinding.create( + new TargetProof(tenantId, versionId, 1, "tenant-key", 2, "tenant-key", "NEW_GAME_ROW"), + requestId, + commitId, + "logout-all-draft-base:" + UUID.randomUUID(), + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "synthetic complete Draft owner payload")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "region-1", + "aggregate", + "region-1", + "9007199254740999"))); + byte[] completeBytes = complete.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + seed.accountUuid(), + complete.target().canonicalTenantId(), + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "1", + completeBytes, + completeBytes, + complete.digest(), + List.of(accountSource)); + } + + private OwnerReadback syntheticOwnerReadback( + Fixture fixture, + DraftAuthorizationFenceBinding binding, + Owner owner, + Outcome outcome, + byte[] result) { + OwnerReadback readback = + new OwnerReadback( + owner, + outcome, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + result); + transaction( + fixture.transaction(), + () -> { + draftFences(fixture).recordOwnerReadback(binding, readback); + return null; + }); + return readback; + } + + private Fixture newFixture() { + return newFixtureAtVersion(null); + } + + private Fixture newFixtureAtVersion(String targetVersion) { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; + dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + var flywayConfiguration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (targetVersion != null) { + flywayConfiguration.target(MigrationVersion.fromVersion(targetVersion)); + } + flywayConfiguration.load().migrate(); + + DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + PlatformTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + AccountRepository accounts = new AccountRepository(transactionDsl); + AccountAuthorityGenerationRepository authority = + new AccountAuthorityGenerationRepository(transactionDsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(transactionDsl); + AccountPasswordResetOperationRepository passwordResetOperations = + new AccountPasswordResetOperationRepository(transactionDsl); + AccountLogoutAllOperationRepository logoutOperations = + new AccountLogoutAllOperationRepository(transactionDsl); + PasswordResetTokenRepository tokens = new PasswordResetTokenRepository(transactionDsl); + return new Fixture( + schema, + dataSource, + setupDsl, + transactionDsl, + transactionManager, + transaction, + accounts, + authority, + outbox, + passwordResetOperations, + logoutOperations, + tokens); + } + + private Seed seedAccount(Fixture fixture) { + return transaction( + fixture.transaction(), + () -> { + Account account = new Account(); + String unique = UUID.randomUUID().toString(); + account.setUsername("logout-all-" + unique); + account.setEmail("logout-all-" + unique + "@example.test"); + account.setPasswordHash("initial-verifier"); + Account saved = fixture.accounts().save(account); + // Fresh repository insertion atomically establishes exact Account and issuer baselines. + // Reads verify that evidence; generic initialization cannot enroll or repair a source. + ScopeState initialState = + fixture.authority().read(AuthorityScope.account(saved.getAccountUuid())); + assertThat( + new net.firedevops.firemud.accountservice.repository + .AccountAuthoritySourceEvidenceRepository( + fixture.transactionDsl(), fixture.authority(), fixture.outbox()) + .readCurrentAccountSource(saved.getAccountUuid(), initialState)) + .isNotNull(); + PasswordResetToken token = new PasswordResetToken(); + String rawToken = "reset-token-" + unique; + LocalDateTime deadline = LocalDateTime.now().plusHours(2); + token.setAccount(saved); + token.setToken(rawToken); + token.setExpiresAt(deadline); + fixture.tokens().save(token); + return new Seed(saved.getId(), saved.getAccountUuid(), rawToken, initialState); + }); + } + + private LogoutAllResult commit( + Fixture fixture, + Seed seed, + UUID requestId, + String requestDigest, + String tokenHash, + ScopeState expected) { + return commit(fixture, seed, requestId, requestDigest, TOKEN_PROFILE, tokenHash, expected); + } + + private LogoutAllResult commit( + Fixture fixture, + Seed seed, + UUID requestId, + String requestDigest, + String tokenProfile, + String tokenHash, + ScopeState expected) { + return producer(fixture) + .commit( + requestId, 1, requestDigest, tokenProfile, tokenHash, account(fixture, seed), expected); + } + + private AccountLogoutAllAuthorityEventProducer producer(Fixture fixture) { + return producer(fixture, fixture.accounts()); + } + + private AccountLogoutAllAuthorityEventProducer producer( + Fixture fixture, AccountRepository accounts) { + return new AccountLogoutAllAuthorityEventProducer( + accounts, + fixture.authority(), + new net.firedevops.firemud.accountservice.repository + .AccountAuthoritySourceEvidenceRepository( + fixture.transactionDsl(), fixture.authority(), fixture.outbox()), + fixture.outbox(), + fixture.logoutOperations(), + sourceReadback(fixture, fixture.outbox()), + fixture.transactionDsl(), + fixture.transactionManager()); + } + + private AccountAuthoritySourceEventReadback sourceReadback( + Fixture fixture, AccountAuthorityOutboxRepository outbox) { + return new AccountAuthoritySourceEventReadback( + outbox, + fixture.passwordResetOperations(), + fixture.logoutOperations(), + new net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository(fixture.transactionDsl())); + } + + private Account account(Fixture fixture, Seed seed) { + return transaction( + fixture.transaction(), () -> fixture.accounts().findById(seed.accountId()).orElseThrow()); + } + + private ScopeState authority(Fixture fixture, Seed seed) { + return transaction( + fixture.transaction(), + () -> fixture.authority().read(AuthorityScope.account(seed.accountUuid()))); + } + + private LogoutAllReceipt logoutReceipt(Fixture fixture, UUID requestId) { + return transaction( + fixture.transaction(), + () -> fixture.logoutOperations().findByRequestId(requestId).orElseThrow()); + } + + private AccountAuthorityOutboxRepository.Event event( + Fixture fixture, Seed seed, long outboxSequence) { + return transaction( + fixture.transaction(), + () -> + fixture + .outbox() + .findEvent(streamKey(seed.accountUuid()), outboxSequence) + .orElseThrow()); + } + + private StoredState snapshot(Fixture fixture, Seed seed) { + ScopeState state = authority(fixture, seed); + return new StoredState( + state.generation(), + state.sourceVersion(), + state.issuanceFence().value(), + state.issuanceFence().sourceVersion(), + count(fixture, "accounts"), + count(fixture, "account_authority_generations"), + count(fixture, "account_authority_issuance_fences"), + count(fixture, "password_reset_token"), + count(fixture, "account_logout_all_operation_receipts"), + count(fixture, "account_password_reset_operation_receipts"), + count(fixture, "account_authority_outbox_events"), + count(fixture, "account_authority_outbox_streams")); + } + + private long count(Fixture fixture, String table) { + return Objects.requireNonNull( + fixture.setupDsl().resultQuery("SELECT COUNT(*) FROM " + table).fetchOne(0, Long.class), + "Logout-all source row count is missing"); + } + + private String streamKey(UUID accountUuid) { + return STREAM_PREFIX + accountUuid; + } + + private String digest(String value) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private String logoutAllDigest(UUID accountUuid, String tokenProfile, String tokenHash) { + return AccountLogoutRequestDigest.accountLogoutAll(accountUuid, tokenProfile, tokenHash); + } + + private T transaction(TransactionTemplate transaction, Supplier operation) { + return transaction.execute(status -> operation.get()); + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext setupDsl, + DSLContext transactionDsl, + PlatformTransactionManager transactionManager, + TransactionTemplate transaction, + AccountRepository accounts, + AccountAuthorityGenerationRepository authority, + AccountAuthorityOutboxRepository outbox, + AccountPasswordResetOperationRepository passwordResetOperations, + AccountLogoutAllOperationRepository logoutOperations, + PasswordResetTokenRepository tokens) {} + + private record Seed(long accountId, UUID accountUuid, String rawToken, ScopeState initialState) {} + + private record StoredState( + long generation, + long sourceVersion, + long issuanceFence, + long issuanceFenceSourceVersion, + long accountRowCount, + long generationRowCount, + long issuanceFenceRowCount, + long passwordResetTokenCount, + long logoutReceiptCount, + long passwordResetReceiptCount, + long eventCount, + long streamCount) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java index dc1ac6d1a4..25f085b82a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java @@ -382,6 +382,93 @@ void concurrentExactRetriesCommitOneSourceMutation() throws Exception { assertThat(state.eventCount()).isEqualTo(1L); } + @Test + void mixedOwnerOutcomesKeepExactResetPendingWithoutCredentialOrAuthorityMutation() { + for (Outcome worldOutcome : List.of(Outcome.COMMITTED, Outcome.DEFINITIVELY_ABORTED)) { + Fixture fixture = newFixture(); + Seed seed = seedAccountAndToken(fixture, "initial-password"); + DraftAuthorizationFenceBinding binding = draftBinding(seed); + transaction( + fixture.transaction(), + () -> { + fixture.fences().reserve(binding); + fixture.fences().claimCommitOrder(binding); + return null; + }); + StoredState before = snapshot(fixture, seed); + assertThatThrownBy(() -> reset(fixture, seed.rawToken(), "waiting-password")) + .isInstanceOf( + AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class); + var original = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT request_payload, source_change_binding, password_verifier, password_verifier_digest " + + "FROM account_password_reset_draft_source_changes WHERE token_hash = ?", + HexFormat.of().parseHex(tokenHash(seed.rawToken())))); + Outcome designOutcome = + worldOutcome == Outcome.COMMITTED ? Outcome.DEFINITIVELY_ABORTED : Outcome.COMMITTED; + transaction( + fixture.transaction(), + () -> { + for (Owner owner : binding.requiredOwners()) { + fixture + .fences() + .recordOwnerReadback( + binding, + new OwnerReadback( + owner, + owner == Owner.WORLD ? worldOutcome : designOutcome, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + new byte[] {7})); + } + return null; + }); + assertThatThrownBy(() -> reset(fixture, seed.rawToken(), "waiting-password")) + .isInstanceOf( + AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class); + assertThat(snapshot(fixture, seed)).isEqualTo(before); + assertThat(transaction(fixture.transaction(), () -> fixture.fences().readSettlement(binding))) + .isEqualTo(DraftAuthorizationFenceRepository.Settlement.PENDING); + var retained = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT status, request_payload, source_change_binding, password_verifier, password_verifier_digest " + + "FROM account_password_reset_draft_source_changes WHERE token_hash = ?", + HexFormat.of().parseHex(tokenHash(seed.rawToken())))); + assertThat(retained.get("status", String.class)).isEqualTo("WAITING"); + assertThat(retained.get("password_verifier", String.class)) + .isEqualTo(original.get("password_verifier", String.class)); + for (String column : + List.of("request_payload", "source_change_binding", "password_verifier_digest")) { + assertThat(retained.get(column, byte[].class)) + .containsExactly(original.get(column, byte[].class)); + } + transaction( + fixture.transaction(), + () -> { + assertThat( + fixture.fences().readOwnerResult(binding, Owner.WORLD).orElseThrow().outcome()) + .isEqualTo(worldOutcome); + assertThat( + fixture + .fences() + .readOwnerResult(binding, Owner.GAME_DESIGN) + .orElseThrow() + .outcome()) + .isEqualTo(designOutcome); + return null; + }); + } + } + @Test void waitingResetRetainsExactIntentAndSettlesOnlyAfterOriginalOwnersDeny() { Fixture fixture = newFixture(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java index f9a9064e04..366fcc41e8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java @@ -457,51 +457,56 @@ void commitOrderWithBothDefinitiveAbortsReleasesOriginalWaitingIntentWithoutReop @Test void bothMixedDirectionsRemainPendingAndPreserveOriginalReadbacks() { - for (Outcome worldOutcome : List.of(Outcome.COMMITTED, Outcome.DEFINITIVELY_ABORTED)) { - Context context = context(); - DraftAuthorizationFenceBinding binding = binding(context); - tx(context, () -> context.repository().reserve(binding)); - var ordered = tx(context, () -> context.repository().claimCommitOrder(binding)); - SourceChange change = change(binding); - assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); - var waiting = tx(context, () -> context.repository().readSourceChange(change)); - owner(context, binding, Owner.WORLD, worldOutcome, new byte[] {1}); - var originalWorld = - tx(context, () -> context.repository().readOwnerResult(binding, Owner.WORLD)) - .orElseThrow(); - assertThat(tx(context, () -> context.repository().readSettlement(binding))) - .isEqualTo(Settlement.PENDING); - assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); - assertSourceGuardBlocked(context, change); - Outcome gameDesignOutcome = - worldOutcome == Outcome.COMMITTED ? Outcome.DEFINITIVELY_ABORTED : Outcome.COMMITTED; - owner(context, binding, Owner.GAME_DESIGN, gameDesignOutcome, new byte[] {2}); - assertThat(tx(context, () -> context.repository().readSettlement(binding))) - .isEqualTo(Settlement.PENDING); - assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); - assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); - assertThat(tx(context, () -> context.repository().sourceAbortPermitted(change))).isFalse(); - assertSourceGuardBlocked(context, change); - var held = tx(context, () -> context.repository().readSourceChange(change)); - assertThat(held.status()).isEqualTo("WAITING"); - assertThat(held.binding()).containsExactly(waiting.binding()); - assertThat(held.requestedAt()).isEqualTo(waiting.requestedAt()); - assertThat(tx(context, () -> context.repository().read(binding)).ordering()) - .isEqualTo(Ordering.COMMIT_ORDER); - assertThat(tx(context, () -> context.repository().read(binding)).orderedAt()) - .isEqualTo(ordered.orderedAt()); - owner(context, binding, Owner.WORLD, worldOutcome, new byte[] {1}); - var replay = - tx(context, () -> context.repository().readOwnerResult(binding, Owner.WORLD)) - .orElseThrow(); - assertThat(replay.outcome()).isEqualTo(originalWorld.outcome()); - assertThat(replay.readback()).containsExactly(originalWorld.readback()); - assertThat(replay.recordedAt()).isEqualTo(originalWorld.recordedAt()); - assertThatThrownBy(() -> owner(context, binding, Owner.WORLD, worldOutcome, new byte[] {9})) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> owner(context, binding, Owner.WORLD, gameDesignOutcome, new byte[] {1})) - .isInstanceOf(IllegalArgumentException.class); + for (SourceKind sourceKind : + List.of(SourceKind.ACCOUNT, SourceKind.ISSUER, SourceKind.TENANT, SourceKind.MEMBERSHIP)) { + for (Outcome worldOutcome : List.of(Outcome.COMMITTED, Outcome.DEFINITIVELY_ABORTED)) { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context, sourceKind); + tx(context, () -> context.repository().reserve(binding)); + var ordered = tx(context, () -> context.repository().claimCommitOrder(binding)); + SourceChange change = change(binding); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + var waiting = tx(context, () -> context.repository().readSourceChange(change)); + owner(context, binding, Owner.WORLD, worldOutcome, new byte[] {1}); + var originalWorld = + tx(context, () -> context.repository().readOwnerResult(binding, Owner.WORLD)) + .orElseThrow(); + assertThat(tx(context, () -> context.repository().readSettlement(binding))) + .isEqualTo(Settlement.PENDING); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))) + .isFalse(); + assertSourceGuardBlocked(context, change); + Outcome gameDesignOutcome = + worldOutcome == Outcome.COMMITTED ? Outcome.DEFINITIVELY_ABORTED : Outcome.COMMITTED; + owner(context, binding, Owner.GAME_DESIGN, gameDesignOutcome, new byte[] {2}); + assertThat(tx(context, () -> context.repository().readSettlement(binding))) + .isEqualTo(Settlement.PENDING); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))) + .isFalse(); + assertThat(tx(context, () -> context.repository().sourceAbortPermitted(change))).isFalse(); + assertSourceGuardBlocked(context, change); + var held = tx(context, () -> context.repository().readSourceChange(change)); + assertThat(held.status()).isEqualTo("WAITING"); + assertThat(held.binding()).containsExactly(waiting.binding()); + assertThat(held.requestedAt()).isEqualTo(waiting.requestedAt()); + assertThat(tx(context, () -> context.repository().read(binding)).ordering()) + .isEqualTo(Ordering.COMMIT_ORDER); + assertThat(tx(context, () -> context.repository().read(binding)).orderedAt()) + .isEqualTo(ordered.orderedAt()); + owner(context, binding, Owner.WORLD, worldOutcome, new byte[] {1}); + var replay = + tx(context, () -> context.repository().readOwnerResult(binding, Owner.WORLD)) + .orElseThrow(); + assertThat(replay.outcome()).isEqualTo(originalWorld.outcome()); + assertThat(replay.readback()).containsExactly(originalWorld.readback()); + assertThat(replay.recordedAt()).isEqualTo(originalWorld.recordedAt()); + assertThatThrownBy(() -> owner(context, binding, Owner.WORLD, worldOutcome, new byte[] {9})) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> owner(context, binding, Owner.WORLD, gameDesignOutcome, new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class); + } } } @@ -1288,6 +1293,10 @@ private Context context(String target) { } private DraftAuthorizationFenceBinding binding(Context context) { + return binding(context, SourceKind.ACCOUNT); + } + + private DraftAuthorizationFenceBinding binding(Context context, SourceKind sourceKind) { // Database-owned UUID/provenance satisfies the current Account-before-source lock. // The captured source epochs and authenticated owner evidence remain fixture stipulations. UUID suffix = UUID.randomUUID(); @@ -1308,15 +1317,6 @@ private DraftAuthorizationFenceBinding binding(Context context) { .isEqualTo(row.get("id", Long.class)); assertThat(row.get("account_uuid_provenance", String.class)) .isEqualTo("ACCOUNT_DATABASE_INSERT"); - SourceEvidence source = - new SourceEvidence( - SourceKind.ACCOUNT, - account.toString(), - "3", - "5", - "stream/" + account, - "2", - new byte[] {7}); DraftCommitBinding complete = completeBinding( UUID.randomUUID(), @@ -1326,6 +1326,15 @@ private DraftAuthorizationFenceBinding binding(Context context) { "opaque/base:9007199254740993", "world-payload", UUID.randomUUID()); + String tenant = complete.target().canonicalTenantId().toString(); + String scopeId = + switch (sourceKind) { + case MEMBERSHIP -> account + "/" + tenant; + case TENANT -> tenant; + default -> account.toString(); + }; + SourceEvidence source = + new SourceEvidence(sourceKind, scopeId, "3", "5", "stream/" + account, "2", new byte[] {7}); return new DraftAuthorizationFenceBinding( UUID.randomUUID(), complete.requestId(), diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyPostgresIntegrationTest.java new file mode 100644 index 0000000000..c3fa68e47c --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyPostgresIntegrationTest.java @@ -0,0 +1,389 @@ +package integration.net.firedevops.firemud.accountservice.creatorparty; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository.AssociationConflictException; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource.VerificationStatus; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +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.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Physical proof for exact fresh creator-party receipts and canonical tenant serialization. */ +@Testcontainers(disabledWithoutDocker = true) +class IndividualCreatorPartyPostgresIntegrationTest { + private static final String NAMESPACE = "creator-party-proof"; + private static final String DIGEST = "sha256:" + "1".repeat(64); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void committedAssociationHasExactIndependentReadbackAndReplay() throws Exception { + Fixture fixture = fixture(); + UUID request = UUID.randomUUID(); + + var committed = + tx( + fixture.db(), + () -> fixture.owner().associateFresh(request, fixture.creator(), fixture.party())); + byte[] originalReceipt = + Objects.requireNonNull( + fixture + .db() + .dsl() + .fetchOne( + "SELECT result_payload FROM account_fresh_creator_party_association_operations " + + "WHERE request_id = ?", + request)) + .get("result_payload", byte[].class); + assertThat( + tx( + fixture.db(), + () -> + fixture + .owner() + .readInitialAssociation(request, fixture.creator(), fixture.party()))) + .isEqualTo(committed); + assertThat( + tx( + fixture.db(), + () -> fixture.owner().associateFresh(request, fixture.creator(), fixture.party()))) + .isEqualTo(committed); + assertThat( + Objects.requireNonNull( + fixture + .db() + .dsl() + .fetchOne( + "SELECT result_payload FROM account_fresh_creator_party_association_operations " + + "WHERE request_id = ?", + request)) + .get("result_payload", byte[].class)) + .containsExactly(originalReceipt); + assertThat(count(fixture.db(), "account_tenant_creator_party_history")).isEqualTo(1); + assertThat(count(fixture.db(), "account_fresh_creator_party_association_operations")) + .isEqualTo(1); + } + + @Test + void retainedHistoryCommitsBeforeWaitingFreshAssociationAndExcludesIt() throws Exception { + Fixture fixture = fixture(); + CountDownLatch retainedLocked = new CountDownLatch(1); + CountDownLatch releaseRetained = new CountDownLatch(1); + CountDownLatch freshStarted = new CountDownLatch(1); + AtomicInteger retainedPid = new AtomicInteger(); + AtomicInteger freshPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future retained = + executor.submit( + () -> + tx( + fixture.db(), + () -> { + insertRetainedHistory(fixture); + retainedPid.set(backendPid(fixture.db())); + retainedLocked.countDown(); + await(releaseRetained); + return null; + })); + assertThat(retainedLocked.await(10, TimeUnit.SECONDS)).isTrue(); + + Future fresh = + executor.submit( + () -> + tx( + fixture.db(), + () -> { + freshPid.set(backendPid(fixture.db())); + freshStarted.countDown(); + return fixture + .owner() + .associateFresh(UUID.randomUUID(), fixture.creator(), fixture.party()); + })); + assertThat(freshStarted.await(10, TimeUnit.SECONDS)).isTrue(); + assertDatabaseLockWait(fixture.db(), freshPid.get(), retainedPid.get()); + + releaseRetained.countDown(); + retained.get(10, TimeUnit.SECONDS); + assertThatThrownBy(() -> fresh.get(10, TimeUnit.SECONDS)) + .hasCauseInstanceOf(AssociationConflictException.class); + assertThat(count(fixture.db(), "account_tenant_creator_party_history")).isEqualTo(1); + assertThat(count(fixture.db(), "account_fresh_creator_party_association_operations")) + .isZero(); + } finally { + releaseRetained.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + } + + private static Fixture fixture() throws Exception { + Database db = database(); + UUID account = insertAccount(db); + UUID request = UUID.randomUUID(); + UUID operation = UUID.randomUUID(); + UUID tenant = UUID.randomUUID(); + String tenantKey = "party-game"; + String creationDigest = + GameTenantCreationDigest.requestDigest(NAMESPACE, request, tenantKey, "fixture", null); + FreshTenantCreationEvidence creation = + new FreshTenantCreationEvidence( + 1, + NAMESPACE, + request, + operation, + creationDigest, + tenant, + 1, + tenantKey, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, + request, + operation, + creationDigest, + tenant, + 1, + tenantKey, + "NEW_GAME_ROW")); + FreshTenantCreatorEvidence creator = qualification(creation, account, UUID.randomUUID()); + FreshTenantIdentityAssociationRepository freshTenants = + new FreshTenantIdentityAssociationRepository(db.dsl(), NAMESPACE); + tx( + db, + () -> { + freshTenants.importVerified(creation); + insertCommittedBootstrapFixture(db, creator); + return null; + }); + + IndividualCreatorPartySource party = party(account); + byte[] partyPayload = CreatorPartyEncoding.party(party); + db.dsl() + .execute( + "INSERT INTO account_individual_creator_party_sources " + + "(creator_party_id, account_uuid, verification_status, identity_version, " + + "policy_reference, policy_version, verification_evidence_reference, " + + "verification_evidence_version, source_version, source_payload, source_digest) " + + "VALUES (?, ?, 'VERIFIED', 1, ?, 1, ?, 1, 1, ?, ?)", + party.creatorPartyId(), + party.accountId(), + party.policyReference(), + party.verificationEvidenceReference(), + partyPayload, + CreatorPartyEncoding.digest(partyPayload)); + return new Fixture( + db, + creator, + party, + new IndividualCreatorPartyRepository( + db.dsl(), + freshTenants, + new AccountTenantCreationBootstrapOperationRepository(db.dsl()))); + } + + private static FreshTenantCreatorEvidence qualification( + FreshTenantCreationEvidence creation, UUID account, UUID authorization) { + return new FreshTenantCreatorEvidence( + 1, + creation, + account, + authorization, + DIGEST, + FreshTenantCreatorDigest.evidenceDigest(1, creation, account, authorization, DIGEST)); + } + + private static IndividualCreatorPartySource party(UUID account) { + return new IndividualCreatorPartySource( + UUID.randomUUID(), + account, + VerificationStatus.VERIFIED, + 1, + "fixture-approved-policy", + 1L, + "fixture-verification-evidence", + 1L, + 1); + } + + private static void insertCommittedBootstrapFixture( + Database db, FreshTenantCreatorEvidence creator) { + var creation = creator.creationEvidence(); + UUID authorization = creator.accountAuthorizationOperationId(); + db.dsl() + .execute( + "INSERT INTO account_tenant_creation_bootstrap_operations " + + "(request_id, schema_version, initiating_account_uuid, tenant_uuid, " + + "creation_request_id, creation_operation_id, account_authorization_operation_id, " + + "account_authorization_digest, creator_evidence_digest, creator_evidence_payload, " + + "source_snapshot_payload, source_snapshot_digest, request_payload, request_digest, " + + "baseline_membership_version, baseline_membership_authority_generation, " + + "baseline_event_sequence, status) " + + "VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1, 0, 'IN_PROGRESS')", + authorization, + creator.initiatingAccountId(), + creation.canonicalTenantId(), + creation.creationRequestId(), + creation.operationId(), + authorization, + DIGEST, + creator.evidenceDigest(), + CreatorPartyEncoding.creation(creator), + new byte[] {1}, + DIGEST, + new byte[] {1}, + DIGEST); + db.dsl() + .execute( + "UPDATE account_tenant_creation_bootstrap_operations SET membership_id = 1, " + + "membership_version = 2, membership_authority_generation = 1, " + + "membership_lifecycle_state = 'ACTIVE', gameplay_admission_allowed = FALSE, " + + "membership_roles_payload = convert_to('[\"tenantAdmin\"]', 'UTF8'), " + + "event_stream_key = ?, event_request_id = ?, event_sequence = 1, " + + "event_id = 'fixture-event', event_digest = ?, event_payload = ?, " + + "caller_bound_authority_invalidated = FALSE, audit_event_id = ?, " + + "audit_event_type = 'ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED', " + + "audit_occurred_at = CURRENT_TIMESTAMP, audit_payload_digest = ?, " + + "audit_payload = ?, result_payload = ?, result_digest = ?, status = 'COMMITTED' " + + "WHERE request_id = ?", + "account:auth-authority:v1:membership/" + + creator.initiatingAccountId() + + "/" + + creation.canonicalTenantId(), + authorization.toString(), + DIGEST, + new byte[] {1}, + UUID.randomUUID(), + DIGEST, + new byte[] {1}, + new byte[] {1}, + DIGEST, + authorization); + } + + private static void insertRetainedHistory(Fixture fixture) { + fixture + .db() + .dsl() + .execute( + "INSERT INTO account_tenant_creator_party_history " + + "(history_id, tenant_uuid, origin, source_version, evidence_payload, evidence_digest) " + + "VALUES (?, ?, 'RETAINED', 1, ?, ?)", + UUID.randomUUID(), + fixture.creator().creationEvidence().canonicalTenantId(), + new byte[] {1}, + DIGEST); + } + + private static UUID insertAccount(Database db) { + UUID account = UUID.randomUUID(); + db.dsl() + .execute( + "INSERT INTO accounts (account_uuid, username, email, password_hash) " + + "VALUES (?, ?, ?, 'fixture-hash')", + account, + "party-" + account.toString().substring(0, 8), + account + "@example.com"); + return account; + } + + private static Database database() { + String schema = "creator_party_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + return new Database( + DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES), + new TransactionTemplate(new DataSourceTransactionManager(source))); + } + + private static int backendPid(Database db) { + return Objects.requireNonNull( + Objects.requireNonNull(db.dsl().fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)) + .intValue(); + } + + private static long count(Database db, String table) { + return Objects.requireNonNull( + Objects.requireNonNull(db.dsl().fetchOne("SELECT count(*) AS count FROM " + table)) + .get("count", Long.class)); + } + + private static T tx(Database db, Supplier work) { + return db.transactions().execute(status -> work.get()); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Database interleaving was not released"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Database interleaving was interrupted", exception); + } + } + + private static void assertDatabaseLockWait(Database db, int pid, int blocker) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadline) { + var waiting = db.dsl().fetchSingle("SELECT ? = ANY(pg_blocking_pids(?))", blocker, pid); + if (Boolean.TRUE.equals(waiting.get(0, Boolean.class))) { + return; + } + Thread.sleep(25); + } + throw new AssertionError("Second connection did not wait on canonical tenant owner row"); + } + + private record Database(DSLContext dsl, TransactionTemplate transactions) {} + + private record Fixture( + Database db, + FreshTenantCreatorEvidence creator, + IndividualCreatorPartySource party, + IndividualCreatorPartyRepository owner) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCreatorControlCapturePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCreatorControlCapturePostgresIntegrationTest.java new file mode 100644 index 0000000000..c789f920fc --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCreatorControlCapturePostgresIntegrationTest.java @@ -0,0 +1,380 @@ +package integration.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository.InitialAssociationReadback; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource.VerificationStatus; +import net.firedevops.firemud.accountservice.dto.AccountTenantCreationBootstrapResult; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountCreatorMembershipSourceReader; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.CreatorControlCaptureSources; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxSourceEvidence; +import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapAuthorizationSource; +import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapService; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +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.beans.factory.support.StaticListableBeanFactory; +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; + +/** Exercises the owner-verified creator-control capture against committed Account storage. */ +@Testcontainers(disabledWithoutDocker = true) +class AccountCreatorControlCapturePostgresIntegrationTest { + private static final String NAMESPACE = "creator-control-capture-proof"; + private static final String ISSUER = "firemud-account-service"; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void capturesExactCommittedCreatorSourcesAndRequiresAnAccessibleOriginalReceipt() { + UUID bootstrapRequestId = UUID.randomUUID(); + var fixture = new Fixture(bootstrapRequestId); + FreshTenantCreationEvidence creation = tenantCreation(); + UUID tenantId = creation.canonicalTenantId(); + UUID accountId = fixture.account.getAccountUuid(); + String authorizationDigest = "sha256:" + "a".repeat(64); + var creator = + new FreshTenantCreatorEvidence( + 1, + creation, + accountId, + bootstrapRequestId, + authorizationDigest, + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, accountId, bootstrapRequestId, authorizationDigest)); + var party = + new IndividualCreatorPartySource( + UUID.randomUUID(), + accountId, + VerificationStatus.VERIFIED, + 1L, + "fixture-policy", + 1L, + "fixture-verification", + 1L, + 1L); + UUID partyRequestId = UUID.randomUUID(); + + var committed = + Objects.requireNonNull( + fixture.transaction.execute( + ignored -> { + fixture.tenants.importVerified(creation); + fixture.generations.initializeTenantIfAbsent(tenantId); + var bootstrap = fixture.bootstrap.bootstrap(creator); + fixture.insertControlledIndividualSource(party); + var resolved = + fixture.parties.readIndividualSource(party.creatorPartyId(), accountId); + var association = + fixture.parties.associateFresh(partyRequestId, creator, resolved); + return new CommittedSources( + bootstrap, new InitialAssociationReadback(creator, association, party)); + })); + + var first = fixture.capture(fixture.bootstrap, tenantId); + assertThat(first.party()).isEqualTo(committed.party()); + assertExactSources(first.creator(), committed.bootstrap(), fixture.account, creation); + + assertThatThrownBy(() -> fixture.capture(fixture.bootstrapWithUnavailableReceipt, tenantId)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Committed creator-bootstrap receipt is absent"); + + var recovered = fixture.capture(fixture.bootstrap, tenantId); + assertThat(recovered) + .usingRecursiveComparison() + .ignoringFields("creator.evaluatedAt") + .isEqualTo(first); + } + + private static void assertExactSources( + CreatorControlCaptureSources captured, + AccountTenantCreationBootstrapResult committed, + Account account, + FreshTenantCreationEvidence creation) { + UUID accountId = account.getAccountUuid(); + UUID tenantId = creation.canonicalTenantId(); + String prefix = MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX; + String stream = prefix + "membership/" + accountId + "/" + tenantId; + Map generation = Map.of(tenantId.toString(), "1"); + Map version = Map.of(tenantId.toString(), "2"); + var provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + creation.operationId(), + creation.evidenceDigest()); + var receipt = captured.bootstrapReceipt(); + var event = captured.sourceEvent(); + + assertThat(captured.accountUuid()).isEqualTo(accountId); + assertThat(captured.tenantUuid()).isEqualTo(tenantId); + assertThat(captured.creationSource()).isEqualTo(creation); + assertThat(captured.membershipVersion()).isEqualTo(version); + assertThat(captured.authorityTuple()) + .isEqualTo( + new AuthorityTuple( + "1", "1", generation, generation, List.of(), Optional.empty(), Optional.empty())); + assertThat(receipt.status()).isEqualTo("COMMITTED"); + assertThat(receipt.result()).isEqualTo(committed); + assertThat(receipt.creationOperationId()).isEqualTo(creation.operationId()); + assertThat(receipt.creationRequestId()).isEqualTo(creation.creationRequestId()); + assertThat(receipt.membershipRolesPayload()) + .containsExactly("[\"tenantAdmin\"]".getBytes(StandardCharsets.UTF_8)); + assertThat(receipt.eventPayload()).containsExactly(event.canonicalJsonUtf8()); + assertThat(captured.roleSource()) + .isEqualTo( + new RoleSnapshot( + account.getId(), + null, + Objects.requireNonNull(receipt.membershipId()), + 2L, + List.of("tenantAdmin"), + accountId, + tenantId, + provenance)); + assertThat(captured.pairSource()) + .isEqualTo( + new PairAuthority( + accountId, + tenantId, + provenance, + true, + 2L, + 1L, + 1L, + committed.eventId(), + committed.eventDigest(), + false)); + + assertThat(event.eventId()).isEqualTo(committed.eventId()); + assertThat(event.eventDigest()).isEqualTo(committed.eventDigest()); + assertThat(event.requestId()).isEqualTo(committed.operationId().toString()); + assertThat(event.outboxStreamKey()).isEqualTo(stream); + assertThat(event.outboxSequence()).isEqualTo("1"); + assertThat(event.accountId()).isEqualTo(accountId.toString()); + assertThat(event.tenantId()).isEqualTo(tenantId.toString()); + assertThat(event.membershipVersion()).isEqualTo(version); + assertThat(event.membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(event.membershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(event.roles()).containsExactly("tenantAdmin"); + assertThat(event.gameplayAdmissionAllowed()).isFalse(); + assertThat(event.callerBoundAuthorityInvalidated()).isFalse(); + assertThat(event.authorityTuple()).isEqualTo(captured.authorityTuple()); + assertThat(event.issuanceFence()).isEqualTo(captured.issuanceFence()); + + assertThat(captured.outboxCheckpoints()) + .containsExactly( + new OutboxCheckpointEntry(prefix + "account/" + accountId, "0"), + new OutboxCheckpointEntry(prefix + "issuer/" + ISSUER, "0"), + new OutboxCheckpointEntry(stream, "1"), + new OutboxCheckpointEntry(prefix + "tenant/" + tenantId, "0")); + assertThat(captured.outboxSourceEvidence()) + .containsExactly( + new OutboxSourceEvidence( + stream, "1", committed.eventId(), committed.eventDigest(), event.canonicalJson())); + } + + private static FreshTenantCreationEvidence tenantCreation() { + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + String key = "creator-capture-game"; + String disposition = "NEW_GAME_ROW"; + String requestDigest = + GameTenantCreationDigest.requestDigest(NAMESPACE, requestId, key, "Creator Capture", null); + return new FreshTenantCreationEvidence( + 1, + NAMESPACE, + requestId, + operationId, + requestDigest, + tenantId, + 19L, + key, + disposition, + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, requestId, operationId, requestDigest, tenantId, 19L, key, disposition)); + } + + private record CommittedSources( + AccountTenantCreationBootstrapResult bootstrap, InitialAssociationReadback party) {} + + private record CapturedSources( + CreatorControlCaptureSources creator, InitialAssociationReadback party) {} + + private static final class Fixture { + private final DSLContext dsl; + private final TransactionTemplate transaction; + private final Account account; + private final FreshTenantIdentityAssociationRepository tenants; + private final AccountAuthorityGenerationRepository generations; + private final IndividualCreatorPartyRepository parties; + private final AccountTenantCreationBootstrapService bootstrap; + private final AccountTenantCreationBootstrapService bootstrapWithUnavailableReceipt; + + private Fixture(UUID unavailableReceiptId) { + String schema = "creator_capture_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + transaction = new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + tenants = new FreshTenantIdentityAssociationRepository(dsl, NAMESPACE); + generations = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sources = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + var accounts = new AccountRepository(dsl, sources); + var pairs = new AccountMembershipPairAuthorityRepository(dsl); + var memberships = new AccountTenantMembershipRepository(dsl, accounts, tenants, pairs); + var roles = new AccountTenantMembershipRoleSnapshotRepository(dsl); + var operations = new AccountTenantCreationBootstrapOperationRepository(dsl); + var reader = + new AccountCreatorMembershipSourceReader( + accounts, + new AccountJoinOperationRepository(dsl), + memberships, + pairs, + roles, + tenants, + generations, + outbox, + sources, + operations); + var providers = new StaticListableBeanFactory(); + providers.addBean( + "controlledCreatorAuthorization", + (AccountTenantCreationBootstrapAuthorizationSource) + (evidence, mutation) -> mutation.get()); + var authorization = + providers.getBeanProvider(AccountTenantCreationBootstrapAuthorizationSource.class); + var audit = new AccountAuditOutboxRepository(dsl); + bootstrap = + new AccountTenantCreationBootstrapService( + accounts, + tenants, + reader, + pairs, + memberships, + roles, + outbox, + audit, + operations, + authorization); + // The real lookup still takes its row lock. Only the negative capture loses its result. + var unavailableReceipt = + new AccountTenantCreationBootstrapOperationRepository(dsl) { + @Override + public Optional findForUpdate(UUID requestId) { + var persisted = super.findForUpdate(requestId); + if (unavailableReceiptId.equals(requestId)) { + assertThat(persisted).isPresent(); + return Optional.empty(); + } + return persisted; + } + }; + bootstrapWithUnavailableReceipt = + new AccountTenantCreationBootstrapService( + accounts, + tenants, + reader, + pairs, + memberships, + roles, + outbox, + audit, + unavailableReceipt, + authorization); + parties = new IndividualCreatorPartyRepository(dsl, tenants, operations); + + var input = new Account(); + input.setUsername("creator-capture"); + input.setEmail("creator-capture@example.test"); + input.setPasswordHash("fixture-password-hash"); + input.setRole("player"); + account = Objects.requireNonNull(transaction.execute(ignored -> accounts.save(input))); + } + + private void insertControlledIndividualSource(IndividualCreatorPartySource party) { + byte[] payload = CreatorPartyEncoding.party(party); + dsl.execute( + "INSERT INTO account_individual_creator_party_sources " + + "(creator_party_id, account_uuid, verification_status, identity_version, " + + "policy_reference, policy_version, verification_evidence_reference, " + + "verification_evidence_version, source_version, source_payload, source_digest) " + + "VALUES (?, ?, 'VERIFIED', 1, ?, 1, ?, 1, 1, ?, ?)", + party.creatorPartyId(), + party.accountId(), + party.policyReference(), + party.verificationEvidenceReference(), + payload, + CreatorPartyEncoding.digest(payload)); + } + + private CapturedSources capture(AccountTenantCreationBootstrapService owner, UUID tenantId) { + return Objects.requireNonNull( + transaction.execute( + ignored -> { + var scope = parties.lockExistingInitialAssociationScope(tenantId); + var creator = + owner.readExistingCreatorControlCaptureSources(scope.accountId(), tenantId); + return new CapturedSources( + creator, parties.readExistingInitialAssociation(tenantId)); + })); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java index 1acb484eb8..bcba6b3fa6 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java @@ -384,6 +384,15 @@ void twoAuthenticatedTerminalOwnersSettleActualAccountOrderAndReadBackAfterCommi order, descriptor.world()); var terminal = AccountPublicationAuthorizationPostgresIntegrationTest.terminal(operation, outcome); + var foreignOrder = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), UUID.randomUUID(), order.input(), order.sources()); + var foreignOperation = + AccountPublicationAuthorizationPostgresIntegrationTest.operation( + foreignOrder, descriptor.world()); + var foreignTerminal = + AccountPublicationAuthorizationPostgresIntegrationTest.terminal( + foreignOperation, outcome); var mode = new AtomicReference<>("exact"); var gdReads = new java.util.concurrent.CopyOnWriteArrayList(); var worldReads = new java.util.concurrent.CopyOnWriteArrayList(); @@ -496,6 +505,9 @@ public void readPublicationTerminal( response.setOriginalOperation(com.google.protobuf.ByteString.EMPTY); if (mode.get().equals("world-terminal")) response.setWorldTerminalEvidence(com.google.protobuf.ByteString.EMPTY); + if (mode.get().equals("world-foreign-terminal")) + response.setWorldTerminalEvidence( + com.google.protobuf.ByteString.copyFrom(foreignTerminal.canonicalBytes())); if (mode.get().equals("world-unknown")) response.setWorldOutcomeValue(99); if (mode.get().equals("world-phase")) response.setWorldOutcomeValue( @@ -535,6 +547,16 @@ public void readPublicationTerminal( .isInstanceOf(RuntimeException.class); assertPending(sources, repository, order); } + mode.set("world-foreign-terminal"); + int readsBeforeForeignTerminal = worldReads.size(); + assertThatThrownBy( + () -> asGameDesign(() -> composition.settle(operation.canonicalBytes()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("World returned invalid publication terminal evidence") + .hasCauseInstanceOf(IllegalArgumentException.class); + assertThat(worldReads).hasSize(readsBeforeForeignTerminal + 1); + assertPending(sources, repository, order); + mode.set("exact"); try (var wrongGd = gameDesignClient(wrongServer.getPort(), pki.accountClient, pki.ca); var wrongWorld = worldClient(wrongServer.getPort(), pki.accountClient, pki.ca)) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java index 4eaf36bb80..bb9e0a43c4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.file.Path; +import java.time.Duration; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.Base64; @@ -11,6 +12,11 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; @@ -25,6 +31,7 @@ import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.test.IsolatedWorldPublicationInventoryFixtures; import net.firedevops.firemud.test.TestContainerImages; +import org.awaitility.Awaitility; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.testcontainers.containers.GenericContainer; @@ -285,6 +292,74 @@ void missingAmbiguousSubstitutedAndDisagreeingOwnersKeepOriginalSourcesHeld() th } } + @Test + void concurrentExactSettlementReadsOneCommittedReceipt() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var sources = issued.sources(); + var proof = proof(sources, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(sources.dsl); + var order = + new AccountPublicationAuthorizationService(issued.actors(), sources.fences, repository) + .authorize(issued.compact(), proof.selection(), issued.environment()); + var operation = operation(order, proof.world()); + var terminal = + terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); + var retry = new AtomicReference>(); + var retryBackend = new AtomicInteger(); + var executor = Executors.newSingleThreadExecutor(); + + try { + byte[] original = + sources.tx( + () -> { + int ownerBackend = + sources.dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class); + byte[] receipt = + repository.settle(operation, terminal, "ABORTED", terminal.canonicalBytes()); + retry.set( + executor.submit( + () -> + sources.tx( + () -> { + retryBackend.set( + sources + .dsl + .fetchSingle("SELECT pg_backend_pid()") + .get(0, Integer.class)); + return repository.settle( + operation, terminal, "ABORTED", terminal.canonicalBytes()); + }))); + Awaitility.await() + .pollInSameThread() + .atMost(Duration.ofSeconds(10)) + .until( + () -> + retryBackend.get() > 0 + && Boolean.TRUE.equals( + sources + .dsl + .fetchSingle( + "SELECT ? = ANY(pg_blocking_pids(?))", + ownerBackend, + retryBackend.get()) + .get(0, Boolean.class))); + return receipt; + }); + assertThat(retry.get().get(10, TimeUnit.SECONDS)).isEqualTo(original); + var retained = + sources.dsl.fetch( + "SELECT receipt FROM account_selected_publication_settlements WHERE operation_id = ?", + order.operationId()); + assertThat(retained).hasSize(1); + assertThat(retained.getFirst().get("receipt", byte[].class)).isEqualTo(original); + } finally { + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + } + } + @Test void settlingOneOrderLeavesEveryOtherOriginalSourceParticipationPending() throws Exception { try (var fixture = fixture()) { diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/model/ScriptPatchAlreadySealedException.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/model/ScriptPatchAlreadySealedException.java new file mode 100644 index 0000000000..4362da2555 --- /dev/null +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/model/ScriptPatchAlreadySealedException.java @@ -0,0 +1,8 @@ +package net.firedevops.firemud.automationscripting.model; + +/** A retained immutable patch snapshot cannot be replaced by a different seal. */ +public final class ScriptPatchAlreadySealedException extends IllegalStateException { + public ScriptPatchAlreadySealedException(String message) { + super(message); + } +} diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/model/ScriptPatchPublicationSeal.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/model/ScriptPatchPublicationSeal.java new file mode 100644 index 0000000000..13018489c0 --- /dev/null +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/model/ScriptPatchPublicationSeal.java @@ -0,0 +1,14 @@ +package net.firedevops.firemud.automationscripting.model; + +import java.time.OffsetDateTime; + +/** Immutable Automation-owned snapshot for one exact tenant/base/patch publication identity. */ +public record ScriptPatchPublicationSeal( + Long tenantId, + Long baseVersionId, + String scriptPatchVersion, + int manifestSchemaVersion, + int contentDigestSchemaVersion, + String contentDigest, + String snapshotJson, + OffsetDateTime sealedAt) {} diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptPatchPublicationSealRepository.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptPatchPublicationSealRepository.java new file mode 100644 index 0000000000..355a52023a --- /dev/null +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptPatchPublicationSealRepository.java @@ -0,0 +1,187 @@ +package net.firedevops.firemud.automationscripting.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.OffsetDateTime; +import java.util.Objects; +import net.firedevops.firemud.automationscripting.model.ScriptPatchAlreadySealedException; +import net.firedevops.firemud.automationscripting.model.ScriptPatchPublicationSeal; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** Unregistered owner-local storage. Database writer guards share its patch-row lock. */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class ScriptPatchPublicationSealRepository { + private static final int MAX_SCRIPT_PATCH_VERSION_LENGTH = 20; + + public record PatchLock( + Long tenantId, + String scriptPatchVersion, + boolean sealed, + Long baseVersionId, + Integer manifestSchemaVersion, + Integer contentDigestSchemaVersion, + String contentDigest, + String snapshotJson, + OffsetDateTime sealedAt) {} + + private final DSLContext dsl; + + public ScriptPatchPublicationSealRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** + * Creates/locks the one row shared by all patch writes and publication sealing. The caller must + * already own a transaction, so the FOR UPDATE lock remains held through its whole mutation. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PatchLock lockForUpdate(Long tenantId, String scriptPatchVersion) { + requireTransaction(); + validateIdentity(tenantId, scriptPatchVersion); + dsl.execute( + "INSERT INTO script_patch_publication_seals (tenant_id, script_patch_version) " + + "VALUES (?, ?) ON CONFLICT (tenant_id, script_patch_version) DO NOTHING", + tenantId, + scriptPatchVersion); + Record row = + dsl.fetchOne( + "SELECT tenant_id, script_patch_version, is_sealed, base_version_id, " + + "manifest_schema_version, content_digest_schema_version, content_digest, " + + "snapshot_json, sealed_at FROM script_patch_publication_seals " + + "WHERE tenant_id = ? AND script_patch_version = ? FOR UPDATE", + tenantId, + scriptPatchVersion); + if (row == null) { + throw new IllegalStateException("script_patch_publication_lock_row_missing"); + } + Boolean sealed = row.get("is_sealed", Boolean.class); + return new PatchLock( + row.get("tenant_id", Long.class), + row.get("script_patch_version", String.class), + Boolean.TRUE.equals(sealed), + row.get("base_version_id", Long.class), + row.get("manifest_schema_version", Integer.class), + row.get("content_digest_schema_version", Integer.class), + row.get("content_digest", String.class), + row.get("snapshot_json", String.class), + row.get("sealed_at", OffsetDateTime.class)); + } + + /** + * Stores a complete snapshot while acquiring the same transaction lock used by UpdateScript. + * Resealing is a no-op only when identity and every stored snapshot field match exactly. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ScriptPatchPublicationSeal seal( + Long tenantId, + Long baseVersionId, + String scriptPatchVersion, + int manifestSchemaVersion, + int contentDigestSchemaVersion, + String contentDigest, + String snapshotJson) { + requireTransaction(); + validateIdentity(tenantId, scriptPatchVersion); + Long validatedBaseVersionId = validateBaseVersionId(baseVersionId); + if (manifestSchemaVersion != 1 || contentDigestSchemaVersion != 5) { + throw new IllegalArgumentException("snapshot schema versions must be positive"); + } + if (contentDigest == null || !contentDigest.matches("[0-9a-f]{64}") || snapshotJson == null) { + throw new IllegalArgumentException("publication snapshot is incomplete"); + } + + PatchLock current = lockForUpdate(tenantId, scriptPatchVersion); + if (current.sealed()) { + if (isSameSeal( + current, + validatedBaseVersionId, + manifestSchemaVersion, + contentDigestSchemaVersion, + contentDigest, + snapshotJson)) { + return toSeal(current); + } + throw new ScriptPatchAlreadySealedException( + "script patch has already been sealed with different identity or content"); + } + + int updated = + dsl.execute( + "UPDATE script_patch_publication_seals SET base_version_id = ?, is_sealed = TRUE, " + + "manifest_schema_version = ?, content_digest_schema_version = ?, " + + "content_digest = ?, snapshot_json = ?, sealed_at = clock_timestamp() " + + "WHERE tenant_id = ? AND script_patch_version = ? AND is_sealed = FALSE", + validatedBaseVersionId, + manifestSchemaVersion, + contentDigestSchemaVersion, + contentDigest, + snapshotJson, + tenantId, + scriptPatchVersion); + if (updated != 1) { + throw new IllegalStateException("script_patch_publication_seal_write_lost"); + } + return toSeal(lockForUpdate(tenantId, scriptPatchVersion)); + } + + private static boolean isSameSeal( + PatchLock current, + Long baseVersionId, + int manifestSchemaVersion, + int contentDigestSchemaVersion, + String contentDigest, + String snapshotJson) { + return Objects.equals(current.baseVersionId(), baseVersionId) + && Objects.equals(current.manifestSchemaVersion(), manifestSchemaVersion) + && Objects.equals(current.contentDigestSchemaVersion(), contentDigestSchemaVersion) + && Objects.equals(current.contentDigest(), contentDigest) + && Objects.equals(current.snapshotJson(), snapshotJson); + } + + private static ScriptPatchPublicationSeal toSeal(PatchLock lock) { + return new ScriptPatchPublicationSeal( + lock.tenantId(), + lock.baseVersionId(), + lock.scriptPatchVersion(), + lock.manifestSchemaVersion(), + lock.contentDigestSchemaVersion(), + lock.contentDigest(), + lock.snapshotJson(), + lock.sealedAt()); + } + + private void requireTransaction() { + boolean autoCommit = dsl.connectionResult(connection -> connection.getAutoCommit()); + if (autoCommit) + throw new IllegalStateException("script patch seal requires an owned transaction"); + String isolation = + dsl.fetchSingle("SELECT current_setting('transaction_isolation')").get(0, String.class); + String readOnly = + dsl.fetchSingle("SELECT current_setting('transaction_read_only')").get(0, String.class); + if (!"read committed".equals(isolation) || !"off".equals(readOnly)) { + throw new IllegalStateException("script patch seal requires writable READ COMMITTED"); + } + } + + private static void validateIdentity(Long tenantId, String scriptPatchVersion) { + if (tenantId == null || tenantId <= 0) { + throw new IllegalArgumentException("tenantId must be positive"); + } + if (scriptPatchVersion == null + || scriptPatchVersion.isBlank() + || scriptPatchVersion.length() > MAX_SCRIPT_PATCH_VERSION_LENGTH) { + throw new IllegalArgumentException("scriptPatchVersion is invalid"); + } + } + + private static Long validateBaseVersionId(Long baseVersionId) { + if (baseVersionId == null || baseVersionId <= 0) { + throw new IllegalArgumentException("baseVersionId is invalid"); + } + return baseVersionId; + } +} diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/ScriptDesignDigestService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/ScriptDesignDigestService.java index c235ce34d8..0f342c5fe4 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/ScriptDesignDigestService.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/ScriptDesignDigestService.java @@ -1,11 +1,27 @@ package net.firedevops.firemud.automationscripting.service; +import java.util.List; +import net.firedevops.firemud.automationscripting.entity.ScriptDefinition; +import net.firedevops.firemud.automationscripting.entity.ScriptEventBinding; + public interface ScriptDesignDigestService { ScriptDraftDesignDigest getDraftDesignDigestForVersion(String tenantId, String versionId); ScriptDraftDesignDigest getDraftDesignDigestForScriptPatch( String tenantId, long baseVersionId, String scriptPatchVersion); + /** + * Digests already captured owner-local rows; this does not authorize publication or seal storage. + * The caller owns transaction/immutability and must supply definitions in the original + * owner-query order. Rows remain mutable and must not change during this call. + */ + ScriptDraftDesignDigest getDraftDesignDigestForScriptPatchSnapshot( + String tenantId, + long baseVersionId, + String scriptPatchVersion, + List definitions, + List bindings); + record ScriptDraftDesignDigest( String tenantId, String scopeValue, diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/PluginRuntimeStateServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/PluginRuntimeStateServiceImpl.java index e0255ffd99..b0d305b264 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/PluginRuntimeStateServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/PluginRuntimeStateServiceImpl.java @@ -24,7 +24,6 @@ import net.firedevops.firemud.automationscripting.v1.PluginState; import net.firedevops.firemud.common.security.RequestIdValidation; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionResponse; -import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; import net.firedevops.firemud.gamedesign.v1.PluginComponentPolicyDecision; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; import net.firedevops.firemud.gamesession.v1.GameInstanceRuntimeState; @@ -44,7 +43,6 @@ @Service public class PluginRuntimeStateServiceImpl implements PluginRuntimeStateService { private static final Logger logger = LoggerFactory.getLogger(PluginRuntimeStateServiceImpl.class); - private static final String PARTICIPANT_KEY_AUTOMATION_SCRIPTING = "AUTOMATION_SCRIPTING"; private static final String ACTOR_POLICY_RECONCILER = "automation-scripting-policy-reconciler"; private static final String DEFAULT_DISABLED_REASON = "not_activated"; private static final String OPERATION_ACTIVATE = "ACTIVATE"; @@ -411,16 +409,13 @@ private void requireAbilitySchemaMatch( throw new IllegalArgumentException( "GAME_INSTANCE_RUNTIME_UNAVAILABLE: " + releaseBundle.getError().getMessage()); } - ParticipantDigest automationDigest = - releaseBundle.getBundle().getParticipantDigestsList().stream() - .filter( - digest -> PARTICIPANT_KEY_AUTOMATION_SCRIPTING.equals(digest.getParticipantKey())) - .findFirst() + String runtimeAbilitySchemaDigest = + PublishedAbilitySchemaEvidence.read(releaseBundle.getBundle(), runtimeVersionId) .orElseThrow( () -> new IllegalArgumentException( "PLUGIN_ABILITY_SCHEMA_MISMATCH: runtime ability schema digest is unavailable")); - if (!automationDigest.getContentDigest().equals(pluginAbilitySchemaDigest)) { + if (!runtimeAbilitySchemaDigest.equals(pluginAbilitySchemaDigest)) { throw new IllegalArgumentException( "PLUGIN_ABILITY_SCHEMA_MISMATCH: plugin ability schema digest does not match runtime version"); } diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/PublishedAbilitySchemaEvidence.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/PublishedAbilitySchemaEvidence.java new file mode 100644 index 0000000000..e9965b7b52 --- /dev/null +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/PublishedAbilitySchemaEvidence.java @@ -0,0 +1,41 @@ +package net.firedevops.firemud.automationscripting.service.impl; + +import java.util.Optional; +import java.util.regex.Pattern; +import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; + +final class PublishedAbilitySchemaEvidence { + private static final String GAME_LOGIC = "GAME_LOGIC"; + private static final Pattern CONTENT_DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern ABILITY_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + + private PublishedAbilitySchemaEvidence() {} + + static Optional read(PublishedReleaseBundle bundle, long versionId) { + if (versionId <= 0 || bundle.getVersionId() != versionId || bundle.getIsScriptOnly()) { + return Optional.empty(); + } + ParticipantDigest owner = null; + for (ParticipantDigest participant : bundle.getParticipantDigestsList()) { + if (GAME_LOGIC.equals(participant.getParticipantKey())) { + if (owner != null) { + return Optional.empty(); + } + owner = participant; + } else if (participant.hasAbilitySchemaDigest()) { + return Optional.empty(); + } + } + if (owner == null + || !Long.toString(versionId).equals(owner.getScopeValue()) + || owner.getDigestSchemaVersion() != 1 + || owner.getAppliedCommitId().isBlank() + || !CONTENT_DIGEST.matcher(owner.getContentDigest()).matches() + || !owner.hasAbilitySchemaDigest() + || !ABILITY_DIGEST.matcher(owner.getAbilitySchemaDigest()).matches()) { + return Optional.empty(); + } + return Optional.of(owner.getAbilitySchemaDigest()); + } +} diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptDesignDigestServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptDesignDigestServiceImpl.java index 6dacdd4cc4..c20fd932a0 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptDesignDigestServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptDesignDigestServiceImpl.java @@ -6,10 +6,12 @@ import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Comparator; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.TreeMap; +import net.firedevops.firemud.automationscripting.entity.ScriptDefinition; import net.firedevops.firemud.automationscripting.entity.ScriptEventBinding; import net.firedevops.firemud.automationscripting.repository.ScriptDefinitionRepository; import net.firedevops.firemud.automationscripting.repository.ScriptEventBindingRepository; @@ -111,9 +113,54 @@ public ScriptDraftDesignDigest getDraftDesignDigestForScriptPatch( if (retainedBaseVersionId.longValue() != requestedBaseVersionId) { throw new IllegalArgumentException("script_patch_base_version_mismatch"); } + return digestSnapshot( + tenantId, + retainedBaseVersionId, + scriptPatchVersion, + repository.findByTenantIdAndScriptVersionOrderByNameAsc(tenantKey, scriptPatchVersion), + bindingRepository + .findByTenantIdAndScriptPatchVersionOrderByEventTypeAscEventSchemaVersionAscPriorityAscScriptIdAsc( + tenantKey, scriptPatchVersion)); + } + + @Override + public ScriptDraftDesignDigest getDraftDesignDigestForScriptPatchSnapshot( + String tenantId, + long baseVersionId, + String scriptPatchVersion, + List definitions, + List bindings) { + long tenantKey = RequestIdValidation.requirePositiveLong(tenantId, "tenantId"); + if (baseVersionId <= 0 || scriptPatchVersion == null || scriptPatchVersion.isBlank()) { + throw new IllegalArgumentException("script_patch_snapshot_identity_invalid"); + } + var names = new HashSet(); + for (var definition : definitions) { + if (!Objects.equals(definition.getTenantId(), tenantKey) + || !scriptPatchVersion.equals(definition.getScriptVersion()) + || definition.getName() == null + || definition.getName().isBlank() + || !names.add(definition.getName())) { + throw new IllegalArgumentException("script_patch_snapshot_definition_identity_invalid"); + } + } + for (var binding : bindings) { + if (!Objects.equals(binding.getTenantId(), tenantKey) + || !scriptPatchVersion.equals(binding.getScriptPatchVersion())) { + throw new IllegalArgumentException("script_patch_snapshot_binding_identity_invalid"); + } + } + return digestSnapshot(tenantId, baseVersionId, scriptPatchVersion, definitions, bindings); + } + + private ScriptDraftDesignDigest digestSnapshot( + String tenantId, + long retainedBaseVersionId, + String scriptPatchVersion, + List definitions, + List storedBindings) { List> scripts = new ArrayList<>(); - for (var script : - repository.findByTenantIdAndScriptVersionOrderByNameAsc(tenantKey, scriptPatchVersion)) { + for (var script : definitions) { requireStoredBase(script.getBaseVersionId(), retainedBaseVersionId, "script"); scripts.add( canonicalMap( @@ -123,10 +170,6 @@ public ScriptDraftDesignDigest getDraftDesignDigestForScriptPatch( "baseVersionId", retainedBaseVersionId, "definition", normalize(script.getDefinition())))); } - List storedBindings = - bindingRepository - .findByTenantIdAndScriptPatchVersionOrderByEventTypeAscEventSchemaVersionAscPriorityAscScriptIdAsc( - tenantKey, scriptPatchVersion); for (ScriptEventBinding binding : storedBindings) { requireStoredBase(binding.getBaseVersionId(), retainedBaseVersionId, "binding"); } diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPublicationSealService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPublicationSealService.java new file mode 100644 index 0000000000..9830e55dc4 --- /dev/null +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPublicationSealService.java @@ -0,0 +1,197 @@ +package net.firedevops.firemud.automationscripting.service.impl; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import net.firedevops.firemud.automationscripting.entity.ScriptDefinition; +import net.firedevops.firemud.automationscripting.entity.ScriptEventBinding; +import net.firedevops.firemud.automationscripting.model.ScriptPatchPublicationSeal; +import net.firedevops.firemud.automationscripting.repository.ScriptDefinitionRepository; +import net.firedevops.firemud.automationscripting.repository.ScriptEventBindingRepository; +import net.firedevops.firemud.automationscripting.repository.ScriptPatchPublicationSealRepository; +import net.firedevops.firemud.automationscripting.service.ScriptDesignDigestService; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.security.RequestIdValidation; +import org.springframework.transaction.annotation.Transactional; +import tools.jackson.databind.ObjectMapper; + +/** + * Builds and stores the owner-local immutable script patch snapshot. + * + *

This unregistered primitive stores content and exact request binding only. It does not + * authenticate Game Design, produce an affected-handler readiness manifest, or authorize + * publication. The caller must own the transaction; the storage primitive verifies that physical + * transaction exists. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected repositories and mapper are internal Spring collaborators.") +public class ScriptPatchPublicationSealService { + private static final int MANIFEST_SCHEMA_VERSION = 1; + private static final int MAX_SCRIPT_PATCH_VERSION_LENGTH = 20; + + private final ScriptDefinitionRepository definitions; + private final ScriptEventBindingRepository bindings; + private final ScriptPatchPublicationSealRepository seals; + private final ScriptDesignDigestService digestService; + private final ObjectMapper objectMapper; + + public ScriptPatchPublicationSealService( + ScriptDefinitionRepository definitions, + ScriptEventBindingRepository bindings, + ScriptPatchPublicationSealRepository seals, + ScriptDesignDigestService digestService, + ObjectMapper objectMapper) { + this.definitions = definitions; + this.bindings = bindings; + this.seals = seals; + this.digestService = digestService; + this.objectMapper = objectMapper; + } + + /** + * Stores one canonical snapshot for the exact tenant/base/patch identity. An identical reseal is + * idempotent; any changed definition, binding, schema, digest, or base binding is rejected. + */ + @Transactional(propagation = org.springframework.transaction.annotation.Propagation.MANDATORY) + public ScriptPatchPublicationSeal sealSnapshot( + PublicationDigestRequestBinding publication, String workflowIdentity, String requestDigest) { + if (publication == null + || publication.scopeKind() != PublicationDigestRequestBinding.ScopeKind.SCRIPT_PATCH) { + throw new IllegalArgumentException("script patch publication binding required"); + } + publication.validateSupplied(workflowIdentity, requestDigest); + String tenantId = publication.tenantId(); + long baseVersionId = + RequestIdValidation.requirePositiveLong(publication.baseVersionId(), "baseVersionId"); + String scriptPatchVersion = publication.scriptPatchVersion(); + long tenantKey = RequestIdValidation.requirePositiveLong(tenantId, "tenantId"); + validateText(scriptPatchVersion, MAX_SCRIPT_PATCH_VERSION_LENGTH, "scriptPatchVersion"); + + seals.lockForUpdate(tenantKey, scriptPatchVersion); + if (!definitions + .findScriptPatchBaseVersionId(tenantId, scriptPatchVersion) + .filter(base -> base == baseVersionId) + .isPresent()) { + throw new IllegalStateException("script_patch_retained_base_missing_or_changed"); + } + List scriptSnapshot = + definitions.findByTenantIdAndScriptVersionOrderByNameAsc(tenantKey, scriptPatchVersion); + List bindingSnapshot = + bindings + .findByTenantIdAndScriptPatchVersionOrderByEventTypeAscEventSchemaVersionAscPriorityAscScriptIdAsc( + tenantKey, scriptPatchVersion); + validateDefinitions(scriptSnapshot); + + ScriptDesignDigestService.ScriptDraftDesignDigest digest = + digestService.getDraftDesignDigestForScriptPatchSnapshot( + Long.toString(tenantKey), + baseVersionId, + scriptPatchVersion, + scriptSnapshot, + bindingSnapshot); + String snapshotJson = + serializeSnapshot( + tenantKey, + baseVersionId, + scriptPatchVersion, + scriptSnapshot, + bindingSnapshot, + digest, + publication); + + // The repository reacquires the same transaction lock and allows only byte-for-byte resealing. + return seals.seal( + tenantKey, + baseVersionId, + scriptPatchVersion, + MANIFEST_SCHEMA_VERSION, + digest.digestSchemaVersion(), + digest.contentDigest(), + snapshotJson); + } + + private String serializeSnapshot( + long tenantId, + long baseVersionId, + String scriptPatchVersion, + List scriptSnapshot, + List bindingSnapshot, + ScriptDesignDigestService.ScriptDraftDesignDigest digest, + PublicationDigestRequestBinding publication) { + List> scriptEntries = + scriptSnapshot.stream() + .map( + definition -> + canonicalMap( + Map.of( + "scriptName", definition.getName(), + "scriptPatchVersion", definition.getScriptVersion(), + "definition", definition.getDefinition()))) + .toList(); + List> bindingEntries = + bindingSnapshot.stream() + .map( + binding -> + canonicalMap( + Map.ofEntries( + Map.entry("scriptPatchVersion", binding.getScriptPatchVersion()), + Map.entry("eventType", binding.getEventType()), + Map.entry("eventSchemaVersion", binding.getEventSchemaVersion()), + Map.entry("scriptId", binding.getScriptId()), + Map.entry("bindingId", binding.getBindingId()), + Map.entry("targetScopeType", binding.getTargetScopeType()), + Map.entry("targetScopeId", binding.getTargetScopeId()), + Map.entry("priority", binding.getPriority()), + Map.entry("priorityTag", binding.getPriorityTag()), + Map.entry("requiresExclusiveEvent", binding.isRequiresExclusiveEvent()), + Map.entry("enabled", binding.isEnabled())))) + .toList(); + Map envelope = + canonicalMap( + Map.ofEntries( + Map.entry("tenantId", Long.toString(tenantId)), + Map.entry("baseVersionId", baseVersionId), + Map.entry("scriptPatchVersion", scriptPatchVersion), + Map.entry("manifestSchemaVersion", MANIFEST_SCHEMA_VERSION), + Map.entry("contentDigestSchemaVersion", digest.digestSchemaVersion()), + Map.entry("contentDigest", digest.contentDigest()), + Map.entry("definitions", scriptEntries), + Map.entry("eventBindings", bindingEntries), + Map.entry("publishRequestId", publication.publishRequestId()), + Map.entry("derivedWorkflowIdentity", publication.derivedWorkflowIdentity()), + Map.entry("requestDigest", publication.requestDigest()))); + try { + return objectMapper.writeValueAsString(envelope); + } catch (Exception ex) { + throw new IllegalStateException("failed to serialize script patch publication snapshot", ex); + } + } + + private static void validateDefinitions(List scriptSnapshot) { + String previousName = null; + for (ScriptDefinition definition : scriptSnapshot) { + if (definition.getName() == null + || definition.getName().isBlank() + || definition.getDefinition() == null + || definition.getScriptVersion() == null) { + throw new IllegalStateException("script_patch_publication_definition_invalid"); + } + if (definition.getName().equals(previousName)) { + throw new IllegalStateException("script_patch_publication_definition_identity_duplicate"); + } + previousName = definition.getName(); + } + } + + private static void validateText(String value, int maximumLength, String field) { + if (value == null || value.isBlank() || value.length() > maximumLength) { + throw new IllegalArgumentException(field + " is invalid"); + } + } + + private static Map canonicalMap(Map values) { + return new TreeMap<>(values); + } +} diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImpl.java index a8a8c4d2f1..0ad6bba13e 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImpl.java @@ -43,7 +43,6 @@ import net.firedevops.firemud.common.security.RequestIdValidation; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedScriptPatchVersionResponse; -import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; import net.firedevops.firemud.gamesession.v1.GetGameInstanceRuntimeStateResponse; import org.slf4j.Logger; @@ -64,7 +63,6 @@ static final class ReplayIdempotencyConflictException extends RuntimeException { } private static final Logger LOGGER = LoggerFactory.getLogger(ScriptWorkItemServiceImpl.class); - private static final String PARTICIPANT_KEY_AUTOMATION_SCRIPTING = "AUTOMATION_SCRIPTING"; private static final String STATUS_PENDING_EVALUATION = "PENDING_EVALUATION"; private static final String STATUS_EVALUATING = "EVALUATING"; private static final String STATUS_CANCELED = "CANCELED"; @@ -1292,11 +1290,7 @@ private PublicationMetadata publicationMetadata( return new PublicationMetadata(baseVersionId, "", publication); } String abilitySchemaDigest = - releaseBundleResponse.getBundle().getParticipantDigestsList().stream() - .filter( - digest -> PARTICIPANT_KEY_AUTOMATION_SCRIPTING.equals(digest.getParticipantKey())) - .map(ParticipantDigest::getContentDigest) - .findFirst() + PublishedAbilitySchemaEvidence.read(releaseBundleResponse.getBundle(), baseVersionId) .orElse(""); return new PublicationMetadata(baseVersionId, abilitySchemaDigest, publication); } diff --git a/services/automation-scripting-service/src/main/resources/db/migration/V1006__private_script_patch_snapshot_seal.sql b/services/automation-scripting-service/src/main/resources/db/migration/V1006__private_script_patch_snapshot_seal.sql new file mode 100644 index 0000000000..5e13aa64d0 --- /dev/null +++ b/services/automation-scripting-service/src/main/resources/db/migration/V1006__private_script_patch_snapshot_seal.sql @@ -0,0 +1,218 @@ +-- Private owner-local content seal; no publication ingress or readiness authority. +-- Existing authored rows are retained; no historical seal or base is synthesized. +CREATE TABLE script_patch_publication_seals ( + tenant_id BIGINT NOT NULL CHECK (tenant_id > 0), + script_patch_version VARCHAR(128) NOT NULL CHECK (length(trim(script_patch_version)) > 0), + is_sealed BOOLEAN NOT NULL DEFAULT FALSE, + base_version_id BIGINT, + manifest_schema_version INTEGER, + content_digest_schema_version INTEGER, + content_digest VARCHAR(64), + snapshot_json TEXT, + sealed_at TIMESTAMPTZ, + PRIMARY KEY (tenant_id, script_patch_version), + CHECK ((NOT is_sealed AND base_version_id IS NULL AND manifest_schema_version IS NULL + AND content_digest_schema_version IS NULL AND content_digest IS NULL + AND snapshot_json IS NULL AND sealed_at IS NULL) + OR (is_sealed AND base_version_id IS NOT NULL AND base_version_id > 0 + AND manifest_schema_version IS NOT NULL AND manifest_schema_version = 1 + AND content_digest_schema_version IS NOT NULL AND content_digest_schema_version = 5 AND content_digest IS NOT NULL + AND snapshot_json IS NOT NULL AND sealed_at IS NOT NULL)) +); + +-- [jooq ignore start] +ALTER TABLE script_patch_publication_seals ADD CONSTRAINT ck_script_patch_seal_complete + CHECK (NOT is_sealed OR (content_digest ~ '^[0-9a-f]{64}$' + AND octet_length(snapshot_json) BETWEEN 2 AND 16777216 + AND jsonb_typeof(snapshot_json::jsonb) = 'object')); + +CREATE FUNCTION script_patch_seal_immutable() RETURNS TRIGGER +LANGUAGE plpgsql SET search_path = "${serviceSchema}", pg_catalog AS $$ +BEGIN + IF TG_OP = 'INSERT' AND NOT NEW.is_sealed THEN RETURN NEW; END IF; + IF TG_OP = 'UPDATE' AND NOT OLD.is_sealed AND NEW.is_sealed + AND NEW.tenant_id = OLD.tenant_id + AND NEW.script_patch_version = OLD.script_patch_version THEN + IF NOT EXISTS (SELECT 1 FROM script_patch_base_bindings + WHERE tenant_id=NEW.tenant_id::TEXT AND script_patch_version=NEW.script_patch_version + AND base_version_id=NEW.base_version_id) THEN + RAISE EXCEPTION 'Script patch seal requires exact retained base' USING ERRCODE='23514'; + END IF; + RETURN NEW; + END IF; + RAISE EXCEPTION 'Immutable script patch seal cannot be replaced or removed' USING ERRCODE='23514'; +END; +$$; +CREATE TRIGGER script_patch_seal_retained BEFORE INSERT OR UPDATE OR DELETE + ON script_patch_publication_seals FOR EACH ROW EXECUTE FUNCTION script_patch_seal_immutable(); +CREATE TRIGGER script_patch_seal_no_truncate BEFORE TRUNCATE + ON script_patch_publication_seals FOR EACH STATEMENT EXECUTE FUNCTION script_patch_seal_immutable(); + +-- One row lock is shared by raw SQL writers and the private seal owner. Lock both +-- old/new identities in stable order before permitting an identity-changing update. +CREATE FUNCTION script_patch_authored_write_guard() RETURNS TRIGGER +LANGUAGE plpgsql SET search_path = "${serviceSchema}", pg_catalog AS $$ +DECLARE old_row JSONB; new_row JSONB; scope RECORD; sealed BOOLEAN; +BEGIN + IF TG_OP = 'TRUNCATE' THEN + IF EXISTS (SELECT 1 FROM script_patch_publication_seals WHERE is_sealed) THEN + RAISE EXCEPTION 'Sealed authored patch rows cannot be truncated' USING ERRCODE='23514'; + END IF; + RETURN NULL; + END IF; + IF TG_OP <> 'INSERT' THEN old_row := to_jsonb(OLD); END IF; + IF TG_OP <> 'DELETE' THEN new_row := to_jsonb(NEW); END IF; + FOR scope IN + SELECT DISTINCT (row_value->>'tenant_id')::BIGINT AS tenant, + coalesce(row_value->>'script_patch_version',row_value->>'version') AS patch + FROM (VALUES(old_row),(new_row)) AS images(row_value) + WHERE row_value IS NOT NULL + ORDER BY tenant, patch + LOOP + INSERT INTO script_patch_publication_seals(tenant_id,script_patch_version) + VALUES(scope.tenant,scope.patch) ON CONFLICT DO NOTHING; + SELECT is_sealed INTO sealed FROM script_patch_publication_seals + WHERE tenant_id=scope.tenant AND script_patch_version=scope.patch FOR UPDATE; + IF sealed IS DISTINCT FROM FALSE THEN + RAISE EXCEPTION 'Authored script patch is sealed' USING ERRCODE='23514'; + END IF; + END LOOP; + IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER scripts_seal_writer BEFORE INSERT OR UPDATE OR DELETE ON scripts + FOR EACH ROW EXECUTE FUNCTION script_patch_authored_write_guard(); +CREATE TRIGGER script_bindings_seal_writer BEFORE INSERT OR UPDATE OR DELETE ON script_event_bindings + FOR EACH ROW EXECUTE FUNCTION script_patch_authored_write_guard(); +CREATE TRIGGER script_base_seal_writer BEFORE INSERT OR UPDATE OR DELETE ON script_patch_base_bindings + FOR EACH ROW EXECUTE FUNCTION script_patch_authored_write_guard(); +CREATE TRIGGER scripts_seal_no_truncate BEFORE TRUNCATE ON scripts + FOR EACH STATEMENT EXECUTE FUNCTION script_patch_authored_write_guard(); +CREATE TRIGGER script_bindings_seal_no_truncate BEFORE TRUNCATE ON script_event_bindings + FOR EACH STATEMENT EXECUTE FUNCTION script_patch_authored_write_guard(); +CREATE TRIGGER script_base_seal_no_truncate BEFORE TRUNCATE ON script_patch_base_bindings + FOR EACH STATEMENT EXECUTE FUNCTION script_patch_authored_write_guard(); + +INSERT INTO automation_runtime_family_classification + (family_id,relation_name,component_name,family_role,state_class,fresh_disposition,retention_disposition,owner_consequence) +VALUES ('script_patch_publication_seals','script_patch_publication_seals','','SOURCE','NOT_PAYLOAD','SOURCE_ONLY','IMMUTABLE_RETAINED', + 'Private exact authored content and publication-request binding; not a readiness manifest, runtime initialization, or publication authority. Retain sealed bytes and shared writer locks.'); + +CREATE OR REPLACE FUNCTION automation_runtime_family_catalog_installed() RETURNS BOOLEAN +LANGUAGE SQL STABLE SET search_path = "${serviceSchema}", pg_catalog AS $$ + SELECT EXISTS (SELECT 1 FROM "${flyway:table}" + WHERE version='1004' AND script='V1004__automation_owner_runtime_family_catalog.sql' AND success) + AND EXISTS (SELECT 1 FROM "${flyway:table}" + WHERE version='1005' AND script='V1005__automation_catalog_view_options.sql' AND success) + AND EXISTS (SELECT 1 FROM "${flyway:table}" WHERE version='1006' AND script='V1006__private_script_patch_snapshot_seal.sql' AND success); +$$; + +CREATE OR REPLACE FUNCTION automation_runtime_family_catalog_bytes(p_epoch BIGINT) RETURNS BYTEA +LANGUAGE plpgsql STABLE SET search_path = "${serviceSchema}", pg_catalog AS $$ +DECLARE v_families JSONB; v_facts JSONB; v_gaps JSONB; +BEGIN + IF p_epoch IS NULL OR p_epoch<=0 THEN + RAISE EXCEPTION 'Positive Automation catalog epoch required' USING ERRCODE='23514'; + END IF; + IF EXISTS ( + SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname='${serviceSchema}' AND c.relkind IN ('r','p','f') + EXCEPT SELECT relation_name FROM automation_runtime_family_classification WHERE component_name='' + ) OR EXISTS ( + SELECT 1 FROM automation_runtime_family_classification f + LEFT JOIN pg_namespace n ON n.nspname='${serviceSchema}' + LEFT JOIN pg_class c ON c.relnamespace=n.oid AND c.relname=f.relation_name AND c.relkind IN ('r','p','f') + WHERE c.oid IS NULL OR (f.component_name<>'' AND NOT EXISTS ( + SELECT 1 FROM pg_attribute a WHERE a.attrelid=c.oid AND a.attname=f.component_name + AND a.attnum>0 AND NOT a.attisdropped)) + ) THEN + RAISE EXCEPTION 'Unclassified or changed Automation schema family' USING ERRCODE='23514'; + END IF; + SELECT jsonb_agg(jsonb_build_object('familyId',family_id,'relation',relation_name,'component',component_name, + 'role',family_role,'stateClass',state_class,'freshDisposition',fresh_disposition, + 'retentionDisposition',retention_disposition,'ownerConsequence',owner_consequence) + ORDER BY family_id COLLATE "C") INTO v_families FROM automation_runtime_family_classification; + SELECT jsonb_agg(jsonb_build_object('id',gap_id,'disposition',disposition,'ownerConsequence',owner_consequence) + ORDER BY gap_id COLLATE "C") INTO v_gaps FROM automation_runtime_catalog_non_sql_gap; + + -- Live definitions, never payload rows, OIDs, sequence positions, statistics or installation times. + WITH relations AS ( + SELECT c.* FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='${serviceSchema}' + ), definitions(kind,identity,definition) AS ( + SELECT 'TABLE',c.relname::TEXT,jsonb_build_array(c.relkind,c.relpersistence, + c.relrowsecurity,c.relforcerowsecurity,c.reloptions,pg_get_partkeydef(c.oid))::TEXT + FROM relations c WHERE c.relkind IN ('r','p','f') + UNION ALL + SELECT 'COLUMN',c.relname||'.'||a.attname,jsonb_build_array(a.attnum, + format_type(a.atttypid,a.atttypmod),a.attnotnull,a.attidentity,a.attgenerated, + pg_get_expr(d.adbin,d.adrelid),co.collname)::TEXT + FROM relations c JOIN pg_attribute a ON a.attrelid=c.oid + LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum + LEFT JOIN pg_collation co ON co.oid=a.attcollation + WHERE c.relkind IN ('r','p','f','v','m') AND a.attnum>0 AND NOT a.attisdropped + UNION ALL + SELECT 'CONSTRAINT',c.relname||'.'||k.conname, + jsonb_build_array(pg_get_constraintdef(k.oid,true),k.convalidated,k.condeferrable,k.condeferred)::TEXT + FROM relations c JOIN pg_constraint k ON k.conrelid=c.oid + UNION ALL + SELECT 'INDEX',c.relname::TEXT,jsonb_build_array(pg_get_indexdef(c.oid),i.indisvalid,i.indisready)::TEXT + FROM relations c JOIN pg_index i ON i.indexrelid=c.oid + UNION ALL + SELECT 'TRIGGER',c.relname||'.'||t.tgname,jsonb_build_array(pg_get_triggerdef(t.oid,true),t.tgenabled)::TEXT + FROM relations c JOIN pg_trigger t ON t.tgrelid=c.oid WHERE NOT t.tgisinternal + UNION ALL + SELECT 'POLICY',c.relname||'.'||p.polname,jsonb_build_array(p.polcmd,p.polpermissive, + (SELECT jsonb_agg(r.rolname ORDER BY r.rolname COLLATE "C") FROM pg_roles r WHERE r.oid=ANY(p.polroles)), + pg_get_expr(p.polqual,p.polrelid),pg_get_expr(p.polwithcheck,p.polrelid))::TEXT + FROM relations c JOIN pg_policy p ON p.polrelid=c.oid + UNION ALL + SELECT 'RULE',c.relname||'.'||r.rulename,pg_get_ruledef(r.oid,true) + FROM relations c JOIN pg_rewrite r ON r.ev_class=c.oid + UNION ALL + SELECT 'ROUTINE',p.proname||'('||pg_get_function_identity_arguments(p.oid)||')',pg_get_functiondef(p.oid) + FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace + WHERE n.nspname='${serviceSchema}' AND p.prokind IN ('f','p') + UNION ALL + SELECT 'SEQUENCE',c.relname::TEXT,(to_jsonb(s)-'seqrelid')::TEXT + FROM relations c JOIN pg_sequence s ON s.seqrelid=c.oid + UNION ALL + SELECT 'VIEW',c.relname::TEXT,jsonb_build_array(pg_get_viewdef(c.oid,true),c.reloptions)::TEXT FROM relations c WHERE c.relkind IN ('v','m') + UNION ALL + SELECT 'TYPE',t.typname::TEXT,jsonb_build_array(t.typtype,t.typnotnull,t.typdefault, + (SELECT jsonb_agg(e.enumlabel ORDER BY e.enumsortorder) FROM pg_enum e WHERE e.enumtypid=t.oid))::TEXT + FROM pg_type t JOIN pg_namespace n ON n.oid=t.typnamespace WHERE n.nspname='${serviceSchema}' + UNION ALL + SELECT 'MIGRATION',installed_rank::TEXT||':'||coalesce(version,'repeatable')||':'||script, + jsonb_build_array(version,type,script,checksum,success)::TEXT + FROM "${flyway:table}" WHERE version IS DISTINCT FROM '1004' AND version IS DISTINCT FROM '1005' AND version IS DISTINCT FROM '1006' + UNION ALL + -- Catalog history rows are post-transaction. Distinct stable installation markers bind + -- those scripts; installed() separately requires both successful exact script identities. + -- These markers do not fabricate post-transaction Flyway checksums. + SELECT 'MIGRATION','catalog-installation:1004','V1004__automation_owner_runtime_family_catalog.sql' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1005','V1005__automation_catalog_view_options.sql' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1006','V1006__private_script_patch_snapshot_seal.sql' + ) + SELECT jsonb_agg(jsonb_build_object('kind',kind,'identity',identity, + 'definitionDigest','sha256:'||encode(sha256(convert_to(definition,'UTF8')),'hex')) + ORDER BY (kind||'/'||identity) COLLATE "C") INTO v_facts FROM definitions; + IF v_families IS NULL OR v_facts IS NULL OR v_gaps IS NULL + OR jsonb_array_length(v_families)>512 OR jsonb_array_length(v_facts)>16384 + OR jsonb_array_length(v_gaps)>32 THEN + RAISE EXCEPTION 'Complete Automation catalog exceeds source bounds' USING ERRCODE='23514'; + END IF; + RETURN convert_to(jsonb_build_object('schema','automation-runtime-family-catalog/v1', + 'owner','automation-scripting-service','catalogEpoch',p_epoch::TEXT, + 'families',v_families,'schemaFacts',v_facts,'nonSqlGaps',v_gaps)::TEXT,'UTF8'); +END; +$$; + +-- Replace every affected routine before sealing the next exact owner-local epoch. +INSERT INTO automation_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT next_epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') +FROM (SELECT coalesce(max(catalog_epoch),0)+1 AS next_epoch FROM automation_runtime_family_catalog_epoch) next +CROSS JOIN LATERAL (SELECT automation_runtime_family_catalog_bytes(next.next_epoch) AS bytes) seal; +-- [jooq ignore stop] diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java index cc9ff1c293..00a49d2ca3 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java @@ -98,7 +98,7 @@ void migrateWithRetainedLegacyAuthoredRows() { dsl.fetchSingle( "SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1") .get(0, String.class)) - .isEqualTo("1005"); + .isEqualTo("1006"); } /** Synthetic retained SQL state only; no genuine script or runtime admission authority. */ diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java index 4eaf8de2f1..651cefa7ec 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java @@ -511,7 +511,7 @@ void deniesUnqualifiedRowsInEachAuthoredFamilyWithoutCreatingOwnerRecords() { dsl.execute( "INSERT INTO script_patch_base_bindings (tenant_id, script_patch_version, base_version_id) " + "VALUES (?, ?, ?)", - "unqualified-tenant-key", + "503", "unqualified-patch", 503L); assertUnqualifiedDenial(fixture, requestDigest); diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationRuntimeFamilyCatalogPostgresIntegrationTest.java index 113ea88800..54025eda9c 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -84,7 +84,7 @@ void completeLiveCensusIncludesEveryEmptyTableAndExplicitBlockingFamiliesAndNonS throws Exception { try (Fixture f = fixture(null)) { var catalog = f.owner().read(request()).catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(2); + assertThat(catalog.catalogEpoch()).isEqualTo(3); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -364,7 +364,7 @@ void priorMigrationFactsAndOwnSuccessfulScriptAreRequiredNotFabricatedOwnChecksu "INSERT INTO " + f.history + " (installed_rank,version,description,type,script,checksum,installed_by,execution_time,success)" - + " VALUES (10000,'1006','controlled later migration','SQL','V1006__probe.sql',1,current_user,0,true)"); + + " VALUES (10000,'1007','controlled later migration','SQL','V1007__probe.sql',1,current_user,0,true)"); assertThatThrownBy(() -> f.owner().read(request())) .isInstanceOf(AutomationRuntimeFamilyCatalogRepository.CatalogConflictException.class); } @@ -379,8 +379,8 @@ void explicitOwnerEpochAdvanceInvalidatesOldRequestButRetainsOriginalSnapshot() // Controlled owner revision installation only; no runtime mutation/registration API exists. f.dsl.execute( "INSERT INTO automation_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" - + " SELECT 3,bytes,'sha256:'||encode(sha256(bytes),'hex')" - + " FROM (SELECT automation_runtime_family_catalog_bytes(3) AS bytes) revised"); + + " SELECT 4,bytes,'sha256:'||encode(sha256(bytes),'hex')" + + " FROM (SELECT automation_runtime_family_catalog_bytes(4) AS bytes) revised"); assertThatThrownBy(() -> f.owner().readExact(read)) .isInstanceOf(AutomationRuntimeFamilyCatalogRepository.CatalogConflictException.class); assertThatThrownBy(() -> f.owner().read(read)) @@ -393,9 +393,9 @@ void explicitOwnerEpochAdvanceInvalidatesOldRequestButRetainsOriginalSnapshot() .get(0, byte[].class)) .isEqualTo(AutomationRuntimeFamilyCatalogCodec.evidenceBytes(original)); var revised = f.owner().read(request()); - assertThat(revised.catalog().catalogEpoch()).isEqualTo(3); + assertThat(revised.catalog().catalogEpoch()).isEqualTo(4); assertThat(revised.catalog().digest()).isNotEqualTo(original.catalog().digest()); - assertThat(f.count("automation_runtime_family_catalog_epoch")).isEqualTo(3); + assertThat(f.count("automation_runtime_family_catalog_epoch")).isEqualTo(4); } } @@ -503,7 +503,7 @@ void viewSecurityOptionsInvalidateReadRetryAndFreshCaptureWithoutChangingRetaine migration(f.source, f.schema, f.history, null).migrate(); Request read = request(); var original = f.owner().read(read); - assertThat(original.catalog().catalogEpoch()).isEqualTo(2); + assertThat(original.catalog().catalogEpoch()).isEqualTo(3); assertThat(original.catalog().schemaFacts()) .anySatisfy( fact -> { @@ -560,7 +560,7 @@ void catalogViewOptionsUpgradeRetainsV1004DataHistoryEpochAndSnapshot() throws E List history = f.historyRows(false); String epoch = f.catalogRows("automation_runtime_family_catalog_epoch"); String snapshots = f.catalogRows("automation_runtime_family_catalog_snapshot"); - migration(f.source, f.schema, f.history, null).migrate(); + migration(f.source, f.schema, f.history, "1005").migrate(); for (var retained : rows.entrySet()) assertThat(f.jsonRows(retained.getKey())).isEqualTo(retained.getValue()); assertThat( @@ -607,13 +607,55 @@ void catalogViewOptionsUpgradeRetainsV1004DataHistoryEpochAndSnapshot() throws E script.getBytes(java.nio.charset.StandardCharsets.UTF_8))); }); } - migration(f.source, f.schema, f.history, null).validate(); + migration(f.source, f.schema, f.history, "1005").validate(); + } + } + + @Test + void privateSealUpgradeRetainsAllPriorRowsEpochsAndSnapshots() throws Exception { + try (Fixture f = fixture("1005")) { + f.populatePredecessor(); + var original = f.owner().read(request()); + Map rows = f.rows(); + rows.remove("automation_runtime_family_catalog_epoch"); + rows.remove("automation_runtime_family_classification"); + String epochs = f.catalogRows("automation_runtime_family_catalog_epoch"); + String families = f.catalogRows("automation_runtime_family_classification"); + List history = f.historyRows(false); + migration(f.source, f.schema, f.history, null).migrate(); + for (var retained : rows.entrySet()) + assertThat(f.jsonRows(retained.getKey())).isEqualTo(retained.getValue()); + assertThat(f.catalogRows("automation_runtime_family_catalog_epoch WHERE catalog_epoch<=2")) + .isEqualTo(epochs); + assertThat( + f.catalogRows( + "automation_runtime_family_classification WHERE family_id<>'script_patch_publication_seals'")) + .isEqualTo(families); + assertThat( + f.dsl + .fetch( + "SELECT to_jsonb(h)::text FROM " + + f.history + + " h WHERE version IS DISTINCT FROM '1006' ORDER BY installed_rank") + .getValues(0, String.class)) + .isEqualTo(history); + assertThat(f.count("script_patch_publication_seals")).isZero(); + var current = f.owner().read(request()); + assertThat(current.catalog().catalogEpoch()).isEqualTo(3); + assertThat(current.catalog().digest()).isNotEqualTo(original.catalog().digest()); + assertThat(current.catalog().families()) + .anySatisfy( + family -> { + assertThat(family.familyId()).isEqualTo("script_patch_publication_seals"); + assertThat(family.freshDisposition()).isEqualTo(FreshDisposition.SOURCE_ONLY); + }); + assertThat(f.owner().readExact(current.request())).isEqualTo(current); } } @Test - void bothExactSuccessfulCatalogInstallationsAreRequired() throws Exception { - for (String version : List.of("1004", "1005")) { + void allExactSuccessfulCatalogInstallationsAreRequired() throws Exception { + for (String version : List.of("1004", "1005", "1006")) { for (String change : List.of("success=false", "script='wrong_catalog_installation.sql'")) { try (Fixture f = fixture(null)) { Request read = request(); @@ -723,7 +765,7 @@ List historyRows(boolean excludeNew) { + history + " h" + (excludeNew - ? " WHERE version IS DISTINCT FROM '1004' AND version IS DISTINCT FROM '1005'" + ? " WHERE version IS DISTINCT FROM '1004' AND version IS DISTINCT FROM '1005' AND version IS DISTINCT FROM '1006'" : "") + " ORDER BY installed_rank") .getValues(0, String.class); diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptPatchPublicationSealRepositoryIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptPatchPublicationSealRepositoryIntegrationTest.java new file mode 100644 index 0000000000..aa420ff49d --- /dev/null +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptPatchPublicationSealRepositoryIntegrationTest.java @@ -0,0 +1,303 @@ +package net.firedevops.firemud.automationscripting.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.automationscripting.model.ScriptPatchAlreadySealedException; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = false) +@SuppressWarnings("resource") +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class ScriptPatchPublicationSealRepositoryIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(net.firedevops.firemud.test.TestContainerImages.postgres()); + + private DSLContext dsl; + private String schema; + + @BeforeEach + void migrateSchema() { + schema = "script_patch_seal_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION, "classpath:db/migration/saga") + .table("flyway_schema_history_automation_scripting_service") + .placeholders(java.util.Map.of("serviceSchema", schema)) + .schemas(schema) + .defaultSchema(schema) + .load() + .migrate(); + dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + dsl.execute( + "INSERT INTO script_patch_base_bindings(tenant_id,script_patch_version,base_version_id) VALUES ('23','patch-7',7)"); + } + + @AfterEach + void dropSchema() { + if (schema != null) { + adminDsl().execute("DROP SCHEMA " + schema + " CASCADE"); + schema = null; + } + } + + @Test + void identicalResealIsIdempotentButChangedSnapshotOrBaseBindingFailsClosed() { + var first = + inTransaction( + transactionDsl -> seal(transactionDsl, 7L, "1a".repeat(32), "{\"definitions\":[]}")); + var retry = + inTransaction( + transactionDsl -> seal(transactionDsl, 7L, "1a".repeat(32), "{\"definitions\":[]}")); + + assertThat(retry).isEqualTo(first); + assertThatThrownBy( + () -> + inTransaction( + transactionDsl -> + seal(transactionDsl, 8L, "1a".repeat(32), "{\"definitions\":[]}"))) + .isInstanceOf(ScriptPatchAlreadySealedException.class); + assertThatThrownBy( + () -> + inTransaction( + transactionDsl -> + seal(transactionDsl, 7L, "2b".repeat(32), "{\"definitions\":[1]}"))) + .isInstanceOf(ScriptPatchAlreadySealedException.class); + assertThat( + dsl.fetchValue("SELECT count(*) FROM script_patch_publication_seals WHERE is_sealed")) + .isEqualTo(1L); + } + + @Test + void rowLockSerializesMutationAndSealTransactionsForOnePatch() throws Exception { + CountDownLatch updateHasLock = new CountDownLatch(1); + CountDownLatch releaseUpdate = new CountDownLatch(1); + CountDownLatch sealHasLock = new CountDownLatch(1); + AtomicBoolean sealCompleted = new AtomicBoolean(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future update = + executor.submit( + () -> + inTransaction( + transactionDsl -> { + transactionDsl.execute( + "INSERT INTO scripts (tenant_id, name, version, definition) " + + "VALUES (23, 'alpha', 'patch-7', '{\"v\":1}')"); + updateHasLock.countDown(); + await(releaseUpdate); + return null; + })); + assertThat(updateHasLock.await(5, TimeUnit.SECONDS)).isTrue(); + Future seal = + executor.submit( + () -> + inTransaction( + transactionDsl -> { + var repository = new ScriptPatchPublicationSealRepository(transactionDsl); + repository.seal( + 23L, + 7L, + "patch-7", + 1, + 5, + "1a".repeat(32), + "{\"definitions\":[{\"name\":\"alpha\"}]}"); + sealHasLock.countDown(); + sealCompleted.set(true); + return null; + })); + + assertThat(sealHasLock.await(250, TimeUnit.MILLISECONDS)).isFalse(); + releaseUpdate.countDown(); + update.get(10, TimeUnit.SECONDS); + seal.get(10, TimeUnit.SECONDS); + + assertThat(sealCompleted).isTrue(); + assertThat(dsl.fetchCount(DSL.table("scripts"))).isEqualTo(1); + assertThat( + dsl.fetchValue( + "SELECT snapshot_json FROM script_patch_publication_seals " + + "WHERE tenant_id = 23 AND script_patch_version = 'patch-7'")) + .isEqualTo("{\"definitions\":[{\"name\":\"alpha\"}]}"); + } finally { + releaseUpdate.countDown(); + executor.shutdownNow(); + } + } + + @Test + void sealedPatchRejectsRawDefinitionBindingBaseAndSealMutations() { + dsl.execute( + "INSERT INTO scripts(tenant_id,name,version,base_version_id,definition) VALUES(23,'alpha','patch-7',7,'{}')"); + dsl.execute( + "INSERT INTO script_event_bindings(tenant_id,script_patch_version,base_version_id,event_type,event_schema_version,script_id,binding_id,target_scope_type,target_scope_id) VALUES(23,'patch-7',7,'onEnter','1','alpha','binding','ROOM','')"); + inTransaction(tx -> seal(tx, 7L, "1a".repeat(32), "{}")); + for (String sql : + java.util.List.of( + "UPDATE scripts SET definition='{\"changed\":true}' WHERE tenant_id=23", + "DELETE FROM scripts WHERE tenant_id=23", + "UPDATE script_event_bindings SET enabled=false WHERE tenant_id=23", + "DELETE FROM script_event_bindings WHERE tenant_id=23", + "UPDATE script_patch_base_bindings SET base_version_id=8 WHERE tenant_id='23'", + "DELETE FROM script_patch_base_bindings WHERE tenant_id='23'", + "DELETE FROM script_patch_publication_seals", + "UPDATE script_patch_publication_seals SET snapshot_json='{\"changed\":true}'", + "TRUNCATE TABLE scripts", + "TRUNCATE TABLE script_patch_publication_seals")) { + assertThatThrownBy(() -> dsl.execute(sql)) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + assertThat(dsl.fetchValue("SELECT definition FROM scripts WHERE tenant_id=23")).isEqualTo("{}"); + assertThat( + dsl.fetchValue( + "SELECT snapshot_json FROM script_patch_publication_seals WHERE tenant_id=23")) + .isEqualTo("{}"); + } + + @Test + void sealRequiresPhysicalTransactionAndExactRetainedBase() { + assertThatThrownBy( + () -> new ScriptPatchPublicationSealRepository(dsl).lockForUpdate(23L, "patch-7")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("owned transaction"); + assertThatThrownBy(() -> inTransaction(tx -> seal(tx, 8L, "1a".repeat(32), "{}"))) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("exact retained base"); + assertThat( + dsl.fetchValue("SELECT count(*) FROM script_patch_publication_seals WHERE is_sealed")) + .isEqualTo(0L); + } + + @Test + void actualOwnerCapturesExactStoredRowsAndRequestAndResealsIdentically() { + dsl.execute( + "INSERT INTO scripts(tenant_id,name,version,base_version_id,definition) VALUES(23,'alpha','patch-7',7,'{}')"); + var binding = + net.firedevops.firemud.common.publication.PublicationDigestRequestBinding.patch( + "23", "7", "patch-7", "request-7"); + java.util.function.Function< + DSLContext, net.firedevops.firemud.automationscripting.model.ScriptPatchPublicationSeal> + capture = + tx -> { + var definitions = new ScriptDefinitionRepository(tx); + var bindings = new ScriptEventBindingRepository(tx); + var mapper = new tools.jackson.databind.ObjectMapper(); + var digest = + new net.firedevops.firemud.automationscripting.service.impl + .ScriptDesignDigestServiceImpl(definitions, bindings, mapper); + return new net.firedevops.firemud.automationscripting.service.impl + .ScriptPatchPublicationSealService( + definitions, + bindings, + new ScriptPatchPublicationSealRepository(tx), + digest, + mapper) + .sealSnapshot( + binding, binding.derivedWorkflowIdentity(), binding.requestDigest()); + }; + var first = inTransaction(capture); + assertThat(inTransaction(capture)).isEqualTo(first); + assertThat(first.contentDigestSchemaVersion()).isEqualTo(5); + assertThat(first.snapshotJson()).contains(binding.requestDigest()).contains("alpha"); + assertThat(first.snapshotJson()).doesNotContain("onLoadHandlerIds"); + } + + @Test + void establishedRepeatableReadSnapshotCannotSealOverACommittedWriter() throws Exception { + try (var connection = dataSource(schema).getConnection()) { + connection.setAutoCommit(false); + var oldSnapshot = DSL.using(connection, SQLDialect.POSTGRES); + oldSnapshot.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"); + assertThat(oldSnapshot.fetchValue("SELECT count(*) FROM scripts")).isEqualTo(0L); + dsl.execute( + "INSERT INTO scripts(tenant_id,name,version,base_version_id,definition) VALUES(23,'late','patch-7',7,'{}')"); + assertThat(oldSnapshot.fetchValue("SELECT count(*) FROM scripts")).isEqualTo(0L); + assertThat(dsl.fetchValue("SELECT count(*) FROM scripts")).isEqualTo(1L); + assertThatThrownBy(() -> seal(oldSnapshot, 7L, "1a".repeat(32), "{}")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable READ COMMITTED"); + connection.rollback(); + } + assertThat( + dsl.fetchValue("SELECT count(*) FROM script_patch_publication_seals WHERE is_sealed")) + .isEqualTo(0L); + } + + @Test + void readOnlyTransactionCannotOwnASeal() throws Exception { + try (var connection = dataSource(schema).getConnection()) { + connection.setAutoCommit(false); + var readOnly = DSL.using(connection, SQLDialect.POSTGRES); + readOnly.execute("SET TRANSACTION READ ONLY"); + assertThatThrownBy(() -> seal(readOnly, 7L, "1a".repeat(32), "{}")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable READ COMMITTED"); + connection.rollback(); + } + } + + private static net.firedevops.firemud.automationscripting.model.ScriptPatchPublicationSeal seal( + DSLContext transactionDsl, Long baseVersionId, String digest, String snapshot) { + return new ScriptPatchPublicationSealRepository(transactionDsl) + .seal(23L, baseVersionId, "patch-7", 1, 5, digest, snapshot); + } + + private T inTransaction(java.util.function.Function action) { + return dsl.transactionResult(configuration -> action.apply(DSL.using(configuration))); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("patch update transaction was not released"); + } + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("patch transaction wait was interrupted", ex); + } + } + + private static DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setSchema(schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } + + private static DSLContext adminDsl() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return DSL.using(dataSource, SQLDialect.POSTGRES); + } +} diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginRuntimeStateServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginRuntimeStateServiceImplTest.java index 79a210edf8..c676bb1fc4 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginRuntimeStateServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginRuntimeStateServiceImplTest.java @@ -45,6 +45,9 @@ import org.springframework.transaction.support.SimpleTransactionStatus; class PluginRuntimeStateServiceImplTest { + private static final String ABILITY_SCHEMA_DIGEST = "sha256:" + "a".repeat(64); + private static final String AGGREGATE_DIGEST = "b".repeat(64); + @Test void listsActivePluginVersionsForCurrentRuntimeScope() { PluginRuntimeState enabledMatching = new PluginRuntimeState(); @@ -165,7 +168,7 @@ void createsRuntimeActivationState() { .setBaseVersionId(7L) .setPublicationState( VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED) - .setAbilitySchemaDigest("ability-1") + .setAbilitySchemaDigest(ABILITY_SCHEMA_DIGEST) .setBundleDigest("bundle-1") .setManifestSchemaVersion(1) .setSignerKeyId("signer-1") @@ -188,19 +191,7 @@ void createsRuntimeActivationState() { when(gameSessionClient.getGameInstanceRuntimeState("1", "game-1", "")).thenReturn(runtimeState); when(gameSessionClient.getGameInstanceRuntimeState("1", "game-1", "region-7")) .thenReturn(runtimeState); - when(gameDesignClient.getPublishedReleaseBundle("1", 7L)) - .thenReturn( - GetPublishedReleaseBundleResponse.newBuilder() - .setBundle( - PublishedReleaseBundle.newBuilder() - .setVersionId(7L) - .addParticipantDigests( - ParticipantDigest.newBuilder() - .setParticipantKey("AUTOMATION_SCRIPTING") - .setContentDigest("ability-1") - .build()) - .build()) - .build()); + when(gameDesignClient.getPublishedReleaseBundle("1", 7L)).thenReturn(publishedReleaseBundle()); PluginRuntimeStateService service = new PluginRuntimeStateServiceImpl( repository, @@ -582,19 +573,7 @@ void alreadyEnabledActivationStoresReceiptWithoutChangingRuntimeState() { .build(); when(gameSessionClient.getGameInstanceRuntimeState("1", "game-1", "region-7")) .thenReturn(runtimeState); - when(gameDesignClient.getPublishedReleaseBundle("1", 7L)) - .thenReturn( - GetPublishedReleaseBundleResponse.newBuilder() - .setBundle( - PublishedReleaseBundle.newBuilder() - .setVersionId(7L) - .addParticipantDigests( - ParticipantDigest.newBuilder() - .setParticipantKey("AUTOMATION_SCRIPTING") - .setContentDigest("ability-1") - .build()) - .build()) - .build()); + when(gameDesignClient.getPublishedReleaseBundle("1", 7L)).thenReturn(publishedReleaseBundle()); PluginRuntimeStateServiceImpl service = new PluginRuntimeStateServiceImpl( repository, @@ -1185,7 +1164,7 @@ void rejectsActivationWhenSignerIsRevoked() { .setBaseVersionId(7L) .setPublicationState( VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED) - .setAbilitySchemaDigest("ability-1") + .setAbilitySchemaDigest(ABILITY_SCHEMA_DIGEST) .setBundleDigest("bundle-1") .setManifestSchemaVersion(1) .setSignerKeyId("signer-1") @@ -1232,7 +1211,7 @@ void rejectsActivationWhenComponentPolicyBlocksPlugin() { .setBaseVersionId(7L) .setPublicationState( VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED) - .setAbilitySchemaDigest("ability-1") + .setAbilitySchemaDigest(ABILITY_SCHEMA_DIGEST) .setBundleDigest("bundle-1") .setManifestSchemaVersion(1) .setSignerKeyId("signer-1") @@ -1278,7 +1257,7 @@ void rejectsActivationWhenBaseVersionDoesNotMatchRuntime() { .setBaseVersionId(9L) .setPublicationState( VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED) - .setAbilitySchemaDigest("ability-1") + .setAbilitySchemaDigest(ABILITY_SCHEMA_DIGEST) .setBundleDigest("bundle-1") .setManifestSchemaVersion(1) .setSignerKeyId("signer-1") @@ -1301,19 +1280,7 @@ void rejectsActivationWhenBaseVersionDoesNotMatchRuntime() { when(gameSessionClient.getGameInstanceRuntimeState("1", "game-1", "")).thenReturn(runtimeState); when(gameSessionClient.getGameInstanceRuntimeState("1", "game-1", "region-7")) .thenReturn(runtimeState); - when(gameDesignClient.getPublishedReleaseBundle("1", 7L)) - .thenReturn( - GetPublishedReleaseBundleResponse.newBuilder() - .setBundle( - PublishedReleaseBundle.newBuilder() - .setVersionId(7L) - .addParticipantDigests( - ParticipantDigest.newBuilder() - .setParticipantKey("AUTOMATION_SCRIPTING") - .setContentDigest("ability-1") - .build()) - .build()) - .build()); + when(gameDesignClient.getPublishedReleaseBundle("1", 7L)).thenReturn(publishedReleaseBundle()); PluginRuntimeStateService service = new PluginRuntimeStateServiceImpl( repository, @@ -1396,7 +1363,7 @@ void rejectsActivationWhenAbilitySchemaDigestDoesNotMatchRuntimeVersion() { .setBaseVersionId(7L) .setPublicationState( VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED) - .setAbilitySchemaDigest("ability-plugin") + .setAbilitySchemaDigest("sha256:" + "c".repeat(64)) .setBundleDigest("bundle-1") .setManifestSchemaVersion(1) .setSignerKeyId("signer-1") @@ -1419,6 +1386,62 @@ void rejectsActivationWhenAbilitySchemaDigestDoesNotMatchRuntimeVersion() { when(gameSessionClient.getGameInstanceRuntimeState("1", "game-1", "")).thenReturn(runtimeState); when(gameSessionClient.getGameInstanceRuntimeState("1", "game-1", "region-7")) .thenReturn(runtimeState); + when(gameDesignClient.getPublishedReleaseBundle("1", 7L)).thenReturn(publishedReleaseBundle()); + PluginRuntimeStateService service = + new PluginRuntimeStateServiceImpl( + repository, + eventRepository, + gameDesignClient, + gameSessionClient, + Mockito.mock(ScriptScheduleInstanceService.class)); + + assertThatThrownBy( + () -> + service.setActiveVersion( + new PluginRuntimeStateService.ActivationCommand( + "1", "game-1", "plugin-1", "plugin-v1", "req-1", "admin", "activation"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage( + "PLUGIN_ABILITY_SCHEMA_MISMATCH: plugin ability schema digest does not match runtime version"); + } + + @Test + void rejectsActivationWithoutMutationWhenOnlyAggregateAbilityEvidenceExists() { + PluginRuntimeState existing = activePluginState(); + existing.setPluginActivationEpoch(4L); + existing.setLifecycleRevision(9L); + PluginRuntimeState expected = activePluginState(); + expected.setPluginActivationEpoch(4L); + expected.setLifecycleRevision(9L); + PluginRuntimeStateRepository repository = Mockito.mock(PluginRuntimeStateRepository.class); + PluginRuntimeEventRepository eventRepository = Mockito.mock(PluginRuntimeEventRepository.class); + PluginRuntimeRequestHistoryRepository historyRepository = + Mockito.mock(PluginRuntimeRequestHistoryRepository.class); + GameDesignControlPlaneClient gameDesignClient = + Mockito.mock(GameDesignControlPlaneClient.class); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + ScriptScheduleInstanceService scheduleService = + Mockito.mock(ScriptScheduleInstanceService.class); + PluginActivationPreflightService preflightService = + Mockito.mock(PluginActivationPreflightService.class); + when(repository.findByTenantIdAndGameInstanceIdAndPluginId("1", "game-1", "plugin-1")) + .thenReturn(Optional.of(existing)); + when(gameDesignClient.getPublishedPluginVersion("1", "plugin-1", "plugin-v1")) + .thenReturn( + publishedPluginVersion( + PluginComponentPolicyDecision.PLUGIN_COMPONENT_POLICY_DECISION_ALLOWED, false)); + when(gameSessionClient.getGameInstanceRuntimeState("1", "game-1", "region-7")) + .thenReturn( + GetGameInstanceRuntimeStateResponse.newBuilder() + .setRuntimeState( + GameInstanceRuntimeState.newBuilder() + .setTenantId("1") + .setGameInstanceId("game-1") + .setRegionId("region-7") + .setRegionEpoch(12L) + .setRuntimeVersionId("7")) + .build()); when(gameDesignClient.getPublishedReleaseBundle("1", 7L)) .thenReturn( GetPublishedReleaseBundleResponse.newBuilder() @@ -1428,9 +1451,10 @@ void rejectsActivationWhenAbilitySchemaDigestDoesNotMatchRuntimeVersion() { .addParticipantDigests( ParticipantDigest.newBuilder() .setParticipantKey("AUTOMATION_SCRIPTING") - .setContentDigest("ability-runtime") - .build()) - .build()) + .setScopeValue("7") + .setAppliedCommitId("commit-7") + .setContentDigest(ABILITY_SCHEMA_DIGEST) + .setDigestSchemaVersion(1))) .build()); PluginRuntimeStateService service = new PluginRuntimeStateServiceImpl( @@ -1438,7 +1462,9 @@ void rejectsActivationWhenAbilitySchemaDigestDoesNotMatchRuntimeVersion() { eventRepository, gameDesignClient, gameSessionClient, - Mockito.mock(ScriptScheduleInstanceService.class)); + scheduleService, + preflightService, + historyRepository); assertThatThrownBy( () -> @@ -1446,8 +1472,12 @@ void rejectsActivationWhenAbilitySchemaDigestDoesNotMatchRuntimeVersion() { new PluginRuntimeStateService.ActivationCommand( "1", "game-1", "plugin-1", "plugin-v1", "req-1", "admin", "activation"))) .isInstanceOf(IllegalArgumentException.class) - .hasMessage( - "PLUGIN_ABILITY_SCHEMA_MISMATCH: plugin ability schema digest does not match runtime version"); + .hasMessage("PLUGIN_ABILITY_SCHEMA_MISMATCH: runtime ability schema digest is unavailable"); + + assertThat(existing).usingRecursiveComparison().isEqualTo(expected); + Mockito.verify(repository, Mockito.never()).save(Mockito.any()); + Mockito.verify(historyRepository, Mockito.never()).insertOrGet(Mockito.any()); + Mockito.verifyNoInteractions(eventRepository, scheduleService, preflightService); } @Test @@ -2194,19 +2224,7 @@ void activationAlreadyAppliedFromFreshRequestIsMutationFree() { when(gameSessionClient.getGameInstanceRuntimeState("1", "game-1", "")).thenReturn(runtimeState); when(gameSessionClient.getGameInstanceRuntimeState("1", "game-1", "region-7")) .thenReturn(runtimeState); - when(gameDesignClient.getPublishedReleaseBundle("1", 7L)) - .thenReturn( - GetPublishedReleaseBundleResponse.newBuilder() - .setBundle( - PublishedReleaseBundle.newBuilder() - .setVersionId(7L) - .addParticipantDigests( - ParticipantDigest.newBuilder() - .setParticipantKey("AUTOMATION_SCRIPTING") - .setContentDigest("ability-1") - .build()) - .build()) - .build()); + when(gameDesignClient.getPublishedReleaseBundle("1", 7L)).thenReturn(publishedReleaseBundle()); PluginRuntimeStateService service = new PluginRuntimeStateServiceImpl( repository, @@ -2351,6 +2369,22 @@ private static PluginRuntimeRequestHistory requestHistory( return history; } + private static GetPublishedReleaseBundleResponse publishedReleaseBundle() { + return GetPublishedReleaseBundleResponse.newBuilder() + .setBundle( + PublishedReleaseBundle.newBuilder() + .setVersionId(7L) + .addParticipantDigests( + ParticipantDigest.newBuilder() + .setParticipantKey("GAME_LOGIC") + .setScopeValue("7") + .setAppliedCommitId("commit-7") + .setContentDigest(AGGREGATE_DIGEST) + .setDigestSchemaVersion(1) + .setAbilitySchemaDigest(ABILITY_SCHEMA_DIGEST))) + .build(); + } + private static GetPublishedPluginVersionResponse publishedPluginVersion( PluginComponentPolicyDecision componentPolicyDecision, boolean signerRevoked) { return GetPublishedPluginVersionResponse.newBuilder() @@ -2361,7 +2395,7 @@ private static GetPublishedPluginVersionResponse publishedPluginVersion( .setPluginVersionId("plugin-v1") .setBaseVersionId(7L) .setPublicationState(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED) - .setAbilitySchemaDigest("ability-1") + .setAbilitySchemaDigest(ABILITY_SCHEMA_DIGEST) .setBundleDigest("bundle-1") .setManifestSchemaVersion(1) .setSignerKeyId("signer-1") diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PublishedAbilitySchemaEvidenceTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PublishedAbilitySchemaEvidenceTest.java new file mode 100644 index 0000000000..8da60fe9fb --- /dev/null +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PublishedAbilitySchemaEvidenceTest.java @@ -0,0 +1,66 @@ +package net.firedevops.firemud.automationscripting.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.stream.Stream; +import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +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; + +class PublishedAbilitySchemaEvidenceTest { + private static final String ABILITY_DIGEST = "sha256:" + "a".repeat(64); + private static final ParticipantDigest OWNER = + ParticipantDigest.newBuilder() + .setParticipantKey("GAME_LOGIC") + .setScopeValue("7") + .setAppliedCommitId("commit-1") + .setDigestSchemaVersion(1) + .setContentDigest("b".repeat(64)) + .setAbilitySchemaDigest(ABILITY_DIGEST) + .build(); + private static final PublishedReleaseBundle FULL_BUNDLE = bundle(OWNER).build(); + + @Test + void readsTheDedicatedDigestForTheExactBaseVersion() { + assertThat(PublishedAbilitySchemaEvidence.read(FULL_BUNDLE, 7L)).contains(ABILITY_DIGEST); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("unavailableEvidence") + void refusesUnavailableEvidence(String description, PublishedReleaseBundle bundle) { + assertThat(PublishedAbilitySchemaEvidence.read(bundle, 7L)).as(description).isEmpty(); + } + + private static Stream unavailableEvidence() { + return Stream.of( + Arguments.of("different version", FULL_BUNDLE.toBuilder().setVersionId(8L).build()), + Arguments.of("script-only bundle", FULL_BUNDLE.toBuilder().setIsScriptOnly(true).build()), + Arguments.of( + "different scope", bundle(OWNER.toBuilder().setScopeValue("8").build()).build()), + Arguments.of( + "unsupported schema", + bundle(OWNER.toBuilder().setDigestSchemaVersion(2).build()).build()), + Arguments.of( + "missing commit", bundle(OWNER.toBuilder().clearAppliedCommitId().build()).build()), + Arguments.of( + "missing dedicated digest", + bundle(OWNER.toBuilder().clearAbilitySchemaDigest().build()).build()), + Arguments.of( + "invalid dedicated digest", + bundle(OWNER.toBuilder().setAbilitySchemaDigest("not-a-digest").build()).build()), + Arguments.of( + "duplicate Game Logic", FULL_BUNDLE.toBuilder().addParticipantDigests(OWNER).build()), + Arguments.of( + "another participant claims dedicated evidence", + FULL_BUNDLE.toBuilder() + .addParticipantDigests(OWNER.toBuilder().setParticipantKey("AUTOMATION_SCRIPTING")) + .build())); + } + + private static PublishedReleaseBundle.Builder bundle(ParticipantDigest owner) { + return PublishedReleaseBundle.newBuilder().setVersionId(7L).addParticipantDigests(owner); + } +} diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptDesignDigestServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptDesignDigestServiceImplTest.java index 5c7e08a6ec..a239da1301 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptDesignDigestServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptDesignDigestServiceImplTest.java @@ -31,6 +31,115 @@ void setUp() { when(repository.findScriptPatchBaseVersionId("1", "patch-1")).thenReturn(Optional.of(1L)); } + @Test + void capturedSnapshotMatchesLiveDigestWithoutReadingMutableRowsAgain() { + var definition = snapshotDefinition("alpha", 1L, "patch-1"); + when(repository.findByTenantIdAndScriptVersionOrderByNameAsc(1L, "patch-1")) + .thenReturn(List.of(definition)); + when(bindingRepository + .findByTenantIdAndScriptPatchVersionOrderByEventTypeAscEventSchemaVersionAscPriorityAscScriptIdAsc( + 1L, "patch-1")) + .thenReturn(List.of()); + var live = service.getDraftDesignDigestForScriptPatch("1", 1L, "patch-1"); + org.mockito.Mockito.clearInvocations(repository, bindingRepository); + assertEquals( + live, + service.getDraftDesignDigestForScriptPatchSnapshot( + "1", 1L, "patch-1", List.of(definition), List.of())); + verifyNoInteractions(repository, bindingRepository); + } + + @Test + void capturedSnapshotRejectsForeignOrDuplicateRows() { + var alpha = snapshotDefinition("alpha", 1L, "patch-1"); + for (var invalid : + List.of( + snapshotDefinition("alpha", 2L, "patch-1"), + snapshotDefinition("alpha", 1L, "other"), + alpha)) { + assertThrows( + IllegalArgumentException.class, + () -> + service.getDraftDesignDigestForScriptPatchSnapshot( + "1", 1L, "patch-1", List.of(alpha, invalid), List.of())); + } + alpha.setBaseVersionId(2L); + assertThrows( + IllegalArgumentException.class, + () -> + service.getDraftDesignDigestForScriptPatchSnapshot( + "1", 1L, "patch-1", List.of(alpha), List.of())); + verifyNoInteractions(repository, bindingRepository); + } + + @Test + void capturedSnapshotRejectsForeignBindingsAndMissingPatch() { + var definition = snapshotDefinition("alpha", 1L, "patch-1"); + var binding = new ScriptEventBinding(); + binding.setTenantId(2L); + binding.setScriptPatchVersion("patch-1"); + binding.setBaseVersionId(1L); + assertThrows( + IllegalArgumentException.class, + () -> + service.getDraftDesignDigestForScriptPatchSnapshot( + "1", 1L, "patch-1", List.of(definition), List.of(binding))); + binding.setTenantId(1L); + binding.setScriptPatchVersion("other"); + assertThrows( + IllegalArgumentException.class, + () -> + service.getDraftDesignDigestForScriptPatchSnapshot( + "1", 1L, "patch-1", List.of(definition), List.of(binding))); + assertThrows( + IllegalArgumentException.class, + () -> + service.getDraftDesignDigestForScriptPatchSnapshot( + "1", 1L, "patch-1", List.of(), List.of())); + verifyNoInteractions(repository, bindingRepository); + } + + @Test + void capturedSnapshotRetainsOwnerDefinitionOrderAndCanonicalBindingOrder() { + var definitions = + List.of( + snapshotDefinition("éclair", 1L, "patch-1"), + snapshotDefinition("zebra", 1L, "patch-1")); + var first = binding("binding-a"); + var second = binding("binding-b"); + when(repository.findByTenantIdAndScriptVersionOrderByNameAsc(1L, "patch-1")) + .thenReturn(definitions); + when(bindingRepository + .findByTenantIdAndScriptPatchVersionOrderByEventTypeAscEventSchemaVersionAscPriorityAscScriptIdAsc( + 1L, "patch-1")) + .thenReturn(List.of(first, second)); + var live = service.getDraftDesignDigestForScriptPatch("1", 1L, "patch-1"); + assertEquals( + "92e4200157ea21a575680e67798570863d1a6539e6a7889ef214935bf4d1b83e", live.contentDigest()); + org.mockito.Mockito.clearInvocations(repository, bindingRepository); + assertEquals( + live, + service.getDraftDesignDigestForScriptPatchSnapshot( + "1", 1L, "patch-1", definitions, List.of(second, first))); + first.setBaseVersionId(2L); + assertThrows( + IllegalArgumentException.class, + () -> + service.getDraftDesignDigestForScriptPatchSnapshot( + "1", 1L, "patch-1", definitions, List.of(first))); + verifyNoInteractions(repository, bindingRepository); + } + + private static ScriptDefinition snapshotDefinition(String name, long tenantId, String patch) { + var definition = new ScriptDefinition(); + definition.setTenantId(tenantId); + definition.setName(name); + definition.setScriptVersion(patch); + definition.setBaseVersionId(1L); + definition.setDefinition("return 1"); + return definition; + } + @Test void getDraftDesignDigestReturnsStablePatchDigest() { ScriptDefinition one = new ScriptDefinition(); diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPublicationSealServiceTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPublicationSealServiceTest.java new file mode 100644 index 0000000000..7f1dafc014 --- /dev/null +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPublicationSealServiceTest.java @@ -0,0 +1,166 @@ +package net.firedevops.firemud.automationscripting.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Optional; +import net.firedevops.firemud.automationscripting.entity.ScriptDefinition; +import net.firedevops.firemud.automationscripting.entity.ScriptEventBinding; +import net.firedevops.firemud.automationscripting.model.ScriptPatchPublicationSeal; +import net.firedevops.firemud.automationscripting.repository.ScriptDefinitionRepository; +import net.firedevops.firemud.automationscripting.repository.ScriptEventBindingRepository; +import net.firedevops.firemud.automationscripting.repository.ScriptPatchPublicationSealRepository; +import net.firedevops.firemud.automationscripting.service.ScriptDesignDigestService; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; +import tools.jackson.databind.ObjectMapper; + +class ScriptPatchPublicationSealServiceTest { + private ScriptDefinitionRepository definitions; + private ScriptEventBindingRepository bindings; + private ScriptPatchPublicationSealRepository seals; + private ScriptDesignDigestService digestService; + private ObjectMapper objectMapper; + private ScriptPatchPublicationSealService service; + + @BeforeEach + void setUp() { + definitions = Mockito.mock(ScriptDefinitionRepository.class); + bindings = Mockito.mock(ScriptEventBindingRepository.class); + seals = Mockito.mock(ScriptPatchPublicationSealRepository.class); + digestService = Mockito.mock(ScriptDesignDigestService.class); + objectMapper = new ObjectMapper(); + service = + new ScriptPatchPublicationSealService( + definitions, bindings, seals, digestService, objectMapper); + when(definitions.findScriptPatchBaseVersionId("23", "patch-7")).thenReturn(Optional.of(6L)); + when(seals.lockForUpdate(23L, "patch-7")) + .thenReturn( + new ScriptPatchPublicationSealRepository.PatchLock( + 23L, "patch-7", false, null, null, null, null, null, null)); + } + + @Test + void sealsBoundContentWithoutClaimingAReadinessManifest() throws Exception { + ScriptDefinition definition = new ScriptDefinition(); + definition.setTenantId(23L); + definition.setName("alpha"); + definition.setScriptVersion("patch-7"); + definition.setDefinition("{\"say\":\"hello\"}"); + ScriptEventBinding binding = new ScriptEventBinding(); + binding.setTenantId(23L); + binding.setScriptPatchVersion("patch-7"); + binding.setEventType("onCommand"); + binding.setEventSchemaVersion("v1"); + binding.setScriptId("alpha"); + binding.setBindingId("greet"); + binding.setTargetScopeType("GLOBAL"); + binding.setTargetScopeId(""); + binding.setPriority(2); + binding.setPriorityTag("normal"); + binding.setEnabled(true); + when(definitions.findByTenantIdAndScriptVersionOrderByNameAsc(23L, "patch-7")) + .thenReturn(List.of(definition)); + when(bindings + .findByTenantIdAndScriptPatchVersionOrderByEventTypeAscEventSchemaVersionAscPriorityAscScriptIdAsc( + 23L, "patch-7")) + .thenReturn(List.of(binding)); + when(digestService.getDraftDesignDigestForScriptPatchSnapshot( + "23", 6L, "patch-7", List.of(definition), List.of(binding))) + .thenReturn( + new ScriptDesignDigestService.ScriptDraftDesignDigest( + "23", "patch-7", 6L, "script-patch:patch-7", "ab".repeat(32), 5)); + when(seals.seal(eq(23L), eq(6L), eq("patch-7"), eq(1), eq(5), eq("ab".repeat(32)), anyString())) + .thenAnswer( + invocation -> + new ScriptPatchPublicationSeal( + invocation.getArgument(0), + invocation.getArgument(1), + invocation.getArgument(2), + invocation.getArgument(3), + invocation.getArgument(4), + invocation.getArgument(5), + invocation.getArgument(6), + OffsetDateTime.now())); + + ScriptPatchPublicationSeal seal = + service.sealSnapshot( + binding(), binding().derivedWorkflowIdentity(), binding().requestDigest()); + + assertThat(seal.baseVersionId()).isEqualTo(6L); + ArgumentCaptor snapshot = ArgumentCaptor.forClass(String.class); + verify(seals) + .seal( + eq(23L), eq(6L), eq("patch-7"), eq(1), eq(5), eq("ab".repeat(32)), snapshot.capture()); + var json = objectMapper.readTree(snapshot.getValue()); + assertThat(json.get("tenantId").asText()).isEqualTo("23"); + assertThat(json.get("baseVersionId").asLong()).isEqualTo(6L); + assertThat(json.get("scriptPatchVersion").asText()).isEqualTo("patch-7"); + assertThat(json.get("contentDigestSchemaVersion").asInt()).isEqualTo(5); + assertThat(json.get("contentDigest").asText()).isEqualTo("ab".repeat(32)); + assertThat(json.get("definitions").get(0).get("definition").asText()) + .isEqualTo("{\"say\":\"hello\"}"); + assertThat(json.get("eventBindings").get(0).get("bindingId").asText()).isEqualTo("greet"); + assertThat(json.has("onLoadHandlerIds")).isFalse(); + assertThat(json.get("requestDigest").asText()).isEqualTo(binding().requestDigest()); + } + + @Test + void emptyPatchContentDoesNotInventZeroHandlerReadiness() throws Exception { + when(definitions.findByTenantIdAndScriptVersionOrderByNameAsc(23L, "patch-7")) + .thenReturn(List.of()); + when(bindings + .findByTenantIdAndScriptPatchVersionOrderByEventTypeAscEventSchemaVersionAscPriorityAscScriptIdAsc( + 23L, "patch-7")) + .thenReturn(List.of()); + when(digestService.getDraftDesignDigestForScriptPatchSnapshot( + "23", 6L, "patch-7", List.of(), List.of())) + .thenReturn( + new ScriptDesignDigestService.ScriptDraftDesignDigest( + "23", "patch-7", 6L, "script-patch:patch-7", "cd".repeat(32), 5)); + when(seals.seal(eq(23L), eq(6L), eq("patch-7"), eq(1), eq(5), eq("cd".repeat(32)), anyString())) + .thenReturn( + new ScriptPatchPublicationSeal( + 23L, 6L, "patch-7", 1, 5, "cd".repeat(32), "{}", OffsetDateTime.now())); + + service.sealSnapshot(binding(), binding().derivedWorkflowIdentity(), binding().requestDigest()); + + ArgumentCaptor snapshot = ArgumentCaptor.forClass(String.class); + verify(seals) + .seal( + eq(23L), eq(6L), eq("patch-7"), eq(1), eq(5), eq("cd".repeat(32)), snapshot.capture()); + assertThat(objectMapper.readTree(snapshot.getValue()).has("onLoadHandlerIds")).isFalse(); + } + + private static PublicationDigestRequestBinding binding() { + return PublicationDigestRequestBinding.patch("23", "6", "patch-7", "request-7"); + } + + @Test + void refusesChangedRequestBeforeReadingOrSealing() { + org.assertj.core.api.Assertions.assertThatThrownBy( + () -> service.sealSnapshot(binding(), "wrong", binding().requestDigest())) + .isInstanceOf(IllegalArgumentException.class); + Mockito.verifyNoInteractions(seals); + } + + @Test + void refusesUnretainedBaseEvenForEmptyPatch() { + when(definitions.findScriptPatchBaseVersionId("23", "patch-7")).thenReturn(Optional.empty()); + org.assertj.core.api.Assertions.assertThatThrownBy( + () -> + service.sealSnapshot( + binding(), binding().derivedWorkflowIdentity(), binding().requestDigest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("retained_base"); + Mockito.verifyNoInteractions(bindings, digestService); + } +} diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImplTest.java index ae0417495d..55292adaec 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImplTest.java @@ -78,6 +78,8 @@ import org.springframework.transaction.support.TransactionTemplate; class ScriptWorkItemServiceImplTest { + private static final String ABILITY_SCHEMA_DIGEST = "sha256:" + "a".repeat(64); + @Test void replayAuthorityPreflightIsOutsideTheTransactionAndDurablePhaseGetsItsOwn() { try (AnnotationConfigApplicationContext context = @@ -531,20 +533,26 @@ private static GameDesignControlPlaneClient gameDesignClient() { .build()) .build()); when(client.getPublishedReleaseBundle(Mockito.anyString(), Mockito.eq(7L))) - .thenReturn( - GetPublishedReleaseBundleResponse.newBuilder() - .setBundle( - PublishedReleaseBundle.newBuilder() - .addParticipantDigests( - ParticipantDigest.newBuilder() - .setParticipantKey("AUTOMATION_SCRIPTING") - .setContentDigest("ability-1") - .build()) - .build()) - .build()); + .thenReturn(releaseBundle(7L)); return client; } + private static GetPublishedReleaseBundleResponse releaseBundle(long versionId) { + return GetPublishedReleaseBundleResponse.newBuilder() + .setBundle( + PublishedReleaseBundle.newBuilder() + .setVersionId(versionId) + .addParticipantDigests( + ParticipantDigest.newBuilder() + .setParticipantKey("GAME_LOGIC") + .setScopeValue(Long.toString(versionId)) + .setAppliedCommitId("commit-1") + .setDigestSchemaVersion(1) + .setContentDigest("b".repeat(64)) + .setAbilitySchemaDigest(ABILITY_SCHEMA_DIGEST))) + .build(); + } + private static ScriptPatchReadinessProjectionService readinessProjectionService() { return Mockito.mock(ScriptPatchReadinessProjectionService.class); } @@ -1957,8 +1965,9 @@ void doesNotScanOrDeleteDeadLettersForAgeOrRowCap() { verify(workItemRepository, never()).deleteOldestByStatus(Mockito.anyString(), Mockito.anyInt()); } - @Test - void summarizesPatchStatusFromReadinessProjection() { + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void summarizesPatchStatusWithOnlyDedicatedAbilitySchemaEvidence(boolean hasOwnerEvidence) { ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); ScriptPatchReadinessProjectionService readinessProjectionService = @@ -1975,6 +1984,19 @@ void summarizesPatchStatusFromReadinessProjection() { "", 200L))); GameDesignControlPlaneClient gameDesignControlPlaneClient = gameDesignClient(); + if (!hasOwnerEvidence) { + when(gameDesignControlPlaneClient.getPublishedReleaseBundle("1", 7L)) + .thenReturn( + GetPublishedReleaseBundleResponse.newBuilder() + .setBundle( + PublishedReleaseBundle.newBuilder() + .setVersionId(7L) + .addParticipantDigests( + ParticipantDigest.newBuilder() + .setParticipantKey("AUTOMATION_SCRIPTING") + .setContentDigest(ABILITY_SCHEMA_DIGEST))) + .build()); + } ScriptWorkItemService service = service( workItemRepository, @@ -1998,7 +2020,8 @@ void summarizesPatchStatusFromReadinessProjection() { assertThat(status.get().statusReason()).isEqualTo("tenant_readiness_running"); assertThat(status.get().lastChangedAtMs()).isEqualTo(200L); assertThat(status.get().baseVersionId()).isEqualTo(7L); - assertThat(status.get().abilitySchemaDigest()).isEqualTo("ability-1"); + assertThat(status.get().abilitySchemaDigest()) + .isEqualTo(hasOwnerEvidence ? ABILITY_SCHEMA_DIGEST : ""); assertThat(status.get().publication().versionId()).isEqualTo(17L); verify(gameDesignControlPlaneClient).getPublishedScriptPatchVersion("1", 7L, "patch-1"); } @@ -3283,17 +3306,7 @@ void listDeadLettersUsesTheWorkItemsRetainedPatchBase() { .build()) .build()); when(gameDesignControlPlaneClient.getPublishedReleaseBundle("1", 11L)) - .thenReturn( - GetPublishedReleaseBundleResponse.newBuilder() - .setBundle( - PublishedReleaseBundle.newBuilder() - .addParticipantDigests( - ParticipantDigest.newBuilder() - .setParticipantKey("AUTOMATION_SCRIPTING") - .setContentDigest("ability-1") - .build()) - .build()) - .build()); + .thenReturn(releaseBundle(11L)); ScriptWorkItemService service = service( workItemRepository, diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java index f668dadd08..26b7cf99a0 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java @@ -3,9 +3,11 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.ArrayList; import java.util.List; @@ -21,6 +23,50 @@ class AccountSecurityStateAuthorityEventV1CodecTest { private static final String LARGE_COUNTER = "9223372036854775807"; private static final ObjectMapper JSON = new ObjectMapper(); + private static final String ORIGINAL_DIGEST = + "sha256:6e6b82b81006e447301262b666825022462f4298a8b3fc0d44ce4a73895b3374"; + private static final String CANONICAL_PREIMAGE = + "{\"accountAuthorityGeneration\":\"2\",\"accountId\":\"" + + ACCOUNT_ID + + "\",\"accountSecurityCutoff\":{\"accountAuthorityGeneration\":\"2\"," + + "\"outboxSequence\":\"1\",\"outboxStreamKey\":\"" + + STREAM + + "\"},\"accountState\":{\"emailVerified\":true,\"globalRoles\":[]," + + "\"lifecycleState\":\"ACTIVE\",\"loginAuthModes\":[\"EMAIL_OTP\",\"PASSWORD\"]}," + + "\"eventId\":\"account-security-state-event-v1:" + + REQUEST_ID + + "\",\"eventType\":\"ACCOUNT_SECURITY_STATE_CHANGED\"," + + "\"mutationKinds\":[\"EMAIL_LOGIN_ELIGIBILITY_CHANGED\",\"LOGIN_AUTH_MODES_CHANGED\"]," + + "\"outboxSequence\":\"1\",\"outboxStreamKey\":\"" + + STREAM + + "\",\"requestId\":\"" + + REQUEST_ID + + "\",\"schemaVersion\":\"account-auth-account-security-state-event/v1\"," + + "\"sourceScope\":\"account/" + + ACCOUNT_ID + + "\",\"sourceVersion\":\"2\"}"; + private static final String CANONICAL_WIRE = + CANONICAL_PREIMAGE.replace( + "\"eventId\":", "\"eventDigest\":\"" + ORIGINAL_DIGEST + "\",\"eventId\":"); + + @Test + void fixedCombinedFamilyVectorSealsAndVerifiesExactCanonicalBytesAndHash() throws Exception { + Map preimage = JSON.readValue(CANONICAL_PREIMAGE, new TypeReference<>() {}); + var sealed = AccountSecurityStateAuthorityEventV1Codec.seal(preimage); + var verified = AccountSecurityStateAuthorityEventV1Codec.verify(CANONICAL_WIRE); + assertThat(sealed.eventDigest()).isEqualTo(ORIGINAL_DIGEST); + assertThat(sealed.canonicalJson()).isEqualTo(CANONICAL_WIRE); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo(CANONICAL_WIRE.getBytes(StandardCharsets.UTF_8)); + assertThat(verified.accountId()).isEqualTo(ACCOUNT_ID); + assertThat(verified.requestId()).isEqualTo(REQUEST_ID); + assertThat(verified.sourceScope()).isEqualTo("account/" + ACCOUNT_ID); + assertThat(verified.accountState().globalRoles()).isEmpty(); + assertThat(verified.mutationKinds()) + .containsExactly("EMAIL_LOGIN_ELIGIBILITY_CHANGED", "LOGIN_AUTH_MODES_CHANGED"); + assertThat(verified.accountSecurityCutoff().outboxSequence()).isEqualTo("1"); + } + @Test void sealsCompleteSecurityStateAndAllowsEmptyGlobalRoles() throws Exception { var sealed = AccountSecurityStateAuthorityEventV1Codec.seal(preimage(LARGE_COUNTER)); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftTerminalReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftTerminalReadClientMtlsTest.java index e566d0664d..b8a9180950 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftTerminalReadClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftTerminalReadClientMtlsTest.java @@ -3,7 +3,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import io.grpc.BindableService; +import io.grpc.Metadata; import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; import io.grpc.Status; import io.grpc.StatusRuntimeException; import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; @@ -26,6 +31,7 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; @@ -40,11 +46,12 @@ import net.firedevops.firemud.worldmanagement.v1.ReadWorldDraftTerminalOutcomeRequest; import net.firedevops.firemud.worldmanagement.v1.ReadWorldDraftTerminalOutcomeResponse; import net.firedevops.firemud.worldmanagement.v1.WorldDraftTerminalReadServiceGrpc; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -/** Physical mTLS loopback proof for large exact terminal-read responses from both owners. */ +/** Physical mTLS loopback proof for exact terminal-read responses and server workload refusal. */ class DraftTerminalReadClientMtlsTest { private static final int MAX_KEYTOOL_FAILURE_OUTPUT_BYTES = 64 * 1024; private static final long KEYTOOL_TIMEOUT_SECONDS = 30L; @@ -52,6 +59,10 @@ class DraftTerminalReadClientMtlsTest { private static final String NAMESPACE = "test"; private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; private static final String WORLD_URI = "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String OTHER_NAMESPACE_GAME_DESIGN_URI = + "spiffe://firemud/ns/other-test/sa/game-design-service"; + private static final String OTHER_NAMESPACE_WORLD_URI = + "spiffe://firemud/ns/other-test/sa/world-management-service"; private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; private static final String STORE_PASSWORD = "test-only-store-password"; @@ -65,19 +76,14 @@ static void createTrustedWorkloadCertificates() throws Exception { @Test void gameDesignClientAcceptsBoundedResponseAboveOldFourMiBTransportLimit() throws Exception { - var base = AuthoringFixtures.freshGraphRequest(); - var request = - new GameDesignDraftTerminalReadEvidence.Request( - 1, - NAMESPACE, - UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), - base.originalAccountBinding()); + var request = gameDesignRequest(); var readback = largeAbort(request.accountBinding(), Owner.GAME_DESIGN, request.originalAccountBinding()); var response = GameDesignDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(readback)); AtomicReference received = new AtomicReference<>(); - try (TransportServer server = startGameDesignServer(response, received); + try (TransportServer server = + startGameDesignServer(pki.gameDesignServer(), response, received); GameDesignDraftTerminalReadClient client = gameDesignClient(server.port())) { client.init(); var configuredStub = gameDesignStub(client); @@ -97,6 +103,7 @@ void gameDesignClientAcceptsBoundedResponseAboveOldFourMiBTransportLimit() throw var actual = client.read(request); assertThat(actual.ownerReadback().orElseThrow().canonicalBytes()) .containsExactly(readback.canonicalBytes()); + assertThat(server.applicationMetadataCalls()).hasValue(2); assertThat(received.get()).isEqualTo(GameDesignDraftTerminalReadGrpcCodec.toRequest(request)); assertThat(configuredStub.getCallOptions().getMaxInboundMessageSize()) .isEqualTo(DraftTerminalReadGrpcLimits.MAX_RESPONSE_WIRE_BYTES); @@ -111,7 +118,7 @@ void worldClientAcceptsBoundedResponseAboveOldFourMiBTransportLimit() throws Exc var response = WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(readback)); AtomicReference received = new AtomicReference<>(); - try (TransportServer server = startWorldServer(response, received); + try (TransportServer server = startWorldServer(pki.worldServer(), response, received); WorldDraftTerminalReadClient client = worldClient(server.port())) { client.init(); var configuredStub = worldStub(client); @@ -131,12 +138,68 @@ void worldClientAcceptsBoundedResponseAboveOldFourMiBTransportLimit() throws Exc var actual = client.read(request); assertThat(actual.ownerReadback().orElseThrow().canonicalBytes()) .containsExactly(readback.canonicalBytes()); + assertThat(server.applicationMetadataCalls()).hasValue(2); assertThat(received.get()).isEqualTo(WorldDraftTerminalReadGrpcCodec.toRequest(request)); assertThat(configuredStub.getCallOptions().getMaxInboundMessageSize()) .isEqualTo(DraftTerminalReadGrpcLimits.MAX_RESPONSE_WIRE_BYTES); } } + @Test + void gameDesignClientWithholdsMetadataAndBodyFromTrustedWrongWorkloadAndNamespace() + throws Exception { + var request = gameDesignRequest(); + var response = GameDesignDraftTerminalReadGrpcCodec.toResponse(request, Optional.empty()); + for (TestIdentity identity : List.of(pki.worldServer(), pki.otherNamespaceGameDesignServer())) { + AtomicReference received = new AtomicReference<>(); + try (TransportServer server = startGameDesignServer(identity, response, received); + GameDesignDraftTerminalReadClient client = gameDesignClient(server.port())) { + client.init(); + assertRequestWithheld(identity, server, received, () -> client.read(request)); + } + } + } + + @Test + void worldClientWithholdsMetadataAndBodyFromTrustedWrongWorkloadAndNamespace() throws Exception { + var request = AuthoringFixtures.freshGraphRequest(); + var response = WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.empty()); + for (TestIdentity identity : List.of(pki.gameDesignServer(), pki.otherNamespaceWorldServer())) { + AtomicReference received = new AtomicReference<>(); + try (TransportServer server = startWorldServer(identity, response, received); + WorldDraftTerminalReadClient client = worldClient(server.port())) { + client.init(); + assertRequestWithheld(identity, server, received, () -> client.read(request)); + } + } + } + + private static void assertRequestWithheld( + TestIdentity identity, + TransportServer server, + AtomicReference received, + ThrowingCallable read) { + assertThatThrownBy(read) + .as(identity.alias()) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> { + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(failure.getStatus().getDescription()) + .isEqualTo("Request requires the exact authenticated server workload identity"); + }); + assertThat(server.applicationMetadataCalls()).as(identity.alias()).hasValue(0); + assertThat(received.get()).as(identity.alias()).isNull(); + } + + private static GameDesignDraftTerminalReadEvidence.Request gameDesignRequest() throws Exception { + return new GameDesignDraftTerminalReadEvidence.Request( + 1, + NAMESPACE, + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + AuthoringFixtures.freshGraphRequest().originalAccountBinding()); + } + private static DraftAuthorizationFenceBinding.OwnerReadback largeAbort( DraftAuthorizationFenceBinding binding, Owner owner, byte[] originalBinding) { return new DraftAuthorizationFenceBinding.OwnerReadback( @@ -151,6 +214,7 @@ private static DraftAuthorizationFenceBinding.OwnerReadback largeAbort( } private static TransportServer startGameDesignServer( + TestIdentity identity, ReadGameDesignDraftTerminalOutcomeResponse response, AtomicReference received) throws Exception { @@ -165,10 +229,11 @@ public void readGameDesignDraftTerminalOutcome( observer.onCompleted(); } }; - return startServer(pki.gameDesignServer(), service); + return startServer(identity, service); } private static TransportServer startWorldServer( + TestIdentity identity, ReadWorldDraftTerminalOutcomeResponse response, AtomicReference received) throws Exception { @@ -183,11 +248,23 @@ public void readWorldDraftTerminalOutcome( observer.onCompleted(); } }; - return startServer(pki.worldServer(), service); + return startServer(identity, service); } - private static TransportServer startServer(TestIdentity identity, io.grpc.BindableService service) + private static TransportServer startServer(TestIdentity identity, BindableService service) throws Exception { + AtomicInteger applicationMetadataCalls = new AtomicInteger(); + ServerInterceptor countApplicationMetadata = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + applicationMetadataCalls.incrementAndGet(); + return next.startCall(call, metadata); + } + }; Server server = NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) .sslContext( @@ -196,10 +273,11 @@ private static TransportServer startServer(TestIdentity identity, io.grpc.Bindab .trustManager(pki.caCertificate()) .clientAuth(ClientAuth.REQUIRE) .build()) + .intercept(countApplicationMetadata) .addService(service) .build() .start(); - return new TransportServer(server); + return new TransportServer(server, applicationMetadataCalls); } private static GameDesignDraftTerminalReadClient gameDesignClient(int port) throws Exception { @@ -233,7 +311,8 @@ private static WorldDraftTerminalReadClient worldClient(int port) throws Excepti field.get(client); } - private record TransportServer(Server server) implements AutoCloseable { + private record TransportServer(Server server, AtomicInteger applicationMetadataCalls) + implements AutoCloseable { private int port() { return server.getPort(); } @@ -253,6 +332,8 @@ private record TestPki( X509Certificate caCertificate, TestIdentity gameDesignServer, TestIdentity worldServer, + TestIdentity otherNamespaceGameDesignServer, + TestIdentity otherNamespaceWorldServer, TestIdentity accountClient) { private static TestPki create(Path directory) throws Exception { Path caStore = directory.resolve("test-ca.p12"); @@ -299,6 +380,20 @@ private static TestPki create(Path directory) throws Exception { caCertificate, issueIdentity(directory, caStore, caFile, "game-design-server", GAME_DESIGN_URI, true), issueIdentity(directory, caStore, caFile, "world-server", WORLD_URI, true), + issueIdentity( + directory, + caStore, + caFile, + "other-namespace-game-design-server", + OTHER_NAMESPACE_GAME_DESIGN_URI, + true), + issueIdentity( + directory, + caStore, + caFile, + "other-namespace-world-server", + OTHER_NAMESPACE_WORLD_URI, + true), issueIdentity(directory, caStore, caFile, "account-client", ACCOUNT_URI, false)); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceSnapshotTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceSnapshotTest.java index 64bdbfedad..4a14b9cb64 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceSnapshotTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceSnapshotTest.java @@ -23,6 +23,31 @@ class TemplateConfigSourceSnapshotTest { private static final UUID VERSION = UUID.fromString("22222222-2222-4222-8222-222222222222"); private static final UUID GENESIS = UUID.fromString("33333333-3333-4333-8333-333333333333"); + @Test + void configRequiresNonblankBindingAndScopeKeysButAllowsEmptyScopeId() { + String event = + "{\"eventType\":\"onEnter\",\"eventSchemaVersion\":\"1\"," + + "\"bindingId\":\"binding-1\",\"targetScopeType\":\"ROOM\",\"targetScopeId\":\"\"}"; + String valid = + config() + .replace( + "\"scripts\":[]", + "\"scripts\":[{\"scriptId\":\"onEnter\",\"eventBindings\":[" + event + "]}]"); + assertThat(new TemplateConfigSourceValues.Config(valid).hasAutomationReferences()).isTrue(); + + for (String field : List.of("bindingId", "targetScopeType")) { + String original = field.equals("bindingId") ? "binding-1" : "ROOM"; + for (String blank : List.of("", " ")) { + String invalid = + valid.replace( + "\"" + field + "\":\"" + original + "\"", "\"" + field + "\":\"" + blank + "\""); + assertThatThrownBy(() -> new TemplateConfigSourceValues.Config(invalid)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(field); + } + } + } + @Test void directDecoderPreservesV1BytesAndMissingDeclarationEvidence() throws Exception { var config = new TemplateConfigSourceValues.Config(config()); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBindingTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBindingTest.java new file mode 100644 index 0000000000..8b7be8ae28 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBindingTest.java @@ -0,0 +1,141 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.OffsetDateTime; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.junit.jupiter.api.Test; + +/** Isolated fixture currentness is stipulated, not a legal/verification producer. */ +class AccountPublicationAuthorizationBindingTest { + @Test + void roundTripRetainsNestedSelectionAndSeparatesInputFromAllocatedFencesAndCapture() { + var input = + new AccountPublicationAuthorizationBinding.PreallocationInput( + UUID.randomUUID(), selection("notes")); + var source = + new SourceEvidence( + SourceKind.ACCOUNT, + input.actorAccountId().toString(), + "3", + "4", + null, + null, + new byte[] {9}); + var original = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), UUID.randomUUID(), input, List.of(source)); + var restored = AccountPublicationAuthorizationBinding.fromStored(original.canonicalBytes()); + assertThat(restored.canonicalBytes()).isEqualTo(original.canonicalBytes()); + var reallocated = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), UUID.randomUUID(), input, List.of(source)); + assertThat(reallocated.input().digest()).isEqualTo(input.digest()); + assertThat(reallocated.canonicalBytes()).isNotEqualTo(original.canonicalBytes()); + assertThat(restored.input().selection().digest()).isEqualTo(input.selection().digest()); + var recaptured = + new AccountPublicationAuthorizationBinding( + original.operationId(), + original.fenceId(), + input, + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + input.actorAccountId().toString(), + "4", + "5", + null, + null, + new byte[] {10}))); + assertThat(recaptured.input().digest()).isEqualTo(input.digest()); + assertThat(recaptured.canonicalBytes()).isNotEqualTo(original.canonicalBytes()); + } + + @Test + void rejectsDifferentActorScopeDuplicateSourcesAndWrongOperationDomain() { + var input = + new AccountPublicationAuthorizationBinding.PreallocationInput( + UUID.randomUUID(), selection("notes")); + var source = + new SourceEvidence( + SourceKind.ACCOUNT, UUID.randomUUID().toString(), "1", "1", null, null, new byte[] {1}); + assertThatThrownBy( + () -> + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), UUID.randomUUID(), input, List.of(source))) + .isInstanceOf(IllegalArgumentException.class); + var exact = + new SourceEvidence( + SourceKind.ACCOUNT, + input.actorAccountId().toString(), + "1", + "1", + null, + null, + new byte[] {1}); + assertThatThrownBy( + () -> + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), UUID.randomUUID(), input, List.of(exact, exact))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> AccountPublicationAuthorizationBinding.fromStored(exact.canonicalBytes())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static AuthoredDraftPublishSelectionBinding selection(String notes) { + var target = + new DraftCommitBinding.TargetProof( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 9007199254740993L, + "tenant-source", + 9007199254740995L, + "tenant-source", + "NEW_GAME_ROW"); + var commit = + DraftCommitBinding.create( + target, + UUID.fromString("33333333-3333-4333-8333-333333333333"), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.fromString("55555555-5555-4555-8555-555555555555"), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "{\"mutation\":\"fixture\"}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world", + "ROOM_SCOPE", + "room", + "900719925474099312345"))); + return AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + "publication-é", + "900719925474099312345", + notes, + commit.requestId(), + commit.commitId(), + commit.digest()), + target, + commit, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + commit.requestId(), + commit.commitId(), + commit.digest(), + "[]", + OffsetDateTime.parse("2026-10-05T00:00:00Z"))); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBindingTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBindingTest.java new file mode 100644 index 0000000000..e7b4ac225a --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBindingTest.java @@ -0,0 +1,168 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.OffsetDateTime; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.junit.jupiter.api.Test; + +/** + * Codec-only fixtures stipulate upstream synchronized evidence; they grant no publication + * authority. + */ +class AuthoredDraftPublishSelectionBindingTest { + @Test + void preservesRetainedBytesDigestLargeCountersAndDefensiveCopies() { + var original = selection(" exact notes — "); + var restored = + AuthoredDraftPublishSelectionBinding.fromStored( + original.canonicalJson(), original.digest()); + assertThat(restored).isEqualTo(original); + assertThat(restored.digest()) + .isEqualTo(DraftAuthorizationFenceBinding.digest(original.canonicalBytes())); + assertThat(restored.intent().expectedVersionStateEpoch()).isEqualTo("900719925474099312345"); + assertThat(restored.canonicalJson()) + .contains("\"gameDesignVersionRowId\":\"9007199254740993\""); + byte[] copy = restored.canonicalBytes(); + copy[0] = 0; + assertThat(restored.canonicalBytes()).isEqualTo(original.canonicalBytes()); + } + + @Test + void changedNotesChangeCompleteSelectionDigest() { + assertThat(selection("old").digest()).isNotEqualTo(selection("new").digest()); + } + + @Test + void everyCallerSelectionFieldAndSynchronizedEvidenceIsBound() { + var original = selection("notes"); + String json = original.canonicalJson(); + for (String changed : + List.of( + json.replace("publication-é", "publication-other"), + json.replace( + "\"expectedVersionStateEpoch\":\"900719925474099312345\"", + "\"expectedVersionStateEpoch\":\"900719925474099312346\""), + json.replace("\"notes\":\"notes\"", "\"notes\":\"changed\""), + json.replace("2026-10-05T00:00:00Z", "2026-10-05T00:00:01Z"), + json.replace("\"resultVectorJson\":\"[]\"", "\"resultVectorJson\":\"[1]\""))) { + String digest = + DraftAuthorizationFenceBinding.digest( + changed.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + assertThat(digest).isNotEqualTo(original.digest()); + assertThat(AuthoredDraftPublishSelectionBinding.fromStored(changed, digest).canonicalJson()) + .isEqualTo(changed); + } + for (String field : + List.of( + "canonicalTenantId", + "canonicalVersionId", + "selectedCommitRequestId", + "selectedCommitId")) { + String changed = + json.replaceFirst( + "\\\"" + field + "\\\":\\\"[0-9a-f-]+\\\"", + "\"" + field + "\":\"66666666-6666-4666-8666-666666666666\""); + assertThatThrownBy( + () -> + AuthoredDraftPublishSelectionBinding.fromStored( + changed, + DraftAuthorizationFenceBinding.digest( + changed.getBytes(java.nio.charset.StandardCharsets.UTF_8)))) + .isInstanceOf(IllegalArgumentException.class); + } + String changedDigest = + json.replaceFirst( + "\\\"selectedCommitDigest\\\":\\\"sha256:[0-9a-f]{64}\\\"", + "\"selectedCommitDigest\":\"sha256:" + "0".repeat(64) + "\""); + assertThatThrownBy( + () -> + AuthoredDraftPublishSelectionBinding.fromStored( + changedDigest, + DraftAuthorizationFenceBinding.digest( + changedDigest.getBytes(java.nio.charset.StandardCharsets.UTF_8)))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void corruptNestedCommitOrSynchronizedFenceFailsEvenWithRecomputedOuterDigest() { + var original = selection("notes"); + String corrupt = + original.canonicalJson().replace("\"inputDigest\":\"", "\"inputDigest\":\"changed-"); + assertThatThrownBy( + () -> + AuthoredDraftPublishSelectionBinding.fromStored( + corrupt, + DraftAuthorizationFenceBinding.digest( + corrupt.getBytes(java.nio.charset.StandardCharsets.UTF_8)))) + .isInstanceOf(IllegalArgumentException.class); + String changed = original.canonicalJson().replace("900719925474099312345", "01"); + assertThatThrownBy( + () -> + AuthoredDraftPublishSelectionBinding.fromStored( + changed, + DraftAuthorizationFenceBinding.digest( + changed.getBytes(java.nio.charset.StandardCharsets.UTF_8)))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AuthoredDraftPublishSelectionBinding.fromStored( + original.canonicalJson() + " ", original.digest())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static AuthoredDraftPublishSelectionBinding selection(String notes) { + var target = + new DraftCommitBinding.TargetProof( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 9007199254740993L, + "tenant-source", + 9007199254740995L, + "tenant-source", + "NEW_GAME_ROW"); + var commit = + DraftCommitBinding.create( + target, + UUID.fromString("33333333-3333-4333-8333-333333333333"), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.fromString("55555555-5555-4555-8555-555555555555"), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "{\"mutation\":\"fixture\"}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world", + "ROOM_SCOPE", + "room", + "900719925474099312345"))); + return AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + "publication-é", + "900719925474099312345", + notes, + commit.requestId(), + commit.commitId(), + commit.digest()), + target, + commit, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + commit.requestId(), + commit.commitId(), + commit.digest(), + "[]", + OffsetDateTime.parse("2026-10-05T00:00:00Z"))); + } +} diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts index 5a8d8e3fed..849c980f61 100644 --- a/services/game-design-service/build.gradle.kts +++ b/services/game-design-service/build.gradle.kts @@ -26,6 +26,12 @@ testing { } } +tasks.named("integrationTest") { + val composeFile = rootProject.layout.projectDirectory.file("docker/docker-compose.yml") + inputs.file(composeFile).withPropertyName("assetProofComposeFile") + systemProperty("firemud.asset-proof.compose-file", composeFile.asFile.absolutePath) +} + dependencies { compileOnly(libs.spotbugs.annotations) implementation(libs.aws.sdk.s3) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomeRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomeRepository.java index ff51060387..aa0c635d40 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomeRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomeRepository.java @@ -46,7 +46,9 @@ GameDesignDraftTerminalOperation claim( Record byOperation = findOperation(operation.accountBinding().operationId(), true); if (byOperation != null) { - return toOperation(byOperation); + GameDesignDraftTerminalOperation persisted = toOperation(byOperation); + requireExactOperation(operation, persisted); + return persisted; } if (dsl.fetchOne( "SELECT 1 FROM " diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryRepository.java index 038acbf4bc..118296eb65 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryRepository.java @@ -28,7 +28,7 @@ public class GameAuthoredWorldSourceDeliveryRepository { private static final int SCHEMA_VERSION = 1; private static final String NEW_GAME_ROW = "NEW_GAME_ROW"; - private static final int MAX_PENDING_BATCH_SIZE = 100; + public static final int MAX_PENDING_BATCH_SIZE = 100; private static final UUID NIL_UUID = new UUID(0L, 0L); private static final Table DELIVERY = diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredWorldSourceDeliveryService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredWorldSourceDeliveryService.java new file mode 100644 index 0000000000..c8a3f9e51c --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredWorldSourceDeliveryService.java @@ -0,0 +1,175 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ReadRequest; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository.DeliveryClaim; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Standalone, unregistered one-item durable source-delivery preparation. */ +public final class GameAuthoredWorldSourceDeliveryService { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final GameAuthoredWorldSourceDeliveryRepository repository; + private final WorldAuthoredSourceIntakeClient client; + private final TransactionTemplate ownerWrite; + private final String workloadNamespace; + + public GameAuthoredWorldSourceDeliveryService( + GameAuthoredWorldSourceDeliveryRepository repository, + WorldAuthoredSourceIntakeClient client, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.client = Objects.requireNonNull(client, "client"); + this.workloadNamespace = requireNamespace(workloadNamespace); + this.ownerWrite = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + this.ownerWrite.setName("game-authored-world-source-delivery-acknowledge"); + this.ownerWrite.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerWrite.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerWrite.setTimeout(10); + } + + /** + * Dispatches one persisted source claim and returns only a complete durably acknowledged result. + */ + public DeliveryClaim deliver(UUID sourceOperationId) { + requireNonNil(sourceOperationId, "sourceOperationId"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source delivery cannot start inside an ambient transaction"); + } + + DeliveryClaim claim = + repository + .read(sourceOperationId) + .orElseThrow( + () -> + new DeliveryNotFoundException( + "No durable fresh authored-world delivery claim exists for the source")); + if (!workloadNamespace.equals(claim.request().targetNamespace())) { + throw new DeliveryConflictException( + "Authored-world source delivery belongs to another workload namespace"); + } + Optional acknowledged = claim.acknowledgedReceipt(); + if (acknowledged.isPresent()) { + return claim; + } + + // The outbox identity is stable, so a retry after an ambiguous response replays this exact + // idempotent intake request. World dispatch and its independent read happen outside DB work. + CommittedReceipt intakeReceipt = client.intake(claim.request()); + ReadRequest readRequest = new ReadRequest(claim.request(), freshReadRequestId(claim)); + CommittedReceipt readReceipt = client.read(readRequest); + if (!intakeReceipt.equals(readReceipt)) { + throw new DeliveryConflictException( + "World intake and independent readback did not return the same complete receipt"); + } + + return persistAndReadBack(claim, readReceipt); + } + + private DeliveryClaim persistAndReadBack(DeliveryClaim expected, CommittedReceipt receipt) { + DeliveryClaim transactionResult; + try { + transactionResult = ownerWrite.execute(status -> repository.acknowledge(expected, receipt)); + } catch (RuntimeException transactionFailure) { + // A JDBC/transaction-manager failure can occur after the database committed. Resolve that + // ambiguity only from a fresh durable read; never dispatch again from this call. + try { + Optional recovered = repository.read(expected.source().operationId()); + if (recovered.isPresent()) { + DeliveryClaim claim = recovered.orElseThrow(); + requireSameRequest(expected, claim); + Optional durableReceipt = claim.acknowledgedReceipt(); + if (durableReceipt.isPresent()) { + if (!receipt.equals(durableReceipt.orElseThrow())) { + throw new DeliveryConflictException( + "A different World receipt won the durable delivery acknowledgement"); + } + return claim; + } + } + } catch (DeliveryConflictException conflict) { + conflict.addSuppressed(transactionFailure); + throw conflict; + } catch (RuntimeException readFailure) { + transactionFailure.addSuppressed(readFailure); + } + throw transactionFailure; + } + if (transactionResult == null) { + throw new IllegalStateException( + "World receipt acknowledgement transaction returned no proof"); + } + + Optional durableReadback = repository.read(expected.source().operationId()); + if (durableReadback.isEmpty()) { + throw new IllegalStateException( + "Committed World receipt acknowledgement is missing from independent owner readback"); + } + DeliveryClaim readback = durableReadback.orElseThrow(); + requireSameRequest(expected, readback); + if (!transactionResult.source().equals(readback.source()) + || !transactionResult.request().equals(readback.request()) + || !transactionResult.acknowledgedReceipt().equals(readback.acknowledgedReceipt()) + || readback.acknowledgedReceipt().isEmpty() + || !receipt.equals(readback.acknowledgedReceipt().orElseThrow())) { + throw new DeliveryConflictException( + "Committed World receipt acknowledgement failed exact durable owner readback"); + } + return readback; + } + + private static void requireSameRequest(DeliveryClaim expected, DeliveryClaim actual) { + if (!expected.source().equals(actual.source()) + || !expected.request().equals(actual.request())) { + throw new DeliveryConflictException( + "Authored-world source delivery changed while World intake was in flight"); + } + } + + private static UUID freshReadRequestId(DeliveryClaim claim) { + UUID requestId = UUID.randomUUID(); + while (NIL_UUID.equals(requestId) + || requestId.equals(claim.request().intakeRequestId()) + || requestId.equals(claim.source().operationId())) { + requestId = UUID.randomUUID(); + } + return requestId; + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } + + private static String requireNamespace(String namespace) { + Objects.requireNonNull(namespace, "workloadNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + return namespace; + } + + public static class DeliveryConflictException extends IllegalStateException { + public DeliveryConflictException(String message) { + super(message); + } + } + + public static final class DeliveryNotFoundException extends IllegalStateException { + public DeliveryNotFoundException(String message) { + super(message); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredWorldSourceDeliveryWorker.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredWorldSourceDeliveryWorker.java new file mode 100644 index 0000000000..4f065a24e0 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredWorldSourceDeliveryWorker.java @@ -0,0 +1,91 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository.DeliveryClaim; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Executes one explicitly invoked, bounded pass over this namespace's durable fresh-source claims. + */ +public final class GameAuthoredWorldSourceDeliveryWorker { + private static final Logger LOG = + LoggerFactory.getLogger(GameAuthoredWorldSourceDeliveryWorker.class); + + private final GameAuthoredWorldSourceDeliveryRepository repository; + private final GameAuthoredWorldSourceDeliveryService deliveryService; + private final int batchSize; + private final String workloadNamespace; + private final AtomicBoolean passRunning = new AtomicBoolean(); + private volatile UUID afterIntakeRequestId; + + public GameAuthoredWorldSourceDeliveryWorker( + GameAuthoredWorldSourceDeliveryRepository repository, + GameAuthoredWorldSourceDeliveryService deliveryService, + int batchSize, + String workloadNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.deliveryService = Objects.requireNonNull(deliveryService, "deliveryService"); + if (batchSize < 1 + || batchSize > GameAuthoredWorldSourceDeliveryRepository.MAX_PENDING_BATCH_SIZE) { + throw new IllegalArgumentException( + "Authored-world delivery batch size is outside the supported bounds"); + } + this.batchSize = batchSize; + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException( + "Game Design workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Reads at most one indexed page and dispatches each stable claim at most once in this pass. */ + public int runPass() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source delivery pass requires no ambient transaction"); + } + if (!passRunning.compareAndSet(false, true)) { + return 0; + } + try { + List claims = + repository.readPending(workloadNamespace, afterIntakeRequestId, batchSize); + if (claims.isEmpty()) { + afterIntakeRequestId = null; + return 0; + } + + for (DeliveryClaim claim : claims) { + // Move the cursor before remote work. An ambiguous item remains pending but cannot hold + // later claims behind it; a full cycle brings it back for an exact-identity retry. + afterIntakeRequestId = claim.request().intakeRequestId(); + try { + deliveryService.deliver(claim.source().operationId()); + } catch (RuntimeException failure) { + LOG.warn( + "Authored-world source delivery remains pending for operation {}", + claim.source().operationId(), + failure); + } + } + if (claims.size() < batchSize) { + afterIntakeRequestId = null; + } + return claims.size(); + } catch (RuntimeException failure) { + LOG.warn( + "Authored-world source delivery page read failed; durable claims remain pending", + failure); + return 0; + } finally { + passRunning.set(false); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java index 3080772d3a..b11844b2fe 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java @@ -614,7 +614,8 @@ && samePublication( PublishedReleaseBundleDto baseBundle = publishedReleaseBundleService.getPublishedReleaseBundle(tenantId, baseVersionId); PublishedReleaseBundleContract.requireSupportedSchemaForRead(baseBundle); - String expectedAbilitySchemaDigest = requiredAutomationAbilitySchemaDigest(baseBundle); + String expectedAbilitySchemaDigest = + requireGameLogicAbilitySchemaDigest(baseBundle, tenantId, baseVersionId); if (!expectedAbilitySchemaDigest.equals(abilitySchemaDigest)) { throw new IllegalArgumentException( "VALIDATION_FAILED_DESIGN: abilitySchemaDigest does not match published release bundle"); @@ -941,18 +942,44 @@ private void requireRequestedUploadMatchesStoredBundle( } } - private String requiredAutomationAbilitySchemaDigest(PublishedReleaseBundleDto bundle) { - return bundle.participantDigests().stream() - .filter( - digest -> - PublishParticipantKey.AUTOMATION_SCRIPTING.name().equals(digest.participantKey())) - .map(PublishParticipantDigestDto::contentDigest) - .filter(digest -> digest != null && !digest.isBlank()) - .findFirst() - .orElseThrow( - () -> - new IllegalArgumentException( - "INVALID_ARGUMENT: published release bundle is missing the Automation ability-schema digest")); + private static String requireGameLogicAbilitySchemaDigest( + PublishedReleaseBundleDto bundle, String tenantId, long baseVersionId) { + String ownerKey = PublishParticipantKey.GAME_LOGIC.name(); + List ownerEvidence = + bundle.participantDigests().stream() + .filter(participant -> ownerKey.equals(participant.participantKey())) + .toList(); + if (bundle.scriptOnly() + || !tenantId.equals(bundle.tenantId()) + || !Objects.equals(baseVersionId, bundle.versionId()) + || ownerEvidence.size() != 1 + || bundle.participantDigests().stream() + .anyMatch( + participant -> + !ownerKey.equals(participant.participantKey()) + && participant.abilitySchemaDigest() != null)) { + throw missingGameLogicAbilitySchemaDigest(); + } + var owner = ownerEvidence.getFirst(); + if (!owner.succeeded() + || (owner.errorMessage() != null && !owner.errorMessage().isBlank()) + || owner.baseVersionId() != null + || !Long.toString(baseVersionId).equals(owner.scopeValue()) + || !Objects.equals(1, owner.digestSchemaVersion()) + || owner.appliedCommitId() == null + || owner.appliedCommitId().isBlank() + || owner.contentDigest() == null + || !owner.contentDigest().matches("[0-9a-f]{64}") + || owner.abilitySchemaDigest() == null + || !owner.abilitySchemaDigest().matches("sha256:[0-9a-f]{64}")) { + throw missingGameLogicAbilitySchemaDigest(); + } + return owner.abilitySchemaDigest(); + } + + private static IllegalArgumentException missingGameLogicAbilitySchemaDigest() { + return new IllegalArgumentException( + "INVALID_ARGUMENT: published base release lacks exact Game Logic ability-schema evidence"); } private void markValidationFailed(PublishedPluginVersion entity, String statusReason) { diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java index 17025e58cd..463669b2a5 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java @@ -29,6 +29,7 @@ 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.AccountDraftCommitOrderReadGrpcService; import net.firedevops.firemud.accountservice.authordraft.AccountDraftTerminalReconciliationService; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; @@ -64,6 +65,7 @@ import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; @@ -71,6 +73,7 @@ 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.GameAuthoredWorldSourceDeliveryService; import net.firedevops.firemud.gamedesign.service.impl.TenantIdentityGrpcService; import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; import net.firedevops.firemud.test.TestContainerImages; @@ -90,6 +93,7 @@ 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.WorldAuthoredSourceIntakeServiceGrpc; import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; @@ -106,10 +110,14 @@ import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; 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.TransactionSystemException; +import org.springframework.transaction.support.DefaultTransactionStatus; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.Network; @@ -207,6 +215,175 @@ void deniedAccountCreatorRequestReachesNeitherOwnerAndExactRetryRecovers() throw compose(Failure.ACCOUNT_REFUSED); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void durableGameDesignDeliveryAcknowledgesExactWorldReceiptAcrossAuthenticatedSockets( + boolean loseRemoteAcknowledgement) throws Exception { + var gd = gameDesign(); + var world = store(WORLD, "world-management"); + var pki = new GenuineWorldSourceProofPki(temporary.resolve("pki")); + var gdHandlers = new MutableHandlerRegistry(); + var worldHandlers = new MutableHandlerRegistry(); + Server gdServer = server(pki, "game-design-service", gdHandlers); + Server worldServer = null; + try { + worldServer = server(pki, "world-management-service", worldHandlers); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + gdServer.getPort()); + endpoints.setWorldManagementService("localhost:" + worldServer.getPort()); + var factory = new GrpcChannelFactory(); + var sources = new GameAuthoredWorldSourceRepository(gd.store().dsl()); + var deliveries = new GameAuthoredWorldSourceDeliveryRepository(gd.store().dsl()); + register(gdHandlers, new AuthoredWorldSourceReadGrpcService(sources, NAMESPACE)); + var source = + Objects.requireNonNull( + transaction(gd.store()) + .execute( + ignored -> + sources.register( + NAMESPACE, + UUID.randomUUID(), + gd.target().canonicalTenantId(), + "genuine-tenant", + "delivery-world", + "Durably delivered authored World"))); + var claim = deliveries.read(source.operationId()).orElseThrow(); + var secondGame = new Game(); + secondGame.setTenantId(UUID.randomUUID().toString()); + secondGame.setName("Second authored World source"); + secondGame.setDescription("A distinct pending claim for delivery pagination"); + var savedSecondGame = + Objects.requireNonNull( + transaction(gd.store()) + .execute(ignored -> new GameRepository(gd.store().dsl()).save(secondGame))); + var secondSource = + Objects.requireNonNull( + transaction(gd.store()) + .execute( + ignored -> + sources.register( + NAMESPACE, + UUID.randomUUID(), + savedSecondGame.getCanonicalTenantId(), + "second-genuine-tenant", + "second-delivery-world", + "Second authored World"))); + var firstPage = deliveries.readPending(NAMESPACE, null, 1); + assertThat(firstPage).hasSize(1); + var first = firstPage.get(0); + var secondPage = deliveries.readPending(NAMESPACE, first.request().intakeRequestId(), 1); + assertThat(secondPage).hasSize(1); + var second = secondPage.get(0); + assertThat(List.of(first.source(), second.source())) + .containsExactlyInAnyOrder(source, secondSource); + assertThat(deliveries.readPending(NAMESPACE, second.request().intakeRequestId(), 1)) + .isEmpty(); + var intakes = new WorldAuthoredSourceIntakeRepository(world.dsl()); + assertThat(intakes.read(NAMESPACE, claim.request().intakeRequestId())).isEmpty(); + assertThat(claim.acknowledgedReceipt()).isEmpty(); + var intakeCalls = new AtomicInteger(); + var lostWorldResponse = new AtomicBoolean(loseRemoteAcknowledgement); + + try (var sourceClient = + new AuthoredWorldSourceClient( + endpoints, pki.client("world-management-service"), factory, NAMESPACE); + var intakeClient = + new WorldAuthoredSourceIntakeClient( + endpoints, pki.client("game-design-service"), factory, NAMESPACE)) { + sourceClient.init(); + worldHandlers.addService( + ServerInterceptors.intercept( + new WorldAuthoredSourceIntakeGrpcService( + new WorldAuthoredSourceIntakeService( + sourceClient, intakes, world.transactions(), NAMESPACE), + NAMESPACE), + new GrpcPeerIdentityInterceptor(), + observeDeliveryIntakes(intakeCalls, lostWorldResponse))); + intakeClient.init(); + var delivery = + new GameAuthoredWorldSourceDeliveryService( + deliveries, intakeClient, gd.store().transactions(), NAMESPACE); + if (loseRemoteAcknowledgement) { + assertThatThrownBy(() -> delivery.deliver(source.operationId())) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + assertThat(lostWorldResponse).isFalse(); + assertThat(intakeCalls).hasValue(1); + assertThat(deliveries.read(source.operationId())).contains(claim); + var committed = intakes.read(NAMESPACE, claim.request().intakeRequestId()).orElseThrow(); + assertThat(committed.source()).isEqualTo(source); + try (var restartedClient = + new WorldAuthoredSourceIntakeClient( + endpoints, + pki.client("game-design-service"), + new GrpcChannelFactory(), + NAMESPACE)) { + restartedClient.init(); + var restartedDelivery = + new GameAuthoredWorldSourceDeliveryService( + new GameAuthoredWorldSourceDeliveryRepository(gd.store().dsl()), + restartedClient, + gd.store().transactions(), + NAMESPACE); + var recovered = restartedDelivery.deliver(source.operationId()); + assertThat(recovered.request()).isEqualTo(claim.request()); + assertThat(recovered.acknowledgedReceipt().orElseThrow().receiptDigest()) + .isEqualTo(committed.receiptDigest()); + assertThat(intakes.read(NAMESPACE, claim.request().intakeRequestId())) + .contains(committed); + assertThat(deliveries.read(source.operationId())).contains(recovered); + assertThat(restartedDelivery.deliver(source.operationId())).isEqualTo(recovered); + assertThat(intakeCalls).hasValue(2); + } + } + var acknowledged = delivery.deliver(source.operationId()); + var receipt = acknowledged.acknowledgedReceipt().orElseThrow(); + var worldReceipt = intakes.read(NAMESPACE, claim.request().intakeRequestId()).orElseThrow(); + assertThat(acknowledged.source()).isEqualTo(source); + assertThat(acknowledged.request()).isEqualTo(claim.request()); + assertThat(worldReceipt.source()).isEqualTo(source); + assertThat(worldReceipt.receiptDigest()).isEqualTo(receipt.receiptDigest()); + assertThat(deliveries.read(source.operationId())).contains(acknowledged); + assertThat(delivery.deliver(source.operationId())).isEqualTo(acknowledged); + assertThat(deliveries.readPending(NAMESPACE, null, 2)) + .singleElement() + .satisfies(remaining -> assertThat(remaining.source()).isEqualTo(secondSource)); + assertThat(intakeCalls).hasValue(loseRemoteAcknowledgement ? 2 : 1); + + var lostAcknowledgement = new AtomicBoolean(); + var recoveryDelivery = + new GameAuthoredWorldSourceDeliveryService( + deliveries, + intakeClient, + loseDeliveryCommitAcknowledgement(gd.store(), lostAcknowledgement), + NAMESPACE); + var recovered = recoveryDelivery.deliver(secondSource.operationId()); + var recoveredReceipt = recovered.acknowledgedReceipt().orElseThrow(); + var recoveredWorld = + intakes.read(NAMESPACE, recovered.request().intakeRequestId()).orElseThrow(); + + assertThat(lostAcknowledgement).isTrue(); + assertThat(recovered.source()).isEqualTo(secondSource); + assertThat(recoveredWorld.source()).isEqualTo(secondSource); + assertThat(recoveredReceipt.receiptDigest()).isEqualTo(recoveredWorld.receiptDigest()); + assertThat(deliveries.read(secondSource.operationId())).contains(recovered); + assertThat(recoveryDelivery.deliver(secondSource.operationId())).isEqualTo(recovered); + assertThat(intakeCalls).hasValue(loseRemoteAcknowledgement ? 3 : 2); + assertThat(deliveries.readPending(NAMESPACE, null, 2)).isEmpty(); + } + } finally { + gdServer.shutdownNow(); + if (worldServer != null) { + worldServer.shutdownNow(); + assertThat(worldServer.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + assertThat(gdServer.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + private void compose(Failure failure) throws Exception { var gd = gameDesign(); var world = store(WORLD, "world-management"); @@ -597,6 +774,25 @@ public void sendMessage(RespT message) { } } + private static ServerInterceptor observeDeliveryIntakes( + AtomicInteger calls, AtomicBoolean loseWorldResponse) { + String method = + WorldAuthoredSourceIntakeServiceGrpc.getIntakeAuthoredWorldSourceMethod() + .getFullMethodName(); + ServerInterceptor fault = failureInterceptor(Failure.LOST_ACKNOWLEDGEMENT, loseWorldResponse); + return new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + if (method.equals(call.getMethodDescriptor().getFullMethodName())) { + calls.incrementAndGet(); + return fault.interceptCall(call, headers, next); + } + return next.startCall(call, headers); + } + }; + } + private static ServerInterceptor failureInterceptor(Failure failure, AtomicBoolean pending) { return new ServerInterceptor() { @Override @@ -728,6 +924,19 @@ private static TransactionTemplate transaction(Store store) { return result; } + private static DataSourceTransactionManager loseDeliveryCommitAcknowledgement( + Store store, AtomicBoolean lostAcknowledgement) { + return new DataSourceTransactionManager( + Objects.requireNonNull(store.transactions().getDataSource())) { + @Override + protected void doCommit(DefaultTransactionStatus status) { + super.doCommit(status); + lostAcknowledgement.set(true); + throw new TransactionSystemException("Test-only lost Game Design commit acknowledgement"); + } + }; + } + private static Server server( GenuineWorldSourceProofPki pki, String service, MutableHandlerRegistry handlers) throws Exception { diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java index 21c96348e1..e97f5447e9 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java @@ -240,7 +240,8 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema Draft draft = createDraft(gds); var worldSource = registerControlledWorldSource(gds, draft.target()); - DraftCommitBinding commit = selectedCommit(gds, draft.target()); + DraftCommitBinding commandCommit = authorGameplayCommand(gds, draft.target()); + DraftCommitBinding commit = selectedCommit(draft.target(), commandCommit.commitId()); applyGameDesignCommit(gds, commit); var delivery = new net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository( @@ -384,9 +385,19 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema .orElseThrow(); assertThat(synchronizedSources.command().definitions()).isEmpty(); var gameplaySnapshot = synchronizedSources.gameplayEvidence().orElseThrow(); - assertThat(gameplaySnapshot.manifest().families().get(GameplayRuleManifest.Family.COMMANDS)) - .extracting(GameplayRuleManifest.Definition::key) - .containsExactly("LOOK"); + assertThat(GameplayRuleSource.mutations(commit)).isEmpty(); + assertThat(gameplaySnapshot.binding()).isEqualTo(commit); + assertThat(gameplaySnapshot.inheritedCommitId()).isEqualTo(commandCommit.commitId()); + assertThat(gameplaySnapshot.entries()) + .filteredOn(entry -> entry.family() == GameplayRuleManifest.Family.COMMANDS) + .singleElement() + .satisfies( + entry -> { + assertThat(entry.definition().key()).isEqualTo("LOOK"); + assertThat(entry.sourceBinding()).isEqualTo(commandCommit); + assertThat(entry.revisionId()) + .isEqualTo(commandCommit.revisions().get(1).revisionId()); + }); var gameplaySource = new GameplayRuleSelectedSource(gameplaySnapshot.canonicalJson()); var glAuthorization = new GameLogicIntakeAuthorizationBinding( @@ -583,6 +594,14 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema var selectedOwnerReservation = admission.admitAndReserve(intent, accountBinding); assertThat(selectedOwnerReservation.selection().canonicalBytes()) .containsExactly(selectionBinding.canonicalBytes()); + var retainedGameplayCapture = + new GameDesignSourceRepository(gds.dsl()) + .readCapture(selectedOwnerReservation.operation()) + .orElseThrow() + .gameplay() + .orElseThrow(); + assertThat(retainedGameplayCapture.snapshot().canonicalBytes()) + .containsExactly(gameplaySnapshot.canonicalBytes()); var reservationReplay = admission.admitAndReserve(intent, accountBinding); assertThat(reservationReplay.operation().canonicalBytes()) .containsExactly(selectedOwnerReservation.operation().canonicalBytes()); @@ -632,7 +651,13 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema assertThat(participantDigests) .filteredOn(digest -> "GAME_LOGIC".equals(digest.participantKey())) .singleElement() - .satisfies(digest -> assertThat(digest.abilitySchemaDigest()).startsWith("sha256:")); + .satisfies( + digest -> { + assertThat(digest.contentDigest()) + .isEqualTo( + committedGlTerminal.manifestDigest().substring("sha256:".length())); + assertThat(digest.abilitySchemaDigest()).startsWith("sha256:"); + }); gate.assertSelectedGatePassed(versionDto, participantDigests); var altered = new ArrayList<>(participantDigests); @@ -799,6 +824,7 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema return result; }); assertThat(written.attestationSchemaVersion()).isEqualTo("v4"); + assertThat(written.commandDefinitions()).isEmpty(); assertThat(written.participantDigests()).containsExactlyElementsOf(participantDigests); assertThat(written.worldPublishedStartLocationEvidence().canonicalBytes()) .containsExactly(worldOwners.startLocationEvidence().canonicalBytes()); @@ -1624,9 +1650,8 @@ private static AuthoredWorldSourceEvidence registerControlledWorldSource( "Controlled selected World source")); } - private static DraftCommitBinding selectedCommit(Store gds, TargetProof target) + private static DraftCommitBinding selectedCommit(TargetProof target, UUID baseCommitId) throws com.google.protobuf.InvalidProtocolBufferException { - var genesis = new GameDesignSourceRepository(gds.dsl()).readGenesis(target).orElseThrow(); UUID commitId = UUID.randomUUID(); UUID regionId = UUID.randomUUID(); UUID zoneId = UUID.randomUUID(); @@ -1714,56 +1739,6 @@ private static DraftCommitBinding selectedCommit(Store gds, TargetProof target) var revisions = new ArrayList(); var units = new ArrayList(); - var selectedWorldAction = - new GameplayRuleManifest.Action( - "selected-world-look", - "Look", - List.of("selected-world-admission"), - List.of(), - List.of(), - List.of(), - List.of(), - List.of()); - var selectedWorldCommand = - new GameplayRuleManifest.Command( - "LOOK", - "selected-world-look", - "WORLD", - GameplayRuleManifest.ExecutionDiscipline.DURABLE_GAMEPLAY, - GameplayRuleManifest.Stage.GAMEPLAY, - GameplayRuleManifest.PromptPolicy.NEVER, - GameplayRuleManifest.ActionCategory.GAMEPLAY, - true, - List.of(), - List.of(GameplayRuleManifest.ActionTag.WORLD_BROWSE), - List.of("selected-world-admission")); - revisions.add( - new RevisionPayload( - "0", - UUID.randomUUID(), - Owner.GAME_DESIGN_CONTROL_PLANE, - GameplayRuleSource.upsertPayload(selectedWorldAction))); - units.add( - new AffectedUnit( - Owner.GAME_DESIGN_CONTROL_PLANE, - GameplayRuleSource.SCOPE, - target.canonicalVersionId().toString(), - GameplayRuleSource.SCOPE, - GameplayRuleSource.SCOPE_ID, - "0")); - revisions.add( - new RevisionPayload( - "1", - UUID.randomUUID(), - Owner.GAME_DESIGN_CONTROL_PLANE, - GameplayRuleSource.upsertPayload(selectedWorldCommand))); - revisions.add( - new RevisionPayload( - "2", - UUID.randomUUID(), - Owner.GAME_DESIGN_CONTROL_PLANE, - GameplayRuleSource.upsertPayload( - new GameplayRuleManifest.AdmissionTag("selected-world-admission")))); String policyPayload = "{\"revisionKind\":\"REALM_ENTRY_POLICY\",\"logicalRevisionId\":\"selected-public-realm\",\"policy\":{" + "\"schemaVersion\":1,\"worldSlug\":\"controlled-selected-world\",\"worldDisplayName\":\"World\"," @@ -1840,12 +1815,79 @@ private static DraftCommitBinding selectedCommit(Store gds, TargetProof target) "0")); } return DraftCommitBinding.create( - target, - UUID.randomUUID(), - commitId, - "genesis:" + genesis.policy().receiptId(), - revisions, - units); + target, UUID.randomUUID(), commitId, baseCommitId.toString(), revisions, units); + } + + private static DraftCommitBinding authorGameplayCommand(Store gds, TargetProof target) { + var sources = new GameDesignSourceRepository(gds.dsl()); + var genesis = sources.readGenesis(target).orElseThrow(); + var selectedWorldAction = + new GameplayRuleManifest.Action( + "selected-world-look", + "Look", + List.of("selected-world-admission"), + List.of(), + List.of(), + List.of(), + List.of(), + List.of()); + var selectedWorldCommand = + new GameplayRuleManifest.Command( + "LOOK", + "selected-world-look", + "WORLD", + GameplayRuleManifest.ExecutionDiscipline.DURABLE_GAMEPLAY, + GameplayRuleManifest.Stage.GAMEPLAY, + GameplayRuleManifest.PromptPolicy.NEVER, + GameplayRuleManifest.ActionCategory.GAMEPLAY, + true, + List.of(), + List.of(GameplayRuleManifest.ActionTag.WORLD_BROWSE), + List.of("selected-world-admission")); + var binding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis:" + genesis.policy().receiptId(), + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(selectedWorldAction)), + new RevisionPayload( + "1", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(selectedWorldCommand)), + new RevisionPayload( + "2", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload( + new GameplayRuleManifest.AdmissionTag("selected-world-admission")))), + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.SCOPE, + target.canonicalVersionId().toString(), + GameplayRuleSource.SCOPE, + GameplayRuleSource.SCOPE_ID, + "0"))); + applyGameDesignCommit(gds, binding); + var coordinator = new DraftCommitCoordinatorRepository(gds.dsl()); + gds.write() + .executeWithoutResult( + ignored -> { + var applied = sources.apply(binding); + coordinator.recordOwnerOutcome(binding, applied.ownerOutcome()); + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .advanceIsolatedSourceVisibility( + gds.dsl(), binding, List.of(applied.ownerOutcome())); + coordinator.releaseApplicationSlot(binding); + }); + return binding; } private static WorldDesignMutationRevision.Builder mutation( diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/AccountFreshTenantReceiptMtlsCrossServiceTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/AccountFreshTenantReceiptMtlsCrossServiceTest.java new file mode 100644 index 0000000000..f906b95450 --- /dev/null +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/AccountFreshTenantReceiptMtlsCrossServiceTest.java @@ -0,0 +1,632 @@ +package net.firedevops.firemud.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.*; + +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.client.GameDesignFreshTenantIdentityClient; +import net.firedevops.firemud.accountservice.client.GameDesignOriginalTenantCreationOutcomeClient; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.common.tenant.GameTenantCreationOriginalOutcomeEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationOriginalOutcomeEvidence.Binding; +import net.firedevops.firemud.common.tenant.GameTenantCreationOriginalOutcomeEvidence.Outcome; +import net.firedevops.firemud.gamedesign.repository.GameTenantCreationOriginalOutcomeRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantCreationOriginalOutcomeRepository.OriginalOutcomeSnapshot; +import net.firedevops.firemud.gamedesign.repository.GameTenantCreationOriginalOutcomeRepository.OutcomeStatus; +import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; +import net.firedevops.firemud.gamedesign.service.impl.OriginalTenantCreationOutcomeReadGrpcService; +import net.firedevops.firemud.gamedesign.service.impl.TenantIdentityGrpcService; +import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationRequest; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * Actual Account client and GDS adapter over loopback mTLS; mocked persistence, no DB/deployment + * proof. + */ +class AccountFreshTenantReceiptMtlsCrossServiceTest { + private static final String NAMESPACE = "test"; + private static final String DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String WRONG_WORKLOAD_URI = + "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String WRONG_NAMESPACE_URI = + "spiffe://firemud/ns/other/sa/game-design-service"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + private static final UUID CREATION_REQUEST_ID = + UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID OPERATION_ID = UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("32345678-1234-4234-8234-123456789abc"); + + @TempDir static Path temporaryDirectory; + + private static TestPki pki; + private Server server; + private GameDesignFreshTenantIdentityClient client; + private AtomicInteger rpcStarts; + private GameTenantCreationRepository repository; + private AtomicReference receivedPeer; + private AtomicReference receivedRequest; + + @BeforeAll + static void createLocalTestCertificates() throws Exception { + pki = TestPki.create(temporaryDirectory); + } + + @AfterEach + void stopTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void readsClosedBoundEvidenceFromExactSameNamespaceGameDesignPeer() throws Exception { + FreshTenantCreationEvidence expected = evidence(); + startServer(pki.gameDesignServer(), expected); + client = newClient(server); + client.init(); + + FreshTenantCreationEvidence result = + client.resolveCreation(CREATION_REQUEST_ID, expected.requestDigest()); + + assertThat(result).isEqualTo(expected); + assertThat(rpcStarts).hasValue(1); + assertThat(client.resolveCreation(CREATION_REQUEST_ID, expected.requestDigest())) + .isEqualTo(expected); + verify(repository, times(2)).read(CREATION_REQUEST_ID, NAMESPACE); + assertThat(receivedPeer.get()) + .isNotNull() + .extracting(GrpcPeerIdentity::uri) + .isEqualTo(ACCOUNT_URI); + assertThat(receivedRequest.get()) + .isEqualTo( + ResolveFreshTenantCreationRequest.newBuilder() + .setCreationRequestId(CREATION_REQUEST_ID.toString()) + .setExpectedRequestDigest(expected.requestDigest()) + .build()); + } + + @Test + void readsExactOriginalOutcomeAndRefusesChangedInitiatingAccountOverMtls() throws Exception { + FreshTenantCreationEvidence receipt = evidence(); + Binding binding = + new Binding( + NAMESPACE, + CREATION_REQUEST_ID, + UUID.fromString("42345678-1234-4234-8234-123456789abc"), + UUID.fromString("52345678-1234-4234-8234-123456789abc"), + receipt.requestDigest(), + "sha256:" + "a".repeat(64)); + Binding changedAccount = + new Binding( + NAMESPACE, + CREATION_REQUEST_ID, + binding.accountAuthorizationOperationId(), + UUID.fromString("62345678-1234-4234-8234-123456789abc"), + binding.creationRequestDigest(), + binding.accountAuthorizationDigest()); + var outcomes = mock(GameTenantCreationOriginalOutcomeRepository.class); + var receipts = mock(GameTenantCreationRepository.class); + var snapshot = + new OriginalOutcomeSnapshot( + binding, OutcomeStatus.CREATED, receipt.operationId(), receipt.evidenceDigest()); + when(outcomes.readCommitted(binding)).thenReturn(Optional.of(snapshot)); + when(outcomes.readCommitted(changedAccount)).thenReturn(Optional.of(snapshot)); + when(receipts.read(CREATION_REQUEST_ID, NAMESPACE)).thenReturn(Optional.of(receipt)); + var service = new OriginalTenantCreationOutcomeReadGrpcService(outcomes, receipts, NAMESPACE); + server = + serverBuilder(pki.gameDesignServer()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + server.getPort()); + try (var originalClient = + new GameDesignOriginalTenantCreationOutcomeClient( + endpoints, + pki.clientProperties(temporaryDirectory), + new GrpcChannelFactory(), + NAMESPACE)) { + originalClient.init(); + + assertThat(originalClient.readOriginal(binding).evidence()) + .isEqualTo( + new GameTenantCreationOriginalOutcomeEvidence( + 1, binding, Outcome.CREATED, Optional.of(receipt))); + assertThatThrownBy(() -> originalClient.readOriginal(changedAccount)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + } + verify(outcomes).readCommitted(binding); + verify(outcomes).readCommitted(changedAccount); + verify(receipts).read(CREATION_REQUEST_ID, NAMESPACE); + } + + @Test + void wrongServerWorkloadAndNamespaceCannotReturnAcceptedReceipt() throws Exception { + FreshTenantCreationEvidence expected = evidence(); + for (TestIdentity wrongServer : + List.of(pki.wrongWorkloadServer(), pki.wrongNamespaceServer())) { + startServer(wrongServer, expected); + client = newClient(server); + client.init(); + + assertThatThrownBy( + () -> client.resolveCreation(CREATION_REQUEST_ID, expected.requestDigest())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + + // Server identity rejection is client-side: a read may race with rejection, + // but no foreign-server result is accepted by the Account client. + stopTransport(); + } + } + + @Test + void wrongAccountNamespaceAndWrongWorkloadCannotReadOwner() throws Exception { + for (TestIdentity peer : List.of(pki.wrongClient(), pki.foreignClient())) { + startServer(pki.gameDesignServer(), evidence()); + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + server.getPort()); + client = + new GameDesignFreshTenantIdentityClient( + endpoints, + pki.clientProperties(temporaryDirectory, peer), + new GrpcChannelFactory(), + NAMESPACE); + client.init(); + assertThatThrownBy( + () -> client.resolveCreation(CREATION_REQUEST_ID, evidence().requestDigest())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + verifyNoInteractions(repository); + stopTransport(); + } + } + + @Test + void changedReceiptIsRejectedByActualOwnerWithoutSuccessfulReadback() throws Exception { + startServer(pki.gameDesignServer(), evidence()); + var other = + new FreshTenantCreationEvidence( + 1, + NAMESPACE, + UUID.fromString("92345678-1234-4234-8234-123456789abc"), + OPERATION_ID, + evidence().requestDigest(), + CANONICAL_TENANT_ID, + 42L, + "42", + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, + UUID.fromString("92345678-1234-4234-8234-123456789abc"), + OPERATION_ID, + evidence().requestDigest(), + CANONICAL_TENANT_ID, + 42L, + "42", + "NEW_GAME_ROW")); + when(repository.read(CREATION_REQUEST_ID, NAMESPACE)).thenReturn(Optional.of(other)); + client = newClient(server); + client.init(); + assertThatThrownBy( + () -> client.resolveCreation(CREATION_REQUEST_ID, evidence().requestDigest())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + verify(repository).read(CREATION_REQUEST_ID, NAMESPACE); + } + + @Test + void certificateLessTransportCannotReachOwner() throws Exception { + startServer(pki.gameDesignServer(), evidence()); + var channel = + io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder.forAddress( + "localhost", server.getPort()) + .sslContext(GrpcSslContexts.forClient().trustManager(pki.caCertificate()).build()) + .build(); + try { + assertThatThrownBy( + () -> + TenantIdentityServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .resolveFreshTenantCreation( + ResolveFreshTenantCreationRequest.newBuilder() + .setCreationRequestId(CREATION_REQUEST_ID.toString()) + .setExpectedRequestDigest(evidence().requestDigest()) + .build())) + .isInstanceOf(StatusRuntimeException.class); + verifyNoInteractions(repository); + assertThat(rpcStarts).hasValue(0); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + + private void startServer(TestIdentity identity, FreshTenantCreationEvidence expected) + throws Exception { + rpcStarts = new AtomicInteger(); + receivedPeer = new AtomicReference<>(); + receivedRequest = new AtomicReference<>(); + repository = mock(GameTenantCreationRepository.class); + when(repository.read(CREATION_REQUEST_ID, NAMESPACE)).thenReturn(Optional.of(expected)); + var service = new TenantIdentityGrpcService(repository, NAMESPACE); + ServerInterceptor countRpcStarts = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + rpcStarts.incrementAndGet(); + receivedPeer.set(GrpcPeerIdentity.current()); + var delegate = next.startCall(call, headers); + return new io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener< + ReqT>(delegate) { + @Override + public void onMessage(ReqT message) { + receivedRequest.set((ResolveFreshTenantCreationRequest) message); + super.onMessage(message); + } + }; + } + }; + server = + serverBuilder(identity) + .addService( + ServerInterceptors.intercept( + service, countRpcStarts, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private static NettyServerBuilder serverBuilder(TestIdentity identity) throws IOException { + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()); + } + + private GameDesignFreshTenantIdentityClient newClient(Server target) throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + target.getPort()); + return new GameDesignFreshTenantIdentityClient( + endpoints, pki.clientProperties(temporaryDirectory), new GrpcChannelFactory(), NAMESPACE); + } + + private static FreshTenantCreationEvidence evidence() { + String requestDigest = + GameTenantCreationDigest.requestDigest( + NAMESPACE, CREATION_REQUEST_ID, "42", "Test game", "mTLS fixture"); + return new FreshTenantCreationEvidence( + 1, + NAMESPACE, + CREATION_REQUEST_ID, + OPERATION_ID, + requestDigest, + CANONICAL_TENANT_ID, + 42L, + "42", + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, + CREATION_REQUEST_ID, + OPERATION_ID, + requestDigest, + CANONICAL_TENANT_ID, + 42L, + "42", + "NEW_GAME_ROW")); + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity gameDesignServer, + TestIdentity wrongWorkloadServer, + TestIdentity wrongNamespaceServer, + TestIdentity gameSessionClient, + TestIdentity wrongClient, + TestIdentity foreignClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("fresh-tenant-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD fresh-tenant test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("fresh-tenant-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + X509Certificate caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "design-server", DESIGN_URI, true), + issueIdentity( + directory, caStore, caFile, "wrong-workload-server", WRONG_WORKLOAD_URI, true), + issueIdentity( + directory, caStore, caFile, "wrong-namespace-server", WRONG_NAMESPACE_URI, true), + issueIdentity(directory, caStore, caFile, "game-session-client", ACCOUNT_URI, false), + issueIdentity( + directory, + caStore, + caFile, + "wrong-client", + "spiffe://firemud/ns/test/sa/world-management-service", + false), + issueIdentity( + directory, + caStore, + caFile, + "foreign-client", + "spiffe://firemud/ns/other/sa/account-service", + false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory) throws Exception { + return clientProperties(directory, gameSessionClient); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity peer) + throws Exception { + Path clientCertificate = + writePem( + directory.resolve("game-session-client.crt"), + "CERTIFICATE", + peer.certificate().getEncoded()); + Path clientPrivateKey = + writePem( + directory.resolve("game-session-client.key"), + "PRIVATE KEY", + peer.privateKey().getEncoded()); + Path trustCa = + writePem( + directory.resolve("fresh-tenant-client-trust-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()); + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(clientCertificate.toString()); + properties.setPrivateKey(clientPrivateKey.toString()); + properties.setCaCert(trustCa.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + List command = new ArrayList<>(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + if (!process.waitFor(30, TimeUnit.SECONDS)) { + process.destroyForcibly(); + throw new IllegalStateException("keytool timed out"); + } + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (process.exitValue() != 0) { + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomePostgresIntegrationTest.java index a070e577b4..37468b7609 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomePostgresIntegrationTest.java @@ -18,6 +18,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; @@ -37,10 +38,13 @@ import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; +import org.jooq.ExecuteListener; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -72,6 +76,114 @@ static void setUpSchema() { fixture = createFixture(null); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void concurrentChangedClaimPreservesOriginalBindingAndOwners(boolean reuseRequest) + throws Exception { + TargetProof target = fixture.newTarget(); + DraftCommitBinding original = binding(target); + DraftCommitBinding contender = + DraftCommitBinding.create( + target, + reuseRequest ? original.requestId() : UUID.randomUUID(), + original.commitId(), + original.baseCommitId(), + reuseRequest + ? List.of( + new RevisionPayload( + "0", + original.revisions().getFirst().revisionId(), + Owner.WORLD_MANAGEMENT, + "changed concurrent world revision"), + original.revisions().get(1)) + : original.revisions(), + original.affectedUnits()); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + PendingDraftClaim pending = + fixture.inTransaction( + () -> { + fixture.coordinator().claim(original); + int ownerPid = + fixture.dsl().fetchSingle("SELECT pg_backend_pid()").get(0, int.class); + List images = draftClaimImages(target); + var contenderPid = new AtomicInteger(); + var connected = new CountDownLatch(1); + Future rejection = + executor.submit( + () -> + attempt( + () -> { + contenderPid.set( + fixture + .dsl() + .fetchSingle("SELECT pg_backend_pid()") + .get(0, int.class)); + connected.countDown(); + return fixture.coordinator().claim(contender); + })); + await(connected); + assertBackendWaitsForOwner(contenderPid.get(), ownerPid); + return new PendingDraftClaim(rejection, images); + }); + + FinalizeAttempt result = pending.rejection().get(20, TimeUnit.SECONDS); + assertThat(result.succeeded()).isFalse(); + assertThat(result.failure()) + .isInstanceOf( + DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException.class); + var replay = fixture.inTransaction(() -> fixture.coordinator().claim(original)); + assertThat(replay.binding().canonicalBytes()).containsExactly(original.canonicalBytes()); + assertThat(replay.ownerStates()) + .containsOnlyKeys(Owner.WORLD_MANAGEMENT, Owner.ENTITY_MANAGEMENT); + assertThat(pending.originalImages()).hasSize(1 + original.requiredOwners().size()); + assertThat(draftClaimImages(target)).isEqualTo(pending.originalImages()); + } finally { + executor.shutdownNow(); + } + } + + private static List draftClaimImages(TargetProof target) { + return fixture + .dsl() + .fetch( + """ + SELECT 'commit/' || draft.xmin::text || '/' || to_jsonb(draft)::text + FROM game_design_draft_commit draft + WHERE draft.canonical_tenant_id = ? AND draft.canonical_version_id = ? + UNION ALL + SELECT 'owner/' || owner_result.xmin::text || '/' || to_jsonb(owner_result)::text + FROM game_design_draft_commit_owner_result owner_result + WHERE owner_result.canonical_tenant_id = ? AND owner_result.canonical_version_id = ? + ORDER BY 1 + """, + target.canonicalTenantId(), + target.canonicalVersionId(), + target.canonicalTenantId(), + target.canonicalVersionId()) + .getValues(0, String.class); + } + + private static void assertBackendWaitsForOwner(int contenderPid, int ownerPid) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadline) { + boolean blocked = + fixture + .dsl() + .fetchSingle("SELECT ? = ANY(pg_blocking_pids(?))", ownerPid, contenderPid) + .get(0, boolean.class); + if (blocked) return; + try { + TimeUnit.MILLISECONDS.sleep(10); + } catch (InterruptedException interruption) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while observing concurrent Draft claim", interruption); + } + } + throw new AssertionError("The competing Draft claim never waited for the original transaction"); + } + @Test void exactAccountClaimAndTerminalReadbackRetainOriginalBytes() { TargetProof target = fixture.newTarget(); @@ -108,6 +220,82 @@ void exactAccountClaimAndTerminalReadbackRetainOriginalBytes() { assertThat(retainedOperation.accountBindingBytes()).containsExactly(account.canonicalBytes()); } + @Test + void accountOperationClaimedAfterValidationRollsBackCompetingVersion() { + DraftCommitBinding contender = binding(fixture.newTarget()); + DraftCommitBinding winner = binding(fixture.newTarget()); + DraftAuthorizationFenceBinding contenderAccount = + accountBinding(contender, "stipulated-contender"); + UUID operationId = contenderAccount.operationId(); + DraftAuthorizationFenceBinding winnerAccount = + accountBinding( + winner, + operationId, + UUID.randomUUID(), + contenderAccount.actorAccountId(), + "stipulated-winner"); + var independentTransaction = + new TransactionTemplate( + fixture.transaction().getTransactionManager(), fixture.transaction()); + independentTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + String operationLookupSql = + "SELECT * FROM game_design_draft_terminal_operation WHERE operation_id = ? FOR UPDATE"; + var operationLookups = new AtomicInteger(); + var listener = + ExecuteListener.onExecuteStart( + context -> { + if (operationLookupSql.equals(context.sql()) + && operationLookups.incrementAndGet() == 3) { + // Both validation lookups missed. The contender has inserted its Draft and owners. + assertThat(draftClaimImages(contender.target())) + .hasSize(1 + contender.requiredOwners().size()); + independentTransaction.execute( + status -> fixture.coordinator().claim(winner, winnerAccount)); + } + }); + DSLContext observed = DSL.using(fixture.dsl().configuration().deriveAppending(listener)); + var contenderCoordinator = new DraftCommitCoordinatorRepository(observed); + + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> contenderCoordinator.claim(contender, contenderAccount))) + .isExactlyInstanceOf( + DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException.class) + .hasMessage("Account operation identity was reused with changed original canonical bytes"); + assertThat(operationLookups).hasValue(3); + assertThat(draftClaimImages(contender.target())).isEmpty(); + + var persisted = + new GameDesignDraftTerminalOutcomeRepository(fixture.dsl()) + .readOperation(operationId) + .orElseThrow(); + assertThat(persisted.accountBindingBytes()).containsExactly(winnerAccount.canonicalBytes()); + assertThat(persisted.gameDesignBinding().canonicalBytes()) + .containsExactly(winner.canonicalBytes()); + String operationImage = operationClaimImage(operationId); + List winnerImages = draftClaimImages(winner.target()); + assertThat(winnerImages).hasSize(1 + winner.requiredOwners().size()); + + var replay = fixture.inTransaction(() -> fixture.coordinator().claim(winner, winnerAccount)); + assertThat(replay.binding().canonicalBytes()).containsExactly(winner.canonicalBytes()); + assertThat(operationClaimImage(operationId)).isEqualTo(operationImage); + assertThat(draftClaimImages(winner.target())).isEqualTo(winnerImages); + } + + private static String operationClaimImage(UUID operationId) { + return fixture + .dsl() + .fetchSingle( + """ + SELECT retained.xmin::text || '/' || to_jsonb(retained)::text + FROM game_design_draft_terminal_operation retained + WHERE retained.operation_id = ? + """, + operationId) + .get(0, String.class); + } + @Test void committedOutcomeIsAtomicWithSynchronizedFenceAndCompleteOwnerVector() { TargetProof target = fixture.newTarget(); @@ -729,6 +917,9 @@ private static Fixture createFixture(MigrationVersion targetVersion) { private record FinalizeAttempt(boolean succeeded, RuntimeException failure) {} + private record PendingDraftClaim( + Future rejection, List originalImages) {} + private record Fixture( String schema, DriverManagerDataSource dataSource, diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBasePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBasePostgresIntegrationTest.java new file mode 100644 index 0000000000..5ed6f38694 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBasePostgresIntegrationTest.java @@ -0,0 +1,300 @@ +package net.firedevops.firemud.gamedesign.draft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigInteger; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.common.authoring.DraftBaseReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.publication.AssetSnapshot; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyGenesis; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL proof for Game Design's local review evidence guards. */ +@Testcontainers(disabledWithoutDocker = true) +class GameDesignReviewedBasePostgresIntegrationTest { + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void changedGenesisWitnessCannotBeClaimedOrReplaceRetainedV2Evidence() { + Fixture fixture = fixture(); + var genesis = fixture.sources().readGenesis(fixture.target()).orElseThrow(); + var binding = policyBinding(fixture, genesis.policy().receiptId()); + var actual = fixture.resolve(binding); + String changedWitness = + new BigInteger(genesis.policy().creationTransactionId()).add(BigInteger.ONE).toString(); + var changed = + GameDesignReviewedBaseEvidence.genesis( + new GameDesignSourceRepository.Genesis( + new RealmPolicyGenesis( + fixture.target(), genesis.policy().receiptId(), changedWitness), + new CommandSource.NewDraftGenesisReceipt( + fixture.target(), genesis.command().receiptId(), changedWitness), + Optional.of( + new AssetSnapshot.Genesis( + fixture.target(), genesis.asset().receiptId(), changedWitness)))); + assertThat(changed.reference()).isEqualTo(actual.reference()); + assertThat(changed.digest()).isNotEqualTo(actual.digest()); + + assertThatThrownBy(() -> fixture.tx(() -> fixture.sources().claimReviewed(binding, changed))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("REVIEWED_BASE_OWNER_EVIDENCE_CONFLICT"); + assertThatThrownBy( + () -> + fixture.tx( + () -> { + fixture.coordinator().claim(binding); + return insertReview(fixture.dsl(), binding, changed); + })) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("Reviewed base bytes or digest differ from exact owner provenance"); + assertThat(fixture.coordinator().read(fixture.target(), binding.requestId())).isEmpty(); + assertThat(fixture.reviewed().read(binding)).isEmpty(); + + var claim = fixture.tx(() -> fixture.sources().claimReviewed(binding, actual)); + assertThatThrownBy( + () -> + fixture.tx( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_reviewed_draft_base SET evidence_digest = ? WHERE request_id = ?", + changed.digest(), + binding.requestId()))) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("Reviewed Draft base evidence is immutable"); + assertThatThrownBy(() -> fixture.tx(() -> fixture.sources().claimReviewed(binding, changed))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("REVIEWED_BASE_STORED_EVIDENCE_CONFLICT"); + assertThat(fixture.coordinator().read(fixture.target(), binding.requestId())).contains(claim); + var retained = fixture.reviewed().requireCurrentRetained(binding); + assertThat(retained.canonicalBytes()).containsExactly(actual.canonicalBytes()); + assertThat(retained.digest()).isEqualTo(actual.digest()); + } + + @Test + void opaqueClaimRemainsUnreviewedAndCannotApplyOrCaptureSources() { + Fixture fixture = fixture(); + var genesis = fixture.sources().readGenesis(fixture.target()).orElseThrow(); + var binding = policyBinding(fixture, genesis.policy().receiptId()); + var evidence = fixture.resolve(binding); + var originalClaim = fixture.tx(() -> fixture.coordinator().claim(binding)); + + assertThatThrownBy(() -> fixture.tx(() -> fixture.sources().claimReviewed(binding, evidence))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("REVIEWED_BASE_EXISTING_CLAIM_LACKS_EVIDENCE"); + assertThat(fixture.coordinator().read(fixture.target(), binding.requestId())) + .contains(originalClaim); + assertThat(fixture.reviewed().read(binding)).isEmpty(); + + var slot = fixture.tx(() -> fixture.coordinator().claimApplicationSlot(binding)); + assertThatThrownBy(() -> fixture.tx(() -> insertReview(fixture.dsl(), binding, evidence))) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("Reviewed base requires exact new full Draft binding"); + fixture.tx( + () -> fixture.coordinator().markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE)); + var dispatched = + fixture.coordinator().read(fixture.target(), binding.requestId()).orElseThrow(); + + assertThatThrownBy(() -> fixture.tx(() -> fixture.sources().apply(binding))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("GAME_DESIGN_SOURCE_REVIEWED_BASE_UNAVAILABLE"); + assertThatThrownBy(() -> fixture.tx(() -> fixture.sources().captureSynchronized(binding))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("GAME_DESIGN_SOURCE_REVIEWED_BASE_UNAVAILABLE"); + assertThat(fixture.coordinator().read(fixture.target(), binding.requestId())) + .contains(dispatched); + assertThat(fixture.coordinator().readApplicationSlot(fixture.target())).contains(slot); + assertThat(fixture.coordinator().readVisibilityFence(fixture.target())).isEmpty(); + assertThat(fixture.reviewed().read(binding)).isEmpty(); + assertEmptyTables( + fixture.dsl(), + "game_design_realm_policy_application", + "game_design_command_source_application", + "game_design_realm_policy_snapshot", + "game_design_command_source_snapshot"); + } + + @Test + void unreviewedPublicationSelectionCannotFreezeOrReadSourceCaptures() { + Fixture fixture = fixture(); + // Retain the actual local selection and operation using stipulated Account and World evidence. + var operation = + fixture.tx( + () -> { + try { + return IsolatedPublicationOwnerSetup.retain(fixture.dsl(), fixture.target(), 1); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + var selected = operation.account().input().selection().selectedCommit(); + assertThat(fixture.coordinator().readVisibilityFence(fixture.target()).orElseThrow().commitId()) + .isEqualTo(selected.commitId()); + assertThat(fixture.reviewed().read(selected)).isEmpty(); + + assertThatThrownBy(() -> fixture.tx(() -> fixture.sources().freeze(operation))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("GAME_DESIGN_SOURCE_REVIEWED_BASE_UNAVAILABLE"); + assertThatThrownBy(() -> fixture.sources().readCapture(operation)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("GAME_DESIGN_SOURCE_REVIEWED_BASE_UNAVAILABLE"); + assertEmptyTables( + fixture.dsl(), + "game_design_realm_policy_capture", + "game_design_command_source_capture", + "game_design_asset_source_capture", + "game_design_gameplay_rule_source_capture", + "game_design_template_config_source_capture", + "game_design_branding_source_capture"); + } + + private static void assertEmptyTables(DSLContext dsl, String... tables) { + for (String table : tables) { + assertThat(dsl.fetchCount(DSL.table(table))).as(table).isZero(); + } + } + + private static int insertReview( + DSLContext dsl, DraftCommitBinding binding, GameDesignReviewedBaseEvidence evidence) { + return dsl.execute( + "INSERT INTO game_design_reviewed_draft_base " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, input_digest, " + + "binding_json, base_kind, base_identity, base_reference, evidence_schema, " + + "evidence_bytes, evidence_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + binding.digest(), + binding.canonicalJson(), + evidence.reference().kind().name(), + evidence.reference().identity(), + binding.baseCommitId(), + GameDesignReviewedBaseEvidence.SCHEMA, + evidence.canonicalBytes(), + evidence.digest()); + } + + private static DraftCommitBinding policyBinding(Fixture fixture, UUID receiptId) { + String payload = + """ + {"revisionKind":"REALM_ENTRY_POLICY","logicalRevisionId":"authored-main", + "policy":{"schemaVersion":1,"worldSlug":"world","worldDisplayName":"World", + "realmSlug":"main","realmDisplayName":"Realm","visible":true, + "publicProduction":true,"stateScope":"SHARED","entryPolicy":"PRESEEDED_ONLY"}} + """; + return DraftCommitBinding.create( + fixture.target(), + UUID.randomUUID(), + UUID.randomUUID(), + "genesis:" + receiptId, + List.of( + new RevisionPayload("0", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, payload)), + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + fixture.target().canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + "0"))); + } + + private static Fixture fixture() { + String schema = "gd_reviewed_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath()) + .table("flyway_schema_history_game_design_service") + .load() + .migrate(); + var write = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + TargetProof target = + write.execute( + status -> { + var game = new Game(); + game.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); + game.setName("ISOLATED reviewed source"); + var savedGame = new GameRepository(dsl).save(game); + var version = new Version(); + version.setTenantId(savedGame.getTenantId()); + version.setVersionNumber(1); + var saved = new VersionRepository(dsl).save(version); + return new TargetProof( + saved.getCanonicalTenantId(), + saved.getCanonicalVersionId(), + saved.getId(), + saved.getTenantId(), + saved.getIdentitySourceGameRowId(), + saved.getIdentitySourceGameTenantKey(), + saved.getIdentitySourceProvenanceKind()); + }); + return new Fixture( + dsl, + write, + target, + new GameDesignSourceRepository(dsl), + new DraftCommitCoordinatorRepository(dsl), + new GameDesignReviewedBaseRepository(dsl)); + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate write, + TargetProof target, + GameDesignSourceRepository sources, + DraftCommitCoordinatorRepository coordinator, + GameDesignReviewedBaseRepository reviewed) { + T tx(Supplier work) { + return write.execute(status -> work.get()); + } + + GameDesignReviewedBaseEvidence resolve(DraftCommitBinding binding) { + return tx(() -> reviewed.resolve(target, DraftBaseReference.parse(binding.baseCommitId()))); + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java index 935c9fc284..e51904b4b7 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java @@ -16,12 +16,15 @@ import java.util.Map; import java.util.Objects; import java.util.UUID; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftBaseReference; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; @@ -35,6 +38,11 @@ import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.CoordinatorProof; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.DraftCommitStateConflictException; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerOutcome; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerStatus; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.WorkflowState; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; @@ -77,6 +85,123 @@ class GameDesignSourcePostgresIntegrationTest { static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Test + void originalReviewedGenesisRemainsExactAfterDisjointCommandAdvance() { + Fixture local = fixture(); + var reviewed = new GameDesignReviewedBaseRepository(local.dsl()); + String base = + "genesis:" + local.sources().readGenesis(local.target()).orElseThrow().policy().receiptId(); + var reference = net.firedevops.firemud.common.authoring.DraftBaseReference.parse(base); + var original = local.tx(() -> reviewed.resolve(local.target(), reference)); + var command = binding(local.target(), base, null, "0", null, false); + synchronize(local, command, apply(local, command)); + var policy = binding(local.target(), base, "0", null, "main", true); + local.tx(() -> local.sources().claimReviewed(policy, original)); + var retained = reviewed.requireCurrentRetained(policy); + assertThat(retained.canonicalBytes()).containsExactly(original.canonicalBytes()); + assertThat(retained.schema()).isEqualTo(GameDesignReviewedBaseEvidence.SCHEMA); + synchronize(local, policy, apply(local, policy)); + assertOriginalReviewedHistoryAfterAdvance(local, reviewed, policy, original, reference); + assertThat( + local + .sources() + .readSynchronized(local.target(), policy.commitId()) + .orElseThrow() + .command() + .definitions()) + .hasSize(1); + } + + @Test + void originalReviewedAuthoredBaseRemainsExactAfterDisjointCommandAdvance() { + Fixture local = fixture(); + String genesis = + "genesis:" + local.sources().readGenesis(local.target()).orElseThrow().policy().receiptId(); + var first = binding(local.target(), genesis, "0", null, "main", true); + synchronize(local, first, apply(local, first)); + var reviewed = new GameDesignReviewedBaseRepository(local.dsl()); + var reference = + net.firedevops.firemud.common.authoring.DraftBaseReference.parse( + first.commitId().toString()); + var original = local.tx(() -> reviewed.resolve(local.target(), reference)); + var command = binding(local.target(), first.commitId().toString(), null, "0", null, false); + synchronize(local, command, apply(local, command)); + var policy = binding(local.target(), first.commitId().toString(), "1", null, "second", true); + local.tx(() -> local.sources().claimReviewed(policy, original)); + var retained = reviewed.requireCurrentRetained(policy); + assertThat(retained.canonicalBytes()).containsExactly(original.canonicalBytes()); + assertThat(retained.schema()).isEqualTo(GameDesignReviewedBaseEvidence.SCHEMA); + synchronize(local, policy, apply(local, policy)); + assertOriginalReviewedHistoryAfterAdvance(local, reviewed, policy, original, reference); + assertThat( + local + .sources() + .readSynchronized(local.target(), policy.commitId()) + .orElseThrow() + .command() + .definitions()) + .hasSize(1); + } + + // This is genuine local source/coordinator history, not Account or publication authorization. + private static void assertOriginalReviewedHistoryAfterAdvance( + Fixture local, + GameDesignReviewedBaseRepository reviewed, + DraftCommitBinding binding, + GameDesignReviewedBaseEvidence original, + net.firedevops.firemud.common.authoring.DraftBaseReference reference) { + var before = reviewedClaimRows(local); + assertThat(local.tx(() -> reviewed.resolve(local.target(), reference))).isEqualTo(original); + assertThat(local.tx(() -> local.sources().claimReviewed(binding, original)).binding()) + .isEqualTo(binding); + assertThat(reviewed.requireCurrentRetained(binding).canonicalBytes()) + .containsExactly(original.canonicalBytes()); + assertThat(reviewedClaimRows(local)).isEqualTo(before); + } + + @Test + void reviewedBaseRejectsWrongDraftWrongReceiptAndUnknownCommitBeforeClaim() { + Fixture local = fixture(); + var reviewed = new GameDesignReviewedBaseRepository(local.dsl()); + var originalGenesis = local.sources().readGenesis(local.target()).orElseThrow(); + var reference = DraftBaseReference.parse("genesis:" + originalGenesis.policy().receiptId()); + var original = local.tx(() -> reviewed.resolve(local.target(), reference)); + TargetProof other = secondFullDraftInTenant(local).target(); + var otherGenesis = local.sources().readGenesis(other).orElseThrow(); + assertThat(otherGenesis.policy().receiptId()).isNotEqualTo(reference.identity()); + var before = reviewedClaimRows(local); + + var wrongDraft = binding(other, reference.canonicalValue(), "0", null, "main", true); + assertThatThrownBy(() -> local.tx(() -> local.sources().claimReviewed(wrongDraft, original))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("REVIEWED_BASE_BINDING_CONFLICT"); + assertThatThrownBy(() -> local.tx(() -> reviewed.resolve(other, reference))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("REVIEWED_BASE_GENESIS_IDENTITY_CONFLICT"); + var wrongReceipt = new DraftBaseReference(DraftBaseReference.Kind.GENESIS, UUID.randomUUID()); + assertThatThrownBy(() -> local.tx(() -> reviewed.resolve(local.target(), wrongReceipt))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("REVIEWED_BASE_GENESIS_IDENTITY_CONFLICT"); + var unknownCommit = + new DraftBaseReference(DraftBaseReference.Kind.AUTHORED_COMMIT, UUID.randomUUID()); + assertThatThrownBy(() -> local.tx(() -> reviewed.resolve(local.target(), unknownCommit))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("REVIEWED_BASE_AUTHORED_SOURCE_UNAVAILABLE"); + assertThat(reviewedClaimRows(local)).isEqualTo(before); + assertThat(local.coordinator().readApplicationSlot(local.target())).isEmpty(); + assertThat(local.coordinator().readApplicationSlot(other)).isEmpty(); + var otherReference = DraftBaseReference.parse("genesis:" + otherGenesis.policy().receiptId()); + assertThat(local.tx(() -> reviewed.resolve(local.target(), reference)).canonicalBytes()) + .containsExactly(original.canonicalBytes()); + assertThat(local.tx(() -> reviewed.resolve(other, otherReference)).canonicalBytes()) + .containsExactly(GameDesignReviewedBaseEvidence.genesis(otherGenesis).canonicalBytes()); + + var exact = binding(local.target(), reference.canonicalValue(), "0", null, "main", true); + assertThat(local.tx(() -> local.sources().claimReviewed(exact, original)).binding()) + .isEqualTo(exact); + assertOriginalReviewedHistoryAfterAdvance(local, reviewed, exact, original, reference); + } + @Test void exactReviewedClaimReplayPreservesAllRetainedRowsAndChangedInputCannotRewriteThem() { var local = fixture(); @@ -107,6 +232,153 @@ void exactReviewedClaimReplayPreservesAllRetainedRowsAndChangedInputCannotRewrit assertReviewedClaimInventory(local, original); } + @Test + void committedUnknownOwnerRecoversOriginalCommandSourceAndKeepsCompetingDraftQueued() { + var local = fixture(); + var target = local.target(); + var prior = storageBinding(local, "prior synchronized command"); + synchronize(local, prior, apply(local, prior)); + var priorFence = local.coordinator().readVisibilityFence(target).orElseThrow(); + var priorSource = local.sources().readSynchronized(target, prior.commitId()).orElseThrow(); + + var original = binding(target, prior.commitId().toString(), null, "1", "recovered", false); + var competitor = binding(target, prior.commitId().toString(), null, "1", "competing", false); + var owner = Owner.GAME_DESIGN_CONTROL_PLANE; + // The uncertain observation is controlled; recovery below runs the real command owner. + var uncertain = + new OwnerOutcome( + owner, + OwnerStatus.UNKNOWN, + original.commitId(), + original.digest(), + "uncertain-command-observation", + "owner response was uncertain".getBytes(StandardCharsets.UTF_8), + List.of()); + start(local, original); + var originalSlot = local.coordinator().readApplicationSlot(target).orElseThrow(); + local.tx(() -> local.coordinator().recordOwnerOutcome(original, uncertain)); + local.tx( + () -> { + claimStorageBinding(local, competitor); + return null; + }); + + var recovered = new DraftCommitCoordinatorRepository(local.dsl()); + var sources = new GameDesignSourceRepository(local.dsl()); + var pending = recovered.read(target, original.requestId()).orElseThrow(); + var binding = pending.binding(); + assertThat(binding.canonicalBytes()).containsExactly(original.canonicalBytes()); + assertThat(pending.workflowState()).isEqualTo(WorkflowState.RECONCILIATION_REQUIRED); + assertThat(pending.ownerStates()).containsOnlyKeys(owner); + var pendingOwner = pending.ownerStates().get(owner); + assertThat(pendingOwner.status()).isEqualTo(OwnerStatus.UNKNOWN); + var storedUncertain = pendingOwner.outcome().orElseThrow(); + assertThat(storedUncertain).isEqualTo(uncertain); + assertThat(storedUncertain.resultBytes()).containsExactly(uncertain.resultBytes()); + assertThat(recovered.readApplicationSlot(target)).contains(originalSlot); + assertThat(recovered.readVisibilityFence(target)).contains(priorFence); + assertThat(sources.readSynchronized(target, original.commitId())).isEmpty(); + + var queued = recovered.read(target, competitor.requestId()).orElseThrow(); + assertThat(queued.workflowState()).isEqualTo(WorkflowState.QUEUED); + assertThat(queued.ownerStates().get(owner).status()).isEqualTo(OwnerStatus.NOT_ATTEMPTED); + var heldRows = draftRecoveryRows(local.dsl()); + assertThat(local.tx(() -> recovered.claimApplicationSlot(binding))).isEqualTo(originalSlot); + assertThat(local.tx(() -> recovered.recordOwnerOutcome(binding, storedUncertain))) + .isEqualTo(pendingOwner); + assertThatThrownBy(() -> local.tx(() -> recovered.claimApplicationSlot(competitor))) + .isExactlyInstanceOf(DraftCommitStateConflictException.class) + .hasMessageContaining("Another exact Draft commit"); + assertThatThrownBy(() -> local.tx(() -> sources.apply(changedClaimInput(binding)))) + .isExactlyInstanceOf(IllegalArgumentException.class) + .hasMessage("REVIEWED_BASE_STORED_BINDING_CONFLICT"); + assertThatThrownBy( + () -> + local + .write() + .executeWithoutResult(status -> recovered.releaseApplicationSlot(binding))) + .isExactlyInstanceOf(DraftCommitStateConflictException.class) + .hasMessageContaining("cannot release"); + assertThatThrownBy( + () -> + local.tx( + () -> + recovered.advanceSourceVisibilityFence( + binding, new CoordinatorProof(binding, List.of(storedUncertain))))) + .isExactlyInstanceOf(DraftCommitStateConflictException.class) + .hasMessageContaining("one exact APPLIED result"); + assertThat(draftRecoveryRows(local.dsl())).isEqualTo(heldRows); + + var applied = local.tx(() -> sources.apply(binding)); + var appliedOutcome = applied.ownerOutcome(); + var appliedOwner = + recovered.read(target, binding.requestId()).orElseThrow().ownerStates().get(owner); + assertThat(appliedOwner.status()).isEqualTo(OwnerStatus.APPLIED); + assertThat(appliedOwner.outcome()).contains(appliedOutcome); + assertThat(appliedOutcome.appliedEpochs()) + .containsExactly(applied.command().orElseThrow().commandAppliedEpoch()); + assertThat(recovered.readApplicationSlot(target)).contains(originalSlot); + assertThat(recovered.readVisibilityFence(target)).contains(priorFence); + assertThat(sources.readSynchronized(target, binding.commitId())).isEmpty(); + + var stagedRows = draftRecoveryRows(local.dsl()); + var reopenedSources = new GameDesignSourceRepository(local.dsl()); + var replay = local.tx(() -> reopenedSources.apply(binding)); + assertThat(replay.ownerOutcome().resultBytes()).containsExactly(appliedOutcome.resultBytes()); + assertThat(replay.command().orElseThrow().canonicalBytes()) + .containsExactly(applied.command().orElseThrow().canonicalBytes()); + assertThat(draftRecoveryRows(local.dsl())).isEqualTo(stagedRows); + + local + .write() + .executeWithoutResult( + status -> { + recovered.advanceSourceVisibilityFence( + binding, + new CoordinatorProof(binding, List.of(appliedOwner.outcome().orElseThrow()))); + recovered.releaseApplicationSlot(binding); + }); + var fence = recovered.readVisibilityFence(target).orElseThrow(); + assertThat(fence.commitId()).isEqualTo(binding.commitId()); + assertThat(fence.requestId()).isEqualTo(binding.requestId()); + assertThat(fence.inputDigest()).isEqualTo(binding.digest()); + assertThat(recovered.read(target, binding.requestId()).orElseThrow().workflowState()) + .isEqualTo(WorkflowState.SYNCHRONIZED); + var snapshot = reopenedSources.readSynchronized(target, binding.commitId()).orElseThrow(); + assertThat(snapshot.command().sourceEpoch()).isEqualTo("2"); + assertThat(snapshot.command().definitions()) + .singleElement() + .satisfies( + definition -> assertThat(definition.sourceCommitId()).isEqualTo(binding.commitId())); + assertThat(reopenedSources.readSynchronized(target, prior.commitId())).contains(priorSource); + assertThat(recovered.readApplicationSlot(target)).isEmpty(); + assertThat(recovered.read(target, competitor.requestId())).contains(queued); + assertThat(reopenedSources.readSynchronized(target, competitor.commitId())).isEmpty(); + } + + private static List> draftRecoveryRows(DSLContext sql) { + return List.of( + "game_design_draft_commit", + "game_design_draft_commit_owner_result", + "game_design_reviewed_draft_base", + "game_design_draft_commit_application_slot", + "game_design_draft_commit_visibility", + "game_design_draft_commit_visibility_fence", + "game_design_command_source_application", + "game_design_command_source_operation", + "game_design_command_source_snapshot", + "game_design_command_source_head") + .stream() + .map( + table -> + sql.fetch( + "SELECT t.xmin::text || '/' || to_jsonb(t)::text FROM " + + table + + " t ORDER BY 1") + .getValues(0, String.class)) + .toList(); + } + @Test void reviewedClaimAndItsOwnerInventoryRollBackWithoutRetainingReviewEvidence() { var local = fixture(); @@ -739,6 +1011,124 @@ void versionInsertSharesGenesisAndPolicyCommandMixedCommitsKeepOneExactOutcome() .isEqualTo(commandResult.ownerOutcome()); } + @Test + void stableCommandDeletePreservesDisjointHistoryAndFreezesTheExactSelectedSources() { + Fixture fixture = fixture(); + var genesis = fixture.sources().readGenesis(fixture.target()).orElseThrow(); + var authored = + binding( + fixture.target(), "genesis:" + genesis.policy().receiptId(), "0", "0", "main", true); + synchronize(fixture, authored, apply(fixture, authored)); + var original = + fixture.sources().readSynchronized(fixture.target(), authored.commitId()).orElseThrow(); + assertThat(original.command().definitions()) + .singleElement() + .satisfies( + definition -> { + assertThat(definition.commandId()).isEqualTo("look"); + assertThat(definition.sourceCommitId()).isEqualTo(authored.commitId()); + assertThat(definition.sourceRevisionId()) + .isEqualTo(authored.revisions().getFirst().revisionId()); + }); + + var disjoint = + binding(fixture.target(), authored.commitId().toString(), "1", null, "side", false); + synchronize(fixture, disjoint, apply(fixture, disjoint)); + var inherited = + fixture.sources().readSynchronized(fixture.target(), disjoint.commitId()).orElseThrow(); + assertThat(inherited.command().inheritedCommitId()).isEqualTo(authored.commitId()); + assertThat(inherited.command().sourceEpoch()).isEqualTo(original.command().sourceEpoch()); + assertThat(inherited.command().definitions()) + .containsExactlyElementsOf(original.command().definitions()); + assertThat(inherited.policy().policies()).hasSize(2); + assertThat(inherited.policy().policies()).containsAll(original.policy().policies()); + + UUID deleteRevisionId = UUID.randomUUID(); + var deletion = + DraftCommitBinding.create( + fixture.target(), + UUID.randomUUID(), + UUID.randomUUID(), + authored.commitId().toString(), + List.of( + new RevisionPayload( + "0", + deleteRevisionId, + Owner.GAME_DESIGN_CONTROL_PLANE, + CommandSource.deletePayload("look"))), + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + CommandSource.SCOPE, + fixture.target().canonicalVersionId().toString(), + CommandSource.SCOPE, + CommandSource.SCOPE_ID, + inherited.command().sourceEpoch()))); + synchronize(fixture, deletion, apply(fixture, deletion)); + var deleted = + fixture.sources().readSynchronized(fixture.target(), deletion.commitId()).orElseThrow(); + assertThat(deleted.command().definitions()).isEmpty(); + assertThat(deleted.command().sourceEpoch()).isEqualTo("2"); + assertThat(deleted.command().inheritedCommitId()).isEqualTo(disjoint.commitId()); + assertThat(deleted.policy().policies()) + .containsExactlyElementsOf(inherited.policy().policies()); + var operationRow = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT revision_id, operation_kind, command_id, definition_json " + + "FROM game_design_command_source_operation WHERE commit_id = ?", + deletion.commitId())); + assertThat(operationRow.get("revision_id", UUID.class)).isEqualTo(deleteRevisionId); + assertThat(operationRow.get("operation_kind", String.class)).isEqualTo("DELETE"); + assertThat(operationRow.get("command_id", String.class)).isEqualTo("look"); + assertThat(operationRow.get("definition_json", String.class)).isNull(); + + var operation = + fixture.tx( + () -> { + try { + return IsolatedPublicationOwnerSetup.retainSourceBacked( + fixture.dsl(), + fixture.target(), + 1, + "ISOLATED publication after stable command deletion", + deletion.commitId().toString()); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + var selected = operation.account().input().selection().selectedCommit(); + assertThat(selected.baseCommitId()).isEqualTo(deletion.commitId().toString()); + var selectedSources = + fixture.sources().readSynchronized(fixture.target(), selected.commitId()).orElseThrow(); + var capture = fixture.tx(() -> fixture.sources().freeze(operation)); + assertThat(capture.command().operation().canonicalBytes()) + .containsExactly(operation.canonicalBytes()); + assertThat(capture.command().snapshot()).isEqualTo(selectedSources.command()); + assertThat(capture.command().snapshot().inheritedCommitId()).isEqualTo(deletion.commitId()); + assertThat(capture.command().snapshot().definitions()).isEmpty(); + assertThat(capture.policy().snapshot().policies()) + .containsExactlyElementsOf(inherited.policy().policies()); + var retry = fixture.tx(() -> fixture.sources().freeze(operation)); + var retained = fixture.sources().readCapture(operation).orElseThrow(); + assertThat(retry.command().canonicalBytes()) + .containsExactly(capture.command().canonicalBytes()); + assertThat(retained.command().canonicalBytes()) + .containsExactly(capture.command().canonicalBytes()); + assertThat(retained.policy().canonicalBytes()) + .containsExactly(capture.policy().canonicalBytes()); + assertThat( + fixture + .sources() + .readSynchronized(fixture.target(), authored.commitId()) + .orElseThrow() + .command() + .canonicalBytes()) + .containsExactly(original.command().canonicalBytes()); + } + @Test void requiredOwnerSetMustBeNonEmptyDistinctAndKnownBeforeAnyOwnerFence() { Fixture fixture = fixture(); @@ -1805,7 +2195,7 @@ void rawLifecycleFirstRejectsSlotInsertAcrossSupportedIsolationLevels() throws E }); try { assertThat(started.await(10, TimeUnit.SECONDS)).isTrue(); - assertThat(awaitStorageBackendBlock(local, lifecyclePid, workerPid.get())) + assertThat(awaitStorageBackendBlock(local.dsl(), lifecyclePid, workerPid.get())) .as("slot writer backend blocked by lifecycle backend") .isTrue(); } finally { @@ -1861,7 +2251,7 @@ void rawSlotFirstRejectsLifecycleWriteIncludingStaleSnapshotsWithoutChangingVers }); try { assertThat(started.await(10, TimeUnit.SECONDS)).isTrue(); - assertThat(awaitStorageBackendBlock(local, slotPid, workerPid.get())) + assertThat(awaitStorageBackendBlock(local.dsl(), slotPid, workerPid.get())) .as("lifecycle writer backend blocked by slot backend") .isTrue(); } finally { @@ -1879,6 +2269,110 @@ void rawSlotFirstRejectsLifecycleWriteIncludingStaleSnapshotsWithoutChangingVers } } + @Test + void concurrentPublicationRequestClaimsAcrossVersionsRetainOnlyOneSelection() throws Exception { + var first = fixture(); + var second = secondFullDraftInTenant(first); + assertThat(second.target().canonicalTenantId()).isEqualTo(first.target().canonicalTenantId()); + assertThat(second.target().canonicalVersionId()) + .isNotEqualTo(first.target().canonicalVersionId()); + + String requestId = UUID.randomUUID().toString(); + var firstIntent = synchronizedPublicationIntent(first, requestId); + var secondIntent = synchronizedPublicationIntent(second, requestId); + var selections = new AuthoredDraftPublishSelectionRepository(first.dsl(), first.coordinator()); + var losingVersionBefore = selectionRaceVersionRow(second); + var losingFenceBefore = second.coordinator().readVisibilityFence(second.target()).orElseThrow(); + var reviewedBefore = reviewedClaimRows(first); + var winningVersionBefore = versionFields(first); + var manager = Objects.requireNonNull(first.write().getTransactionManager()); + + try (var worker = Executors.newSingleThreadExecutor(); + var observer = + DriverManager.getConnection( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword())) { + var observerSql = DSL.using(observer, SQLDialect.POSTGRES); + var transaction = manager.getTransaction(first.write()); + try { + int winnerPid = storageBackendPid(first.dsl()); + var winner = selections.reserve(firstIntent); + var winningRows = retainedSelectionRows(first); + assertThat(winningRows).hasSize(1); + + var contenderPid = new CompletableFuture(); + var contender = + worker.submit( + () -> + second.tx( + () -> { + second.dsl().execute("SET LOCAL lock_timeout = '10s'"); + contenderPid.complete(storageBackendPid(second.dsl())); + return selections.reserve(secondIntent); + })); + int losingPid = contenderPid.get(10, TimeUnit.SECONDS); + assertThat(awaitStorageBackendBlock(observerSql, winnerPid, losingPid)) + .as("second Draft selection transaction blocked by first Draft selection transaction") + .isTrue(); + manager.commit(transaction); + + assertThatThrownBy(() -> contender.get(20, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .hasCauseInstanceOf( + DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException.class) + .rootCause() + .isInstanceOfSatisfying( + PSQLException.class, + failure -> { + assertThat(failure.getSQLState()).isEqualTo("23505"); + assertThat( + Objects.requireNonNull(failure.getServerErrorMessage()).getConstraint()) + .isEqualTo("uq_gd_authored_draft_publish_operation"); + }); + + var tenantId = firstIntent.canonicalTenantId(); + assertThat(winner.selection().intent()).isEqualTo(firstIntent); + assertThat(selections.readByPublishRequest(tenantId, requestId)).contains(winner); + assertThat(selections.read(tenantId, firstIntent.canonicalVersionId(), requestId)) + .contains(winner); + assertThat(selections.read(tenantId, secondIntent.canonicalVersionId(), requestId)) + .isEmpty(); + assertThat(first.tx(() -> selections.reserve(firstIntent))).isEqualTo(winner); + assertThatThrownBy(() -> second.tx(() -> selections.reserve(secondIntent))) + .isInstanceOf( + DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException.class) + .hasMessageContaining("Publish request identity was reused"); + assertThat(retainedSelectionRows(first)).isEqualTo(winningRows); + assertThat(versionFields(first)).isEqualTo(winningVersionBefore); + assertThat(selectionRaceVersionRow(second)).isEqualTo(losingVersionBefore); + assertThat(second.coordinator().readVisibilityFence(second.target())) + .contains(losingFenceBefore); + assertThat(second.coordinator().readApplicationSlot(second.target())).isEmpty(); + assertThat(reviewedClaimRows(first)).isEqualTo(reviewedBefore); + } finally { + if (!transaction.isCompleted()) manager.rollback(transaction); + } + } + } + + private static List retainedSelectionRows(Fixture fixture) { + return fixture + .dsl() + .fetch( + "SELECT s.xmin::text || '/' || to_jsonb(s)::text " + + "FROM game_design_authored_draft_publish_selection s " + + "ORDER BY s.canonical_tenant_id, s.canonical_version_id") + .getValues(0, String.class); + } + + private static String selectionRaceVersionRow(Fixture fixture) { + return fixture + .dsl() + .fetchSingle( + "SELECT v.xmin::text || '/' || to_jsonb(v)::text FROM version v WHERE v.id = ?", + fixture.target().gameDesignVersionRowId()) + .get(0, String.class); + } + @Test void rawSelectionFirstRejectsSlotInsertEvenWhenSlotSnapshotPredatesSelection() throws Exception { for (int isolation : storageIsolationLevels()) { @@ -1907,7 +2401,7 @@ void rawSelectionFirstRejectsSlotInsertEvenWhenSlotSnapshotPredatesSelection() t }); try { assertThat(started.await(10, TimeUnit.SECONDS)).isTrue(); - assertThat(awaitStorageBackendBlock(local, selectionPid, workerPid.get())) + assertThat(awaitStorageBackendBlock(local.dsl(), selectionPid, workerPid.get())) .as("slot writer backend blocked by selection backend") .isTrue(); } finally { @@ -1956,7 +2450,7 @@ void rawSlotFirstRejectsSelectionEvenWhenSelectionSnapshotPredatesSlot() throws }); try { assertThat(started.await(10, TimeUnit.SECONDS)).isTrue(); - assertThat(awaitStorageBackendBlock(local, slotPid, workerPid.get())) + assertThat(awaitStorageBackendBlock(local.dsl(), slotPid, workerPid.get())) .as("selection writer backend blocked by slot backend") .isTrue(); } finally { @@ -1991,18 +2485,16 @@ private int storageBackendPid(DSLContext sql) { .get(0, Integer.class); } - private boolean awaitStorageBackendBlock(Fixture local, int firstPid, int workerPid) + private boolean awaitStorageBackendBlock(DSLContext observer, int firstPid, int workerPid) throws InterruptedException { long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); while (System.nanoTime() < deadline) { var activity = - local - .dsl() - .fetchOne( - "SELECT ? = ANY(pg_blocking_pids(pid)) AND wait_event_type = 'Lock' AS blocked " - + "FROM pg_stat_activity WHERE pid = ?", - firstPid, - workerPid); + observer.fetchOne( + "SELECT ? = ANY(pg_blocking_pids(pid)) AND wait_event_type = 'Lock' AS blocked " + + "FROM pg_stat_activity WHERE pid = ?", + firstPid, + workerPid); if (activity != null && Boolean.TRUE.equals(activity.get("blocked", Boolean.class))) { return true; } @@ -2101,20 +2593,23 @@ private static TransactionTemplate tx(Fixture fixture) { return fixture.write(); } - private static AuthoredDraftPublishSelection synchronizedStorageSelection(Fixture fixture) { + private static AuthoredDraftPublishSelection.PublishIntent synchronizedPublicationIntent( + Fixture fixture, String requestId) { var binding = storageBinding(fixture, "storage-selected"); - var applied = apply(fixture, binding); - synchronize(fixture, binding, applied); - var intent = - new AuthoredDraftPublishSelection.PublishIntent( - fixture.target().canonicalTenantId(), - fixture.target().canonicalVersionId(), - UUID.randomUUID().toString(), - "1", - "controlled storage race", - binding.requestId(), - binding.commitId(), - binding.digest()); + synchronize(fixture, binding, apply(fixture, binding)); + return new AuthoredDraftPublishSelection.PublishIntent( + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId(), + requestId, + "1", + "controlled storage race", + binding.requestId(), + binding.commitId(), + binding.digest()); + } + + private static AuthoredDraftPublishSelection synchronizedStorageSelection(Fixture fixture) { + var intent = synchronizedPublicationIntent(fixture, UUID.randomUUID().toString()); return fixture.tx( () -> AuthoredDraftPublishSelection.capture( @@ -2124,9 +2619,9 @@ private static AuthoredDraftPublishSelection synchronizedStorageSelection(Fixtur .coordinator() .requireSynchronizedPublicationEvidence( fixture.target(), - binding.requestId(), - binding.commitId(), - binding.digest()))); + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()))); } private void insertRawSelection(DSLContext sql, AuthoredDraftPublishSelection selected) { @@ -2155,6 +2650,35 @@ private void insertRawSelection(DSLContext sql, AuthoredDraftPublishSelection se selected.canonicalJson()); } + private static Fixture secondFullDraftInTenant(Fixture fixture) { + var target = + fixture.tx( + () -> { + var version = new Version(); + version.setTenantId(fixture.target().gameDesignVersionTenantKey()); + version.setVersionNumber(2); + return target(new VersionRepository(fixture.dsl()).save(version)); + }); + return new Fixture( + fixture.schema(), + fixture.dsl(), + fixture.write(), + target, + fixture.sources(), + fixture.coordinator()); + } + + private static TargetProof target(Version version) { + return new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + } + private static Fixture fixture() { return fixture(null); } @@ -2194,15 +2718,7 @@ private static Fixture fixture(String migrationTarget) { var version = new Version(); version.setTenantId(game.getTenantId()); version.setVersionNumber(1); - version = new VersionRepository(dsl).save(version); - return new TargetProof( - version.getCanonicalTenantId(), - version.getCanonicalVersionId(), - version.getId(), - version.getTenantId(), - version.getIdentitySourceGameRowId(), - version.getIdentitySourceGameTenantKey(), - version.getIdentitySourceProvenanceKind()); + return target(new VersionRepository(dsl).save(version)); }); return new Fixture( schema, diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java index 3e6ec183a8..8205b9e06c 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java @@ -12,9 +12,11 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; +import java.util.Base64; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; @@ -41,11 +43,13 @@ import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.FlywayException; 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.postgresql.util.PSQLException; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -163,6 +167,167 @@ void actualDefaultLocationsFreshBootstrapAppliesFullCombinedHistoryAndEnabledGua assertEnabledGuards(dsl, schema); } + @Test + void v503RejectsConflictingRetainedRequestsAcrossVersionsWithoutDiscardingEitherHistory() { + String schema = "gd_selection_collision_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + flyway(source, schema, "50.2").migrate(); + var write = new TransactionTemplate(new DataSourceTransactionManager(source)); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + assertThat( + dsl.fetchSingle( + "SELECT tgenabled::text FROM pg_trigger " + + "WHERE tgrelid = 'game_design_authored_draft_publish_selection'::regclass " + + "AND tgname = 'trg_gd_authored_draft_publish_selection'") + .get(0, String.class)) + .isEqualTo("O"); + + var requested = new Game(); + requested.setTenantId("retained-selection-collision"); + requested.setName("Historical publication request collision"); + var game = new GameRepository(dsl).save(requested); + var versions = new VersionRepository(dsl); + var firstVersion = + versions.findById(insertHistoricalDraftVersion(dsl, game.getId())).orElseThrow(); + var secondVersion = + versions.findById(insertHistoricalDraftVersion(dsl, game.getId(), 2)).orElseThrow(); + + String requestId = UUID.randomUUID().toString(); + var coordinator = new DraftCommitCoordinatorRepository(dsl); + var selections = new AuthoredDraftPublishSelectionRepository(dsl, coordinator); + var first = + Objects.requireNonNull( + write.execute( + status -> retainV502Selection(dsl, coordinator, firstVersion, requestId))); + var second = + Objects.requireNonNull( + write.execute( + status -> retainV502Selection(dsl, coordinator, secondVersion, requestId))); + assertThat(second.target().canonicalTenantId()).isEqualTo(first.target().canonicalTenantId()); + assertThat(second.target().canonicalVersionId()) + .isNotEqualTo(first.target().canonicalVersionId()); + + String selectionImagesQuery = + """ + SELECT s.xmin::text, to_jsonb(s)::text + FROM game_design_authored_draft_publish_selection s + ORDER BY s.canonical_tenant_id, s.canonical_version_id + """; + var selectionImages = dsl.fetch(selectionImagesQuery); + assertThat(selectionImages).hasSize(2); + String historyImagesQuery = + """ + SELECT h.xmin::text, to_jsonb(h)::text + FROM flyway_schema_history_game_design_service h + ORDER BY h.installed_rank + """; + var historyImages = dsl.fetch(historyImagesQuery); + + assertThatThrownBy(() -> flyway(source, schema, "50.3").migrate()) + .isInstanceOf(FlywayException.class) + .hasMessageContaining("50.3") + .rootCause() + .isInstanceOfSatisfying( + PSQLException.class, + failure -> { + assertThat(failure.getSQLState()).isEqualTo("23505"); + assertThat(Objects.requireNonNull(failure.getServerErrorMessage()).getConstraint()) + .isEqualTo("uq_gd_authored_draft_publish_operation"); + }); + + assertThat(dsl.fetch(selectionImagesQuery)).isEqualTo(selectionImages); + assertThat(dsl.fetch(historyImagesQuery)).isEqualTo(historyImages); + assertThat( + dsl.fetch( + "SELECT version FROM flyway_schema_history_game_design_service " + + "WHERE version IN ('50.2', '50.3') AND success ORDER BY installed_rank") + .getValues(0, String.class)) + .containsExactly("50.2"); + for (var original : List.of(first, second)) { + var target = original.target(); + assertThat( + selections.read(target.canonicalTenantId(), target.canonicalVersionId(), requestId)) + .hasValueSatisfying(retained -> assertThat(retained.selection()).isEqualTo(original)); + } + } + + @Test + void legacyAttemptDigestsAndRowsSurviveSelectedDigestWidthAndRevisionUpgrades() { + String schema = "gd_legacy_attempts_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + flyway(source, schema, "50.3").migrate(); + var dsl = DSL.using(source, SQLDialect.POSTGRES); + + var requested = new Game(); + requested.setTenantId("retained-attempt-test"); + requested.setName("Historical publication attempts"); + var game = new GameRepository(dsl).save(requested); + long versionId = insertHistoricalDraftVersion(dsl, game.getId()); + dsl.execute( + """ + INSERT INTO publish_attempt + (tenant_id, publish_workflow_id, publish_type, status, version_id, + version_number, request_digest) + VALUES (?, 'retained-pending', 'FULL_VERSION', 'PENDING', ?, 1, ?), + (?, 'retained-success', 'FULL_VERSION', 'SUCCEEDED', ?, 1, ?), + (?, 'retained-patch', 'SCRIPT_PATCH', 'FAILED', ?, 1, NULL) + """, + game.getTenantId(), + versionId, + "a".repeat(64), + game.getTenantId(), + versionId, + "b".repeat(64), + game.getTenantId(), + versionId); + + String attemptImageQuery = + """ + SELECT attempt.xmin::text, (to_jsonb(attempt) - 'revision')::text + FROM publish_attempt attempt + ORDER BY attempt.id + """; + var attemptImages = dsl.fetch(attemptImageQuery); + assertThat(attemptImages).hasSize(3); + int priorRank = + dsl.fetchSingle("SELECT max(installed_rank) FROM flyway_schema_history_game_design_service") + .get(0, int.class); + String historyQuery = + """ + SELECT to_jsonb(history)::text FROM flyway_schema_history_game_design_service history + WHERE installed_rank <= ? ORDER BY installed_rank + """; + var history = dsl.fetch(historyQuery, priorRank); + + flyway(source, schema, "50.4").migrate(); + assertThat(dsl.fetch(attemptImageQuery)).isEqualTo(attemptImages); + assertThat( + dsl.fetchSingle( + "SELECT character_maximum_length FROM information_schema.columns " + + "WHERE table_schema = ? AND table_name = 'publish_attempt' AND column_name = 'request_digest'", + schema) + .get(0, int.class)) + .isEqualTo(71); + + var latest = flyway(source, schema, null); + latest.migrate(); + latest.validate(); + assertThat(dsl.fetch(attemptImageQuery)).isEqualTo(attemptImages); + assertThat(dsl.fetch(historyQuery, priorRank)).isEqualTo(history); + assertThat( + dsl.fetch("SELECT revision FROM publish_attempt ORDER BY id").getValues(0, Long.class)) + .containsExactly(1L, 1L, 1L); + assertThat(dsl.fetchCount(DSL.table("game_design_publication_operation"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("game_design_draft_terminal_operation"))).isZero(); + } + @Test void actualReceivingParentIncludingSagaUpgradePreservesHistoryAndAppliesStorageTail( @TempDir Path parentMigrations) throws Exception { @@ -748,29 +913,11 @@ private Fixture fixture(boolean reserveV1, boolean retainReviewedV1) throws Exce var game = new GameRepository(dsl).save(requested); // Reproduce the original owner insertion under its actual pre-tail schema. The // current Version writer requires ordinary asset genesis, which did not exist here. - var inserted = - java.util.Objects.requireNonNull( - dsl.fetchOne( - "INSERT INTO version (tenant_id, canonical_version_id, canonical_tenant_id, " - + "identity_source_game_row_id, identity_source_game_tenant_key, " - + "identity_source_provenance_kind, version_number, version_state, " - + "version_state_epoch, is_script_only, created_at, updated_at) " - + "SELECT g.tenant_id, ?, g.canonical_tenant_id, g.id, g.tenant_id, " - + "g.tenant_identity_provenance_kind, 1, 'DRAFT', 1, FALSE, " - + "CURRENT_TIMESTAMP, CURRENT_TIMESTAMP FROM game g WHERE g.id = ? RETURNING id", - UUID.randomUUID(), - game.getId())); var version = - new VersionRepository(dsl).findById(inserted.get("id", Long.class)).orElseThrow(); - var target = - new TargetProof( - version.getCanonicalTenantId(), - version.getCanonicalVersionId(), - version.getId(), - version.getTenantId(), - version.getIdentitySourceGameRowId(), - version.getIdentitySourceGameTenantKey(), - version.getIdentitySourceProvenanceKind()); + new VersionRepository(dsl) + .findById(insertHistoricalDraftVersion(dsl, game.getId())) + .orElseThrow(); + var target = target(version); RealmPolicyGenesis reviewedGenesis = null; String reviewedBaseReference = null; if (retainReviewedV1) { @@ -883,6 +1030,184 @@ private GameDesignPublicationOperation prepareUnreservedOwnerOperation( return operation; } + private AuthoredDraftPublishSelection retainV502Selection( + DSLContext dsl, + DraftCommitCoordinatorRepository coordinator, + Version version, + String requestId) { + var target = target(version); + var owner = DraftCommitBinding.Owner.WORLD_MANAGEMENT; + var unit = + new DraftCommitBinding.AffectedUnit( + owner, "WORLD_TEMPLATE", "world-17", "ROOM_SCOPE", "room-scope-5", "7"); + var commit = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "historical-world-base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + owner, + "{\"completeWorldMutation\":{\"opaque\":\"retained\"}}")), + List.of(unit)); + String resultIdentity = "historical-world-result-" + commit.commitId(); + byte[] resultBytes = resultIdentity.getBytes(StandardCharsets.UTF_8); + var appliedUnits = + List.of( + Map.of( + "aggregateType", unit.aggregateType(), + "aggregateId", unit.aggregateId(), + "scopeType", unit.scopeType(), + "scopeId", unit.scopeId(), + "expectedEpoch", unit.expectedEpoch(), + "resultingEpoch", "8")); + String resultVector = + new String( + canonical( + List.of( + Map.of( + "owner", owner.name(), + "status", "APPLIED", + "commitId", commit.commitId().toString(), + "bindingDigest", commit.digest(), + "resultIdentity", resultIdentity, + "resultBytesBase64", Base64.getEncoder().encodeToString(resultBytes), + "appliedEpochs", appliedUnits))), + StandardCharsets.UTF_8); + + coordinator.claim(commit); + // Reproduce the V50.1 transitions under its installed guards. The current application + // writers require the terminal-operation table added after V50.2. + dsl.execute( + "INSERT INTO game_design_draft_commit_application_slot " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id) VALUES (?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + commit.requestId(), + commit.commitId()); + dsl.execute( + "UPDATE game_design_draft_commit SET workflow_state = 'APPLYING' WHERE request_id = ?", + commit.requestId()); + dsl.execute( + "UPDATE game_design_draft_commit_owner_result SET status = 'IN_PROGRESS' WHERE request_id = ? AND owner = ?", + commit.requestId(), + owner.name()); + dsl.execute( + "UPDATE game_design_draft_commit_owner_result SET status = 'APPLIED', result_commit_id = ?, " + + "result_binding_digest = ?, result_identity = ?, result_bytes = ?, applied_units_json = ? " + + "WHERE request_id = ? AND owner = ?", + commit.commitId(), + commit.digest(), + resultIdentity, + resultBytes, + new String(canonical(appliedUnits), StandardCharsets.UTF_8), + commit.requestId(), + owner.name()); + dsl.execute( + "INSERT INTO game_design_draft_commit_visibility_fence " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, input_digest, result_vector_json) " + + "VALUES (?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + commit.requestId(), + commit.commitId(), + commit.digest(), + resultVector); + dsl.execute( + "UPDATE game_design_draft_commit SET workflow_state = 'SYNCHRONIZED' WHERE request_id = ?", + commit.requestId()); + dsl.execute( + "INSERT INTO game_design_draft_commit_visibility " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, input_digest) " + + "VALUES (?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + commit.requestId(), + commit.commitId(), + commit.digest()); + coordinator.releaseApplicationSlot(commit); + + var intent = + new AuthoredDraftPublishSelection.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + requestId, + Long.toString(version.getVersionStateEpoch()), + "Historical selection for Version " + version.getVersionNumber(), + commit.requestId(), + commit.commitId(), + commit.digest()); + var selection = + AuthoredDraftPublishSelection.capture( + intent, + target, + coordinator.requireSynchronizedPublicationEvidence( + target, commit.requestId(), commit.commitId(), commit.digest())); + // V50.2 permits one selection per Version. The current reserve path assumes the + // V50.3 tenant/request key, so use the original guarded table for both reservations. + dsl.execute( + """ + INSERT INTO game_design_authored_draft_publish_selection + (canonical_tenant_id, canonical_version_id, game_design_version_row_id, + game_design_version_tenant_key, source_game_row_id, source_game_tenant_key, + source_provenance_kind, publish_request_id, version_state_epoch, selected_commit_request_id, + selected_commit_id, selected_commit_digest, selection_digest, selection_json) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind(), + intent.publishRequestId(), + version.getVersionStateEpoch(), + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest(), + selection.digest(), + selection.canonicalJson()); + return selection; + } + + private static TargetProof target(Version version) { + return new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + } + + private static long insertHistoricalDraftVersion(DSLContext dsl, long gameId) { + return insertHistoricalDraftVersion(dsl, gameId, 1); + } + + private static long insertHistoricalDraftVersion(DSLContext dsl, long gameId, int versionNumber) { + return dsl.fetchSingle( + """ + INSERT INTO version + (tenant_id, canonical_version_id, canonical_tenant_id, identity_source_game_row_id, + identity_source_game_tenant_key, identity_source_provenance_kind, version_number, + version_state, version_state_epoch, is_script_only, created_at, updated_at) + SELECT g.tenant_id, ?, g.canonical_tenant_id, g.id, g.tenant_id, + g.tenant_identity_provenance_kind, ?, 'DRAFT', 1, FALSE, + CURRENT_TIMESTAMP, CURRENT_TIMESTAMP + FROM game g WHERE g.id = ? + RETURNING id + """, + UUID.randomUUID(), + versionNumber, + gameId) + .get(0, long.class); + } + private byte[] historicalReviewedGenesisBytes( TargetProof target, RealmPolicyGenesis policyGenesis, diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java index db0c4959dd..f1e89a8139 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java @@ -3,11 +3,23 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.UUID; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import net.firedevops.firemud.common.authoring.DraftBaseReference; @@ -16,7 +28,13 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyReadGrpcCodec; import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; import net.firedevops.firemud.gamedesign.draft.GameDesignReviewedBaseRepository; import net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup; @@ -29,6 +47,7 @@ import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationGrpcService; import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationRepository; import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationService; import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublishedEvidence; @@ -39,6 +58,8 @@ import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; +import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryPolicyServiceGrpc; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; @@ -50,6 +71,7 @@ import org.jooq.impl.DefaultConfiguration; import org.jooq.impl.DefaultExecuteListenerProvider; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.jooq.autoconfigure.SpringTransactionProvider; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -455,6 +477,118 @@ void sealRollbackLeavesNoAssociationAndExactPublicationRetryAllocatesOneStableId assertThat(replay.policySetDigest()).isEqualTo(first.policySetDigest()); } + @Test + void gameSessionMtlsReadsTheExactCommittedHumanPolicy(@TempDir Path directory) throws Exception { + Fixture fixture = fixture(true); + GameDesignPublicationOperation operation = fixture.prepare(true); + fixture.writePublish(operation, false); + var original = fixture.publicationReads().readPublishedSet(fixture.target()).orElseThrow(); + assertThat(original.policies()).hasSize(1); + var policy = original.policies().getFirst(); + + String namespace = "test"; + String serverUri = "spiffe://firemud/ns/test/sa/game-design-service"; + var pki = + LoopbackMtlsTestPki.create( + directory, + "Published realm policy test CA", + new LoopbackMtlsTestPki.IdentitySpec("server", serverUri, true), + new LoopbackMtlsTestPki.IdentitySpec( + "client", "spiffe://firemud/ns/test/sa/game-session-service", false)); + var auth = + new AuthTokenInterceptor( + new JwtUtil("testsecretkeytestsecretkeytest1234", 60_000L), + Set.of( + PublishedRealmEntryPolicyServiceGrpc.getResolvePublishedRealmEntryPolicyMethod() + .getFullMethodName(), + PublishedRealmEntryPolicyServiceGrpc.getListPublishedRealmEntryPoliciesMethod() + .getFullMethodName())); + var server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(pki.keyManagerFactory(pki.identity("server")))) + .trustManager(pki.trustManagerFactory()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + new RealmPolicyPublicationGrpcService(fixture.publicationReads(), namespace), + new GrpcPeerIdentityInterceptor(), + auth)) + .build() + .start(); + try { + var channel = + NettyChannelBuilder.forAddress("localhost", server.getPort()) + .sslContext( + GrpcSslContexts.forClient() + .trustManager(pki.trustManagerFactory()) + .keyManager(pki.keyManagerFactory(pki.identity("client"))) + .build()) + .build(); + try { + var stub = + PublishedRealmEntryPolicyServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(serverUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(serverUri)) + .withDeadlineAfter(5, TimeUnit.SECONDS); + var list = + new PublishedRealmEntryPolicyReadGrpcCodec.ListRequest( + namespace, + UUID.randomUUID(), + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()); + var complete = + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + list, + stub.listPublishedRealmEntryPolicies( + PublishedRealmEntryPolicyReadGrpcCodec.toRequest(list))); + assertThat(complete.policySetDigest()).isEqualTo(original.policySetDigest()); + assertThat(complete.operationBytes()).containsExactly(original.operationBytes()); + assertThat(complete.captureBytes()).containsExactly(original.captureBytes()); + assertThat(complete.terminalEvidenceBytes()) + .containsExactly(original.terminalEvidenceBytes()); + assertThat(complete.policies()) + .singleElement() + .satisfies( + found -> { + assertThat(found.policyId()).isEqualTo(policy.policyId()); + assertThat(found.policyDigest()).isEqualTo(policy.policyDigest()); + }); + + var exact = + new PublishedRealmEntryPolicyReadGrpcCodec.ResolveRequest( + namespace, + UUID.randomUUID(), + list.canonicalTenantId(), + list.canonicalVersionId(), + policy.source().policy().worldSlug(), + policy.source().policy().realmSlug()); + assertThat( + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + exact, + stub.resolvePublishedRealmEntryPolicy( + PublishedRealmEntryPolicyReadGrpcCodec.toRequest(exact)))) + .isEqualTo(complete); + + var otherWorld = + PublishedRealmEntryPolicyReadGrpcCodec.toRequest(exact).toBuilder() + .setWorldSlug("different-world") + .build(); + assertThatThrownBy(() -> stub.resolvePublishedRealmEntryPolicy(otherWorld)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + denied -> + assertThat(denied.getStatus().getCode()).isEqualTo(Status.Code.NOT_FOUND)); + } finally { + assertThat(channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } finally { + assertThat(server.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + @Test void missingPolicyCaptureFailsClosedForEveryFullVersionRelease() throws Exception { Fixture unrelated = fixture(false); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java index 603ac9cbbb..8b09044488 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java @@ -2,6 +2,11 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import java.nio.file.Files; import java.nio.file.Path; @@ -9,9 +14,13 @@ import java.util.Map; import java.util.Objects; import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; @@ -20,6 +29,7 @@ import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository.DeliveryClaim; import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.service.impl.GameAuthoredWorldSourceDeliveryService; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; @@ -202,6 +212,64 @@ void sourceAndDeliveryIntentRollBackTogether() { assertThat(fixture.dsl().fetchCount(DELIVERIES)).isZero(); } + @Test + void concurrentExactDeliveriesReturnOneDurableAckAndRefuseChangedReceipt() throws Exception { + Fixture fixture = fixture(null); + AuthoredWorldSourceEvidence source = fixture.registerFresh(33); + DeliveryClaim pending = fixture.deliveryRepository().read(source.operationId()).orElseThrow(); + CommittedReceipt receipt = + committedReceipt(pending.request(), uuid("44444444-4444-4444-8444-444444444444"), 'a'); + WorldAuthoredSourceIntakeClient worldClient = mock(WorldAuthoredSourceIntakeClient.class); + var intakeCalls = new CountDownLatch(2); + var releaseIntake = new CountDownLatch(1); + when(worldClient.intake(pending.request())) + .thenAnswer( + invocation -> { + intakeCalls.countDown(); + assertThat(releaseIntake.await(10, TimeUnit.SECONDS)).isTrue(); + return receipt; + }); + when(worldClient.read(any(WorldAuthoredSourceIntakeGrpcCodec.ReadRequest.class))) + .thenReturn(receipt); + var delivery = + new GameAuthoredWorldSourceDeliveryService( + fixture.deliveryRepository(), worldClient, fixture.transactionManager(), NAMESPACE); + var executor = Executors.newFixedThreadPool(2); + try { + var first = executor.submit(() -> delivery.deliver(source.operationId())); + var second = executor.submit(() -> delivery.deliver(source.operationId())); + assertThat(intakeCalls.await(10, TimeUnit.SECONDS)).isTrue(); + releaseIntake.countDown(); + + DeliveryClaim firstResult = first.get(10, TimeUnit.SECONDS); + assertThat(second.get(10, TimeUnit.SECONDS)).isEqualTo(firstResult); + assertThat(firstResult.acknowledgedReceipt()).contains(receipt); + assertThat(fixture.deliveryRepository().read(source.operationId())).contains(firstResult); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isEqualTo(1); + verify(worldClient, times(2)).intake(pending.request()); + verify(worldClient, times(2)).read(any(WorldAuthoredSourceIntakeGrpcCodec.ReadRequest.class)); + } finally { + releaseIntake.countDown(); + executor.shutdownNow(); + } + + CommittedReceipt changed = committedReceipt(pending.request(), receipt.operationId(), 'b'); + assertThatThrownBy( + () -> + fixture + .transactionTemplate() + .execute(status -> fixture.deliveryRepository().acknowledge(pending, changed))) + .isInstanceOf(GameAuthoredWorldSourceDeliveryRepository.DeliveryConflictException.class) + .hasMessageContaining("different World receipt"); + assertThat( + fixture + .deliveryRepository() + .read(source.operationId()) + .orElseThrow() + .acknowledgedReceipt()) + .contains(receipt); + } + @Test void databaseRejectsDeliverySourceRebindingAndReceiptMutation() { Fixture fixture = fixture(null); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java index 086d6446cc..e9a73d6444 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java @@ -4,8 +4,16 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.Map; +import java.util.Objects; import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; import org.flywaydb.core.Flyway; @@ -20,6 +28,8 @@ 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.TransactionSystemException; import org.springframework.transaction.support.TransactionTemplate; class GameTenantCreationRepositoryIntegrationTest { @@ -29,6 +39,7 @@ class GameTenantCreationRepositoryIntegrationTest { DSL.field(DSL.name("operation_id"), UUID.class); private static final String NAMESPACE = "fresh-tenant-test"; private static final String SOURCE_KEY = "new-game-tenant-01"; + private static final String NAME = "World"; private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); private static final GameDesignPostgresIntegrationFixture postgres = @@ -65,6 +76,97 @@ void exactRetryReturnsCommittedReceiptWithoutSecondGameWrite() { assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); } + @Test + void concurrentDuplicateCreationRequestsConvergeOnOneUuidAndReceipt() throws Exception { + Fixture fixture = fixture(); + var firstBackend = new CompletableFuture(); + var secondBackend = new CompletableFuture(); + var allowFirstCommit = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> + fixture.inTransaction( + () -> { + FreshTenantCreationEvidence receipt = createCandidate(fixture); + RowVersions rowVersions = ownerRowVersions(fixture.dsl, receipt); + firstBackend.complete(backendPid(fixture.dsl)); + assertThat(allowFirstCommit.await(30, TimeUnit.SECONDS)) + .as("release of the first creation transaction") + .isTrue(); + return new OwnerWrite(receipt, rowVersions); + })); + int firstPid = firstBackend.get(10, TimeUnit.SECONDS); + + Future second = + executor.submit( + () -> + fixture.inTransaction( + () -> { + fixture.dsl.execute("SET LOCAL statement_timeout = '15s'"); + secondBackend.complete(backendPid(fixture.dsl)); + return createCandidate(fixture); + })); + int secondPid = secondBackend.get(10, TimeUnit.SECONDS); + assertBackendWaitsForOwner(fixture.dsl, secondPid, firstPid); + assertThat(fixture.repository.read(REQUEST_ID, NAMESPACE)).isEmpty(); + assertThat(fixture.dsl.fetchCount(GAME)).isZero(); + allowFirstCommit.countDown(); + + OwnerWrite committed = first.get(10, TimeUnit.SECONDS); + assertThat(second.get(10, TimeUnit.SECONDS)).isEqualTo(committed.receipt()); + assertThat(fixture.repository.read(REQUEST_ID, NAMESPACE)).contains(committed.receipt()); + FreshTenantCreationEvidence exactRetry = + fixture.inTransaction(() -> createCandidate(fixture)); + assertThat(exactRetry).isEqualTo(committed.receipt()); + + RowVersions rowVersions = ownerRowVersions(fixture.dsl, committed.receipt()); + assertThat(rowVersions).isEqualTo(committed.rowVersions()); + assertThat(rowVersions.game()).isEqualTo(rowVersions.operation()); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + } finally { + allowFirstCommit.countDown(); + executor.shutdownNow(); + } + } + + @Test + void claimWithoutCompletionCannotCommitAndSameRequestCanRetry() { + Fixture fixture = fixture(); + String requestDigest = + GameTenantCreationDigest.requestDigest(NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, null); + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> + fixture.dsl.execute( + """ + INSERT INTO game_tenant_creation_operations + (operation_id, schema_version, target_namespace, creation_request_id, + request_digest, source_game_tenant_key, name, status) + VALUES (?, 1, ?, ?, ?, ?, ?, 'PENDING') + """, + UUID.randomUUID(), + NAMESPACE, + REQUEST_ID, + requestDigest, + SOURCE_KEY, + NAME))) + .isInstanceOf(TransactionSystemException.class) + .hasStackTraceContaining("Game tenant creation operation cannot commit while pending"); + + assertThat(fixture.repository.read(REQUEST_ID, NAMESPACE)).isEmpty(); + assertThat(fixture.dsl.fetchCount(GAME)).isZero(); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isZero(); + + FreshTenantCreationEvidence retry = fixture.inTransaction(() -> createCandidate(fixture)); + assertThat(fixture.repository.read(REQUEST_ID, NAMESPACE)).contains(retry); + assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); + } + @Test void completedCreationEvidenceCannotBeChangedOrDeleted() { Fixture fixture = fixture(); @@ -99,6 +201,47 @@ void completedCreationEvidenceCannotBeChangedOrDeleted() { assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); } + private static FreshTenantCreationEvidence createCandidate(Fixture fixture) { + return fixture.repository.createCandidate(NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, null); + } + + private static int backendPid(DSLContext dsl) { + return Objects.requireNonNull(dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + } + + private static void assertBackendWaitsForOwner(DSLContext dsl, int contenderPid, int ownerPid) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadline) { + if (Boolean.TRUE.equals( + dsl.fetchSingle("SELECT ? = ANY(pg_blocking_pids(?))", ownerPid, contenderPid) + .get(0, Boolean.class))) { + return; + } + TimeUnit.MILLISECONDS.sleep(10); + } + throw new AssertionError("The duplicate creation never waited for the original transaction"); + } + + private static RowVersions ownerRowVersions(DSLContext dsl, FreshTenantCreationEvidence receipt) { + var row = + dsl.fetchSingle( + """ + SELECT g.xmin::text AS game_xmin, op.xmin::text AS operation_xmin + FROM game g + JOIN game_tenant_creation_operations op + ON op.source_game_row_id = g.id AND op.canonical_tenant_id = g.canonical_tenant_id + WHERE g.id = ? AND g.tenant_id = ? AND g.canonical_tenant_id = ? + AND op.operation_id = ? AND op.status = 'COMPLETED' + """, + receipt.sourceGameRowId(), + receipt.sourceGameTenantKey(), + receipt.canonicalTenantId(), + receipt.operationId()); + return new RowVersions( + row.get("game_xmin", String.class), row.get("operation_xmin", String.class)); + } + private Fixture fixture() { String schema = "game_design_creation_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = postgres.dataSource(); @@ -119,6 +262,7 @@ private Fixture fixture() { TransactionTemplate transactionTemplate = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + transactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); GameRepository gameRepository = new GameRepository(dsl); @@ -126,6 +270,10 @@ private Fixture fixture() { return new Fixture(dsl, repository, transactionTemplate); } + private record OwnerWrite(FreshTenantCreationEvidence receipt, RowVersions rowVersions) {} + + private record RowVersions(String game, String operation) {} + private record Fixture( DSLContext dsl, GameTenantCreationRepository repository, diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryIntegrationTest.java index 1b596c26ef..cf560dc0ff 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryIntegrationTest.java @@ -3,9 +3,13 @@ import static org.assertj.core.api.Assertions.assertThat; import java.time.LocalDateTime; +import java.util.UUID; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; @@ -16,6 +20,9 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; +import org.springframework.transaction.PlatformTransactionManager; +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; @@ -48,6 +55,53 @@ static void configure(DynamicPropertyRegistry registry) { } @Autowired private VersionAssetArtifactRepository repository; + @Autowired private VersionAssetArtifactService artifactService; + @Autowired private GameRepository gameRepository; + @Autowired private VersionRepository versionRepository; + @Autowired private PlatformTransactionManager transactionManager; + + @Test + void stagedIntentCommitsThroughSpringProxyBeforeCallingTransactionRollsBack() { + TransactionTemplate owner = new TransactionTemplate(transactionManager); + owner.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + Game game = new Game(); + game.setTenantId(UUID.randomUUID().toString()); + game.setName("staged intent proof"); + game.setDescription("actual owner source"); + Game storedGame = owner.execute(status -> gameRepository.save(game)); + assertThat(storedGame).isNotNull(); + Version version = new Version(); + version.setTenantId(storedGame.getTenantId()); + version.setVersionNumber(1); + version.setNotes("staged intent proof"); + Version storedVersion = owner.execute(status -> versionRepository.save(version)); + assertThat(storedVersion).isNotNull(); + String workflow = "stable-staged-proof-" + UUID.randomUUID(); + var committed = + owner.execute( + status -> { + var staged = + artifactService.stageExport( + storedGame.getTenantId(), storedVersion.getId(), 1, workflow); + status.setRollbackOnly(); + return staged; + }); + assertThat(committed).isNotNull(); + assertThat(committed.artifactState()).isEqualTo("STAGED"); + assertThat(committed.stateEpoch()).isEqualTo(1L); + assertThat(artifactService.getState(storedGame.getTenantId(), storedVersion.getId())) + .isEqualTo(committed); + assertThat( + artifactService.stageExport( + storedGame.getTenantId(), storedVersion.getId(), 1, workflow)) + .isEqualTo(committed); + assertThat( + repository + .findByTenantIdAndVersionId(storedGame.getTenantId(), storedVersion.getId()) + .orElseThrow() + .getManifestSchemaVersion()) + .isNull(); + } @Test void saveAndFindRoundTripTimestampFields() { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java index b69946852a..73d67ab6d7 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java @@ -145,6 +145,38 @@ void springOwnerCommitsNonemptySnapshotBeforeIndependentReadback() { .containsExactly(SOURCE_BYTES); } + @Test + void committedSnapshotSurvivesAnOuterOwnerCallerRollback() { + Fixture fixture = fixture(); + var transactionManager = new DataSourceTransactionManager(fixture.dataSource); + var service = + new VersionAssetPublicationServiceImpl( + transactionManager, new VersionAssetPublicationRepository(fixture.dsl)); + var caller = new TransactionTemplate(transactionManager); + + var snapshot = + Objects.requireNonNull( + caller.execute( + status -> { + fixture.dsl.execute("CREATE TABLE snapshot_caller_rollback_marker(id bigint)"); + var committed = service.freezeOrReadSnapshot(fixture.tenantId, 1); + assertThat(independentSnapshot(fixture)).isEqualTo(committed); + status.setRollbackOnly(); + return committed; + })); + + var independent = DSL.using(fixture.dataSource, SQLDialect.POSTGRES); + assertThat( + independent + .fetchSingle("SELECT to_regclass('snapshot_caller_rollback_marker')::text") + .get(0, String.class)) + .isNull(); + assertThat(snapshot.items()).hasSize(1); + assertThat(independentSnapshot(fixture)).isEqualTo(snapshot); + assertThat(service.readFrozenAssetBytes(fixture.tenantId, 1, snapshot.items().getFirst())) + .containsExactly(SOURCE_BYTES); + } + @Test void springOwnerCommitsFoundedEmptySnapshotBeforeIndependentReadback() { Fixture fixture = foundedEmptyFixture(); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationMinioPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationMinioPostgresIntegrationTest.java new file mode 100644 index 0000000000..823bd302fe --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationMinioPostgresIntegrationTest.java @@ -0,0 +1,866 @@ +package net.firedevops.firemud.gamedesign.service; + +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.doAnswer; + +import com.github.dockerjava.api.model.ExposedPort; +import com.github.dockerjava.api.model.PortBinding; +import com.github.dockerjava.api.model.Ports; +import java.io.IOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.config.AssetStoreProperties; +import net.firedevops.firemud.gamedesign.draft.IsolatedAssetSourceOwnerSetup; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.GameAsset; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; +import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.impl.AssetExportServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.VersionAssetArtifactServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.VersionAssetExportCandidateServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.VersionAssetPublicationServiceImpl; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.AdditionalAnswers; +import org.mockito.Mockito; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.io.FileSystemResource; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.containers.wait.strategy.Wait; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.utility.DockerImageName; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.S3Configuration; +import software.amazon.awssdk.services.s3.model.CreateBucketRequest; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import tools.jackson.databind.ObjectMapper; + +/** + * Composes the Flyway-backed owner rows and real publication services with the AWS SDK and a + * run-owned MinIO provider. This proves the private PostgreSQL-to-object-store producer boundary; + * it does not prove public delivery, creator authorization, release activation, or launch. The + * existing isolated source fixture supplies reviewed ASSET_REFERENCE authority. The provider uses + * the Compose MinIO image in a disposable container with a random loopback endpoint and + * credentials. + */ +@Testcontainers(disabledWithoutDocker = true) +class VersionAssetPublicationMinioPostgresIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final String TENANT_ID = UUID.randomUUID().toString(); + private static final String PUBLIC_BASE_URL = "https://assets.example.invalid/assets"; + private static final String WORKFLOW_ID = "minio-postgres-composition-workflow"; + private static final int MINIO_PORT = 9000; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private S3Client s3Client; + private String bucket; + private GenericContainer minio; + + @AfterEach + void closeMinioResources() { + try { + if (s3Client != null) { + s3Client.close(); + } + } finally { + if (minio != null) { + minio.close(); + } + } + } + + @Test + void failedDatabaseCandidateWriteRollsBackAllEvidenceAndEpoch() { + CandidateFixture prepared = candidateTransactionFixture(); + Fixture fixture = prepared.fixture(); + Version version = prepared.version(); + Map before = candidateArtifactRow(fixture, version); + fixture + .dsl() + .execute( + "CREATE FUNCTION fail_candidate_update() RETURNS TRIGGER AS $$ BEGIN " + + "RAISE EXCEPTION 'test candidate persistence failure'; END; $$ LANGUAGE plpgsql"); + fixture + .dsl() + .execute( + "CREATE TRIGGER trg_fail_candidate_update AFTER UPDATE ON version_asset_artifact " + + "FOR EACH ROW EXECUTE FUNCTION fail_candidate_update()"); + try { + assertThatThrownBy( + () -> + fixture + .candidateService() + .recordExportCandidate(version.getTenantId(), 1, prepared.candidate())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("test candidate persistence failure"); + Fixture readback = fixtureFromSchema(fixture.schema(), fixture.dataSource()); + // Compare every persisted column, including the frozen origin, and the row version. + assertThat(candidateArtifactRow(readback, version)).isEqualTo(before); + assertThatThrownBy( + () -> readback.candidateService().readExportCandidate(version.getTenantId(), 1)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_EXPORT_CANDIDATE_NOT_FOUND"); + } finally { + fixture + .dsl() + .execute("DROP TRIGGER IF EXISTS trg_fail_candidate_update ON version_asset_artifact"); + fixture.dsl().execute("DROP FUNCTION IF EXISTS fail_candidate_update()"); + } + assertThat( + fixture + .candidateService() + .recordExportCandidate(version.getTenantId(), 1, prepared.candidate())) + .isEqualTo(prepared.candidate()); + } + + @Test + void concurrentExactCandidateRecordsCommitOneEpochAndCallerRollbackCannotUndoIt() + throws Exception { + CandidateFixture prepared = candidateTransactionFixture(); + Fixture fixture = prepared.fixture(); + Version version = prepared.version(); + Fixture firstOwner = fixtureFromSchema(fixture.schema(), fixture.dataSource()); + Fixture secondOwner = fixtureFromSchema(fixture.schema(), fixture.dataSource()); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> { + ready.countDown(); + awaitCandidateStart(start); + return firstOwner + .candidateService() + .recordExportCandidate(version.getTenantId(), 1, prepared.candidate()); + }); + Future second = + executor.submit( + () -> { + ready.countDown(); + awaitCandidateStart(start); + return secondOwner + .candidateService() + .recordExportCandidate(version.getTenantId(), 1, prepared.candidate()); + }); + // Coordinate competing callers; this does not independently measure database lock waiting. + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + assertThat(first.get(20, TimeUnit.SECONDS)).isEqualTo(prepared.candidate()); + assertThat(second.get(20, TimeUnit.SECONDS)).isEqualTo(prepared.candidate()); + } finally { + start.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + + Fixture committed = fixtureFromSchema(fixture.schema(), fixture.dataSource()); + VersionAssetArtifact artifact = + committed + .artifactRepository() + .findByTenantIdAndVersionId(version.getTenantId(), version.getId()) + .orElseThrow(); + assertThat(artifact.getArtifactState().name()).isEqualTo("STAGED"); + assertThat(artifact.getStateEpoch()).isEqualTo(2L); + assertThat(artifact.getLastWorkflowId()).isEqualTo(WORKFLOW_ID + "-candidate-transaction"); + assertThat(committed.candidateService().readExportCandidate(version.getTenantId(), 1)) + .isEqualTo(prepared.candidate()); + Map original = candidateArtifactRow(committed, version); + + fixture + .transactionTemplate() + .executeWithoutResult( + status -> { + assertThat( + fixture + .candidateService() + .recordExportCandidate(version.getTenantId(), 1, prepared.candidate())) + .isEqualTo(prepared.candidate()); + status.setRollbackOnly(); + }); + Fixture afterRollback = fixtureFromSchema(fixture.schema(), fixture.dataSource()); + assertThat(afterRollback.candidateService().readExportCandidate(version.getTenantId(), 1)) + .isEqualTo(prepared.candidate()); + assertThat(candidateArtifactRow(afterRollback, version)).isEqualTo(original); + } + + @Test + void candidateEpochOverflowWritesNothing() { + CandidateFixture prepared = candidateTransactionFixture(); + Fixture fixture = prepared.fixture(); + Version version = prepared.version(); + fixture + .dsl() + .execute( + "UPDATE version_asset_artifact SET state_epoch = ? WHERE tenant_id = ? AND version_id = ?", + Long.MAX_VALUE, + version.getTenantId(), + version.getId()); + Map before = candidateArtifactRow(fixture, version); + assertThatThrownBy( + () -> + fixture + .candidateService() + .recordExportCandidate(version.getTenantId(), 1, prepared.candidate())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_EXPORT_CANDIDATE_CONFLICT") + .hasCauseInstanceOf(ArithmeticException.class); + Fixture readback = fixtureFromSchema(fixture.schema(), fixture.dataSource()); + assertThat(candidateArtifactRow(readback, version)).isEqualTo(before); + assertThatThrownBy( + () -> readback.candidateService().readExportCandidate(version.getTenantId(), 1)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_EXPORT_CANDIDATE_NOT_FOUND"); + } + + // Controlled source and manifest inputs exercise only the private PostgreSQL candidate owner; + // these cases neither require MinIO nor establish production publication authorization. + private CandidateFixture candidateTransactionFixture() { + Fixture fixture = fixture(); + Game game = saveGame(fixture); + Version version = saveVersion(fixture, game, 1); + GameAsset asset = + saveAsset( + fixture, + game.getTenantId(), + "candidate-transaction.png", + "image/png", + bytes("candidate transaction source bytes")); + commitAssetSource(fixture, version, asset); + ExportSnapshot snapshot = + fixture.publicationService().freezeOrReadSnapshot(game.getTenantId(), 1); + stageArtifact(fixture, game, version, WORKFLOW_ID + "-candidate-transaction"); + List digests = + snapshot.items().stream() + .map( + source -> + new PublishedArtifactDigest( + source.usageKey(), + "BINARY", + "artifacts/sha256/" + source.contentDigest().substring("sha256:".length()), + source.contentDigest(), + source.contentType(), + 1)) + .toList(); + assertThat(digests).hasSize(1); + FrozenAssetExportCandidate candidate = + new FrozenAssetExportCandidate( + new ExportedAssetManifest( + "sha256:" + sha256Hex(bytes("controlled candidate transaction manifest")), + 1, + digests.stream().map(PublishedArtifactDigest::usageKey).toList(), + digests), + PUBLIC_BASE_URL); + assertThat( + fixture + .artifactRepository() + .findByTenantIdAndVersionId(game.getTenantId(), version.getId()) + .orElseThrow() + .getStateEpoch()) + .isEqualTo(1L); + return new CandidateFixture(fixture, version, candidate); + } + + private Map candidateArtifactRow(Fixture fixture, Version version) { + return fixture + .dsl() + .fetchSingle( + "SELECT row_to_json(a)::text AS evidence, a.xmin::text AS row_version " + + "FROM version_asset_artifact a WHERE tenant_id = ? AND version_id = ?", + version.getTenantId(), + version.getId()) + .intoMap(); + } + + private static void awaitCandidateStart(CountDownLatch start) { + try { + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent candidate test start signal timed out"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Concurrent candidate test was interrupted", exception); + } + } + + private record CandidateFixture( + Fixture fixture, Version version, FrozenAssetExportCandidate candidate) {} + + @Test + void composesPostgresSnapshotAndCandidateWithMinioBeforeWriteAndRetriesAfterLostAcknowledgement() + throws IOException { + String accessKey = UUID.randomUUID().toString(); + String secretKey = UUID.randomUUID().toString(); + minio = + new GenericContainer<>(composeMinioImage()) + .withCommand("server", "/data") + .withEnv("MINIO_ROOT_USER", accessKey) + .withEnv("MINIO_ROOT_PASSWORD", secretKey) + .withExposedPorts(MINIO_PORT) + .withCreateContainerCmdModifier( + command -> + Objects.requireNonNull(command.getHostConfig()) + .withPortBindings( + new PortBinding( + Ports.Binding.bindIp("127.0.0.1"), ExposedPort.tcp(MINIO_PORT)))) + .waitingFor(Wait.forHttp("/minio/health/live").forPort(MINIO_PORT)); + minio.start(); + String endpoint = "http://" + minio.getHost() + ":" + minio.getMappedPort(MINIO_PORT); + s3Client = newS3Client(endpoint, accessKey, secretKey); + String ownedBucket = "firemud-asset-pg-" + UUID.randomUUID().toString().replace("-", ""); + s3Client.createBucket(CreateBucketRequest.builder().bucket(ownedBucket).build()); + bucket = ownedBucket; + + Fixture fixture = fixture(); + Game game = saveGame(fixture); + Version version = saveVersion(fixture, game, 1); + byte[] publishedBytes = bytes("Flyway-backed mapped asset bytes"); + GameAsset asset = + saveAsset( + fixture, game.getTenantId(), "composition-proof-logo.png", "image/png", publishedBytes); + commitAssetSource(fixture, version, asset); + stageArtifact(fixture, game, version, WORKFLOW_ID); + + String publishedKey = "artifacts/sha256/" + sha256Hex(publishedBytes); + AtomicBoolean losePutAcknowledgement = new AtomicBoolean(true); + AtomicBoolean loseFirstReadback = new AtomicBoolean(true); + AtomicReference candidateBeforePut = new AtomicReference<>(); + AtomicReference artifactXminBeforePut = new AtomicReference<>(); + S3Client interruptedClient = + observingClient( + s3Client, + request -> { + assertThat(request.bucket()).isEqualTo(bucket); + assertPersistedSnapshotAndCandidate( + fixture.schema(), + fixture.dataSource(), + game.getTenantId(), + version.getId(), + asset.getId(), + "composition-proof-logo.png", + publishedBytes, + "image/png", + publishedKey, + candidateBeforePut, + artifactXminBeforePut); + }, + publishedKey, + losePutAcknowledgement, + loseFirstReadback); + + AssetExportServiceImpl interruptedExporter = + newExporter(fixture, interruptedClient, bucket, endpoint); + assertThatThrownBy(() -> interruptedExporter.exportAssets(game.getTenantId(), 1)) + .isInstanceOf(AssetExportOutcomePendingException.class) + .hasMessageContaining("exact object readback is unavailable"); + assertThat(losePutAcknowledgement.get()).isFalse(); + assertThat(loseFirstReadback.get()).isFalse(); + + assertStoredObject(publishedKey, publishedBytes, "image/png"); + assertThat(candidateBeforePut.get()).isNotNull(); + assertThat(artifactXminBeforePut.get()).isNotBlank(); + + Fixture reconstructed = fixtureFromSchema(fixture.schema(), fixture.dataSource()); + ExportedAssetManifest retry = + newExporter(reconstructed, s3Client, bucket, endpoint).exportAssets(game.getTenantId(), 1); + assertThat(retry).isEqualTo(candidateBeforePut.get().manifest()); + assertThat(candidateBeforePut.get().publicBaseUrl()).isEqualTo(PUBLIC_BASE_URL); + assertStoredObject(publishedKey, publishedBytes, "image/png"); + String manifestKey = "manifests/sha256/" + retry.manifestHash().substring("sha256:".length()); + byte[] storedManifest = readObject(manifestKey, "application/json").asByteArray(); + assertThat(sha256Hex(storedManifest)) + .isEqualTo(retry.manifestHash().substring("sha256:".length())); + assertThat(new String(storedManifest, StandardCharsets.UTF_8)) + .contains("composition-proof-logo.png"); + + Fixture afterRetry = fixtureFromSchema(fixture.schema(), fixture.dataSource()); + assertThat(afterRetry.candidateService().readExportCandidate(game.getTenantId(), 1)) + .isEqualTo(candidateBeforePut.get()); + ExportSnapshot retriedSnapshot = + afterRetry.publicationService().readFrozenSnapshot(game.getTenantId(), 1); + assertThat(retriedSnapshot.versionId()).isEqualTo(version.getId()); + assertThat(retriedSnapshot.items()).hasSize(1); + assertThat( + afterRetry + .publicationService() + .readFrozenAssetBytes(game.getTenantId(), 1, retriedSnapshot.items().getFirst())) + .isEqualTo(publishedBytes); + assertThat(retriedSnapshot.items().get(0).contentDigest()) + .isEqualTo("sha256:" + sha256Hex(publishedBytes)); + assertThat(artifactXmin(afterRetry.dsl(), game.getTenantId(), version.getId())) + .isEqualTo(artifactXminBeforePut.get()); + VersionAssetArtifact retainedCandidate = + afterRetry + .artifactRepository() + .findByTenantIdAndVersionId(game.getTenantId(), version.getId()) + .orElseThrow(); + assertThat(retainedCandidate.getStateEpoch()).isEqualTo(2L); + assertThat(retainedCandidate.getManifestHash()).isEqualTo(retry.manifestHash()); + assertThat( + afterRetry + .versionRepository() + .findByTenantIdAndVersionNumber(game.getTenantId(), 1) + .orElseThrow() + .getVersionState() + .name()) + .isEqualTo("DRAFT"); + + byte[] conflictingBytes = bytes("pre-existing conflicting object"); + byte[] requestedConflictBytes = bytes("requested immutable conflict bytes"); + String conflictKey = "artifacts/sha256/" + sha256Hex(requestedConflictBytes); + s3Client.putObject( + PutObjectRequest.builder() + .bucket(bucket) + .key(conflictKey) + .contentType("application/octet-stream") + .build(), + RequestBody.fromBytes(conflictingBytes)); + + Version conflictVersion = saveVersion(fixture, game, 2); + GameAsset conflictAsset = + saveAsset( + fixture, + game.getTenantId(), + "immutable-conflict.png", + "image/png", + requestedConflictBytes); + commitAssetSource(fixture, conflictVersion, conflictAsset); + stageArtifact(fixture, game, conflictVersion, WORKFLOW_ID + "-conflict"); + + Fixture conflictReadback = fixtureFromSchema(fixture.schema(), fixture.dataSource()); + S3Client conflictObservingClient = + observingClient( + s3Client, + request -> { + assertThat(request.bucket()).isEqualTo(bucket); + assertPersistedSnapshotAndCandidate( + fixture.schema(), + fixture.dataSource(), + game.getTenantId(), + conflictVersion.getId(), + conflictAsset.getId(), + "immutable-conflict.png", + requestedConflictBytes, + "image/png", + conflictKey, + new AtomicReference<>(), + new AtomicReference<>()); + }, + null, + new AtomicBoolean(false), + new AtomicBoolean(false)); + assertThatThrownBy( + () -> + newExporter(conflictReadback, conflictObservingClient, bucket, endpoint) + .exportAssets(game.getTenantId(), 2)) + .isInstanceOf(IllegalStateException.class) + .hasMessageStartingWith("IMMUTABLE_OBJECT_CONFLICT"); + assertStoredObject(conflictKey, conflictingBytes, "application/octet-stream"); + } + + private void assertPersistedSnapshotAndCandidate( + String schema, + DriverManagerDataSource dataSource, + String tenantId, + long versionId, + long assetId, + String expectedUsageKey, + byte[] sourceBytes, + String contentType, + String expectedArtifactKey, + AtomicReference capturedCandidate, + AtomicReference capturedArtifactXmin) { + Fixture independentlyReconstructed = fixtureFromSchema(schema, dataSource); + Version version = + independentlyReconstructed + .versionRepository() + .findByTenantIdAndId(tenantId, versionId) + .orElseThrow(); + ExportSnapshot snapshot = + independentlyReconstructed + .publicationService() + .readFrozenSnapshot(tenantId, version.getVersionNumber()); + assertThat(snapshot.versionId()).isEqualTo(versionId); + assertThat(snapshot.canonicalTenantId()).isEqualTo(version.getCanonicalTenantId()); + assertThat(snapshot.canonicalVersionId()).isEqualTo(version.getCanonicalVersionId()); + assertThat(snapshot.items()).hasSize(1); + assertThat(snapshot.items().get(0).assetId()).isEqualTo(assetId); + assertThat( + independentlyReconstructed + .publicationService() + .readFrozenAssetBytes( + tenantId, version.getVersionNumber(), snapshot.items().getFirst())) + .isEqualTo(sourceBytes); + assertThat(snapshot.items().get(0).contentType()).isEqualTo(contentType); + assertThat(snapshot.items().get(0).contentDigest()) + .isEqualTo("sha256:" + sha256Hex(sourceBytes)); + + var header = + independentlyReconstructed + .dsl() + .fetchOne( + "SELECT item_count, captured_version_state_epoch FROM version_asset_export_snapshot " + + "WHERE tenant_id = ? AND version_id = ?", + tenantId, + versionId); + assertThat(header).isNotNull(); + assertThat(header.get("item_count", Integer.class)).isEqualTo(1); + assertThat(header.get("captured_version_state_epoch", Long.class)).isEqualTo(1L); + assertThat(snapshot.items().getFirst().usageKey()).isEqualTo(expectedUsageKey); + assertThat(version.getIdentitySourceGameTenantKey()).isEqualTo(tenantId); + assertThat(version.getIdentitySourceProvenanceKind()).isEqualTo("NEW_GAME_ROW"); + + FrozenAssetExportCandidate frozen = + independentlyReconstructed + .candidateService() + .readExportCandidate(tenantId, version.getVersionNumber()); + assertThat(frozen.publicBaseUrl()).isEqualTo(PUBLIC_BASE_URL); + ExportedAssetManifest candidate = frozen.manifest(); + assertThat(candidate.manifestSchemaVersion()).isEqualTo(1); + assertThat(candidate.artifactDigests()).hasSize(1); + PublishedArtifactDigest digest = candidate.artifactDigests().get(0); + assertThat(digest.usageKey()).isEqualTo(snapshot.items().get(0).usageKey()); + assertThat(digest.immutableObjectKey()).isEqualTo(expectedArtifactKey); + assertThat(digest.contentDigest()).isEqualTo("sha256:" + sha256Hex(sourceBytes)); + assertThat(digest.contentType()).isEqualTo(contentType); + assertThat(candidate.manifestHash()).matches("sha256:[0-9a-f]{64}"); + + VersionAssetArtifact storedArtifact = + independentlyReconstructed + .artifactRepository() + .findByTenantIdAndVersionId(tenantId, versionId) + .orElseThrow(); + assertThat(storedArtifact.getArtifactState().name()).isEqualTo("STAGED"); + assertThat(storedArtifact.getStateEpoch()).isEqualTo(2L); + assertThat(storedArtifact.getManifestHash()).isEqualTo(candidate.manifestHash()); + assertThat(storedArtifact.getManifestSchemaVersion()).isEqualTo(1); + assertThat(storedArtifact.getArtifactDigestsJson()) + .contains(expectedArtifactKey, digest.contentDigest()); + assertThat(storedArtifact.getPublishedObjectProofsJson()) + .contains(expectedArtifactKey, "manifests/sha256/", candidate.manifestHash()); + assertThat(storedArtifact.getCandidateSnapshotVersionId()).isEqualTo(versionId); + assertThat(storedArtifact.getExportedManifestAssetKeysJson()).contains(expectedUsageKey); + String rowXmin = artifactXmin(independentlyReconstructed.dsl(), tenantId, versionId); + if (capturedCandidate != null) { + capturedCandidate.compareAndSet(null, frozen); + } + if (capturedArtifactXmin != null) { + capturedArtifactXmin.compareAndSet(null, rowXmin); + } + } + + private Fixture fixture() { + String schema = "gd_minio_pg_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema); + return fixtureFromSchema(schema, dataSource); + } + + private Fixture fixtureFromSchema(String schema, DriverManagerDataSource dataSource) { + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + PlatformTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + transactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + GameRepository gameRepository = new GameRepository(dsl); + GameAssetRepository gameAssetRepository = new GameAssetRepository(dsl); + VersionRepository versionRepository = new VersionRepository(dsl); + VersionAssetPublicationRepository publicationRepository = + new VersionAssetPublicationRepository(dsl); + VersionAssetPublicationServiceImpl publicationService = + new VersionAssetPublicationServiceImpl(transactionManager, publicationRepository); + VersionAssetArtifactRepository artifactRepository = new VersionAssetArtifactRepository(dsl); + VersionAssetExportCandidateServiceImpl candidateService = + new VersionAssetExportCandidateServiceImpl( + versionRepository, + gameRepository, + new net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository(dsl), + artifactRepository, + publicationRepository, + transactionManager, + new ObjectMapper()); + return new Fixture( + schema, + dataSource, + dsl, + transactionManager, + transactionTemplate, + gameRepository, + gameAssetRepository, + versionRepository, + publicationService, + artifactRepository, + candidateService); + } + + private DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + return dataSource; + } + + private void migrate(DriverManagerDataSource dataSource, String schema) { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()) + .load() + .migrate(); + } + + private Game saveGame(Fixture fixture) { + Game game = new Game(); + game.setTenantId(TENANT_ID); + game.setName("PostgreSQL MinIO composition owner"); + game.setDescription("Canonical Game Design source row"); + return fixture.transactionTemplate().execute(status -> fixture.gameRepository().save(game)); + } + + private Version saveVersion(Fixture fixture, Game game, int versionNumber) { + Version version = new Version(); + version.setTenantId(game.getTenantId()); + version.setVersionNumber(versionNumber); + version.setNotes("PostgreSQL MinIO composition fixture"); + return fixture + .transactionTemplate() + .execute(status -> fixture.versionRepository().save(version)); + } + + private GameAsset saveAsset( + Fixture fixture, String tenantId, String fileName, String contentType, byte[] data) { + GameAsset asset = new GameAsset(); + asset.setTenantId(tenantId); + asset.setFileName(fileName); + asset.setContentType(contentType); + asset.setData(data); + return fixture + .transactionTemplate() + .execute(status -> fixture.gameAssetRepository().save(asset)); + } + + private void commitAssetSource(Fixture fixture, Version version, GameAsset asset) { + fixture + .transactionTemplate() + .executeWithoutResult( + status -> + IsolatedAssetSourceOwnerSetup.upsert( + fixture.dsl(), + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()), + asset.getId(), + asset.getFileName())); + } + + private void stageArtifact(Fixture fixture, Game game, Version version, String workflowId) { + VersionAssetArtifactServiceImpl stageService = + new VersionAssetArtifactServiceImpl( + fixture.artifactRepository(), + null, + fixture.versionRepository(), + null, + null, + null, + null, + null, + new ObjectMapper()); + fixture + .transactionTemplate() + .execute( + status -> + stageService.stageExport( + game.getTenantId(), version.getId(), version.getVersionNumber(), workflowId)); + } + + private AssetExportServiceImpl newExporter( + Fixture fixture, S3Client client, String bucket, String endpoint) { + AssetStoreProperties properties = new AssetStoreProperties(); + properties.setEndpoint(endpoint); + properties.setPublicBaseUrl(PUBLIC_BASE_URL); + properties.setBucket(bucket); + properties.setRegion("us-east-1"); + return new AssetExportServiceImpl( + fixture.publicationService(), fixture.candidateService(), client, properties); + } + + private S3Client newS3Client(String endpoint, String accessKey, String secretKey) { + return S3Client.builder() + .endpointOverride(URI.create(endpoint)) + .credentialsProvider( + StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey))) + .region(Region.US_EAST_1) + .serviceConfiguration(S3Configuration.builder().pathStyleAccessEnabled(true).build()) + .build(); + } + + private S3Client observingClient( + S3Client delegate, + Consumer beforePut, + String loseAcknowledgementKey, + AtomicBoolean losePutAcknowledgement, + AtomicBoolean loseFirstReadback) { + S3Client observer = Mockito.mock(S3Client.class, AdditionalAnswers.delegatesTo(delegate)); + doAnswer( + invocation -> { + PutObjectRequest request = invocation.getArgument(0, PutObjectRequest.class); + beforePut.accept(request); + var response = + delegate.putObject(request, invocation.getArgument(1, RequestBody.class)); + if (request.key().equals(loseAcknowledgementKey) + && losePutAcknowledgement.compareAndSet(true, false)) { + throw SdkClientException.builder() + .message("simulated lost SDK acknowledgement after successful MinIO PUT") + .build(); + } + return response; + }) + .when(observer) + .putObject(any(PutObjectRequest.class), any(RequestBody.class)); + doAnswer( + invocation -> { + GetObjectRequest request = invocation.getArgument(0, GetObjectRequest.class); + if (request.key().equals(loseAcknowledgementKey) + && loseFirstReadback.compareAndSet(true, false)) { + throw SdkClientException.builder() + .message("simulated unavailable readback after lost MinIO PUT acknowledgement") + .build(); + } + return delegate.getObject(request); + }) + .when(observer) + .getObject(any(GetObjectRequest.class)); + return observer; + } + + private ResponseBytes readObject(String key, String contentType) { + ResponseBytes response = + s3Client.getObjectAsBytes(GetObjectRequest.builder().bucket(bucket).key(key).build()); + assertThat(response.response().contentType()).isEqualTo(contentType); + assertThat(response.response().contentLength()).isEqualTo((long) response.asByteArray().length); + return response; + } + + private void assertStoredObject(String key, byte[] expectedBytes, String expectedContentType) { + ResponseBytes response = readObject(key, expectedContentType); + assertThat(response.asByteArray()).isEqualTo(expectedBytes); + assertThat(sha256Hex(response.asByteArray())).isEqualTo(sha256Hex(expectedBytes)); + } + + private String artifactXmin(DSLContext dsl, String tenantId, long versionId) { + var artifactRow = + dsl.fetchOne( + "SELECT xmin::text AS xmin FROM version_asset_artifact " + + "WHERE tenant_id = ? AND version_id = ?", + tenantId, + versionId); + if (artifactRow == null) { + throw new IllegalStateException("Expected persisted Version asset artifact xmin row"); + } + return artifactRow.get("xmin", String.class); + } + + private static DockerImageName composeMinioImage() throws IOException { + FileSystemResource compose = + new FileSystemResource(System.getProperty("firemud.asset-proof.compose-file")); + Object image = + new YamlPropertySourceLoader() + .load("asset-proof-compose", compose) + .getFirst() + .getProperty("services.minio.image"); + if (!(image instanceof String reference) + || !reference.matches("ghcr\\.io/benhook1013/minio-server@sha256:[0-9a-f]{64}")) { + throw new IllegalStateException( + "Asset proof requires the trusted digest-pinned Compose MinIO image"); + } + return DockerImageName.parse(reference); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static String sha256Hex(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 unavailable", exception); + } + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + PlatformTransactionManager transactionManager, + TransactionTemplate transactionTemplate, + GameRepository gameRepository, + GameAssetRepository gameAssetRepository, + VersionRepository versionRepository, + VersionAssetPublicationServiceImpl publicationService, + VersionAssetArtifactRepository artifactRepository, + VersionAssetExportCandidateServiceImpl candidateService) {} +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepositoryTest.java new file mode 100644 index 0000000000..4adc871e7f --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepositoryTest.java @@ -0,0 +1,61 @@ +package net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.DriverManager; +import java.time.LocalDateTime; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.entity.PublishAttempt; +import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; +import net.firedevops.firemud.gamedesign.model.PublishType; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; + +class PublishAttemptRepositoryTest { + @Test + void saveReturnsInsertedAttemptAndMatchesIndependentReadback() throws Exception { + try (var connection = + DriverManager.getConnection( + "jdbc:h2:mem:publish-attempt-" + UUID.randomUUID() + ";DATABASE_TO_LOWER=TRUE")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + dsl.execute( + "CREATE TABLE publish_attempt (" + + "id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, " + + "tenant_id VARCHAR(36) NOT NULL, publish_workflow_id VARCHAR(64) NOT NULL, " + + "publish_type VARCHAR(32) NOT NULL, status VARCHAR(16) NOT NULL, " + + "revision BIGINT NOT NULL DEFAULT 1, " + + "version_id BIGINT, version_number INT NOT NULL, " + + "script_patch_version VARCHAR(100), base_version_id BIGINT, " + + "request_digest VARCHAR(128), failure_code VARCHAR(64), " + + "failure_message TEXT, created_at TIMESTAMP NOT NULL, completed_at TIMESTAMP)"); + + PublishAttempt requested = new PublishAttempt(); + requested.setTenantId("tenant-publish-attempt"); + requested.setPublishWorkflowId("publish-attempt-insert-readback"); + requested.setPublishType(PublishType.FULL_VERSION); + requested.setStatus(PublishAttemptStatus.FAILED); + requested.setVersionId(73L); + requested.setVersionNumber(9); + requested.setRequestDigest("sha256:" + "a".repeat(64)); + requested.setFailureCode("PARTICIPANT_UNAVAILABLE"); + requested.setFailureMessage("full diagnostic evidence " + "x".repeat(600)); + requested.setCreatedAt(LocalDateTime.of(2026, 10, 5, 12, 30)); + requested.setCompletedAt(LocalDateTime.of(2026, 10, 5, 12, 31)); + + PublishAttemptRepository repository = new PublishAttemptRepository(dsl); + PublishAttempt saved = repository.save(requested); + PublishAttempt independentlyRead = + repository.findByPublishWorkflowId("publish-attempt-insert-readback").orElseThrow(); + + assertThat(saved.getId()).isNotNull(); + assertThat(saved.getRevision()).isEqualTo(1L); + assertThat(saved).usingRecursiveComparison().ignoringFields("id").isEqualTo(requested); + assertThat(saved).usingRecursiveComparison().isEqualTo(independentlyRead); + assertThat(independentlyRead.getScriptPatchVersion()).isNull(); + assertThat(independentlyRead.getBaseVersionId()).isNull(); + assertThat(independentlyRead.getFailureMessage()).hasSizeGreaterThan(512); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldLaunchDescriptorMtlsTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldLaunchDescriptorMtlsTest.java new file mode 100644 index 0000000000..15a481ead7 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldLaunchDescriptorMtlsTest.java @@ -0,0 +1,254 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Server; +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.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; +import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; +import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; +import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; +import net.firedevops.firemud.gamedesign.service.PingService; +import net.firedevops.firemud.gamedesign.service.RevisionService; +import net.firedevops.firemud.gamedesign.service.SettingsAuthorityService; +import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; +import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; +import net.firedevops.firemud.gamedesign.service.VersionService; +import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec; +import net.firedevops.firemud.test.LoopbackMtlsTestPki.Pki; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.context.properties.source.ConfigurationPropertySources; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.io.FileSystemResource; +import org.springframework.test.util.ReflectionTestUtils; + +/** + * Loopback mTLS proof for the real Game Design adapter and scoped Common client. The fixture mounts + * the adapter on a test server and supplies digest-valid evidence from a mocked descriptor owner. + * Persistence and application registration are outside the fixture's scope. + */ +class AuthoredWorldLaunchDescriptorMtlsTest { + private static final String NAMESPACE = "test"; + private static final UUID TENANT_ID = UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID READ_REQUEST_ID = + UUID.fromString("32345678-1234-4234-8234-123456789abc"); + + @Test + void resolvesForGameSessionAndReadsForGameSessionAndWorldOverMtls(@TempDir Path directory) + throws Exception { + var request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + "cp-launch", + TENANT_ID, + "silver-march", + UUID.fromString("22345678-1234-4234-8234-123456789abc"), + "sha256:" + "a".repeat(64), + 9L, + false, + null, + false, + null, + false, + null, + false, + null); + var evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "ld-1", + 7L, + false, + null, + "{}", + "genrev-1", + 11L, + 11L, + "release-bundle:" + TENANT_ID + ":7:11", + false, + null); + var read = + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + READ_REQUEST_ID, request, evidence.resultDigest()); + var descriptor = + new ResolvedLaunchDescriptorDto( + evidence.launchDescriptorId(), + TENANT_ID.toString(), + evidence.gameTemplateId(), + evidence.controlPlaneRequestId(), + evidence.versionId(), + evidence.scriptPatchVersion(), + evidence.runtimeFlagsJson(), + evidence.generationConfigRevision(), + evidence.versionStateEpoch(), + evidence.releaseBundleId(), + evidence.publishedReleaseBundleRef(), + evidence.remapSetId(), + evidence); + var owner = mock(LaunchDescriptorService.class); + when(owner.resolveLaunchDescriptor(request)).thenReturn(descriptor); + when(owner.getLaunchDescriptor( + READ_REQUEST_ID, + TENANT_ID, + request.worldSlug(), + request.controlPlaneRequestId(), + evidence.requestDigest(), + evidence.resultDigest())) + .thenReturn(descriptor); + + var pki = + LoopbackMtlsTestPki.create( + directory, + "Launch descriptor test CA", + new IdentitySpec("server", "spiffe://firemud/ns/test/sa/game-design-service", true), + new IdentitySpec("session", "spiffe://firemud/ns/test/sa/game-session-service", false), + new IdentitySpec( + "world", "spiffe://firemud/ns/test/sa/world-management-service", false), + new IdentitySpec("other", "spiffe://firemud/ns/other/sa/game-session-service", false)); + var meters = new SimpleMeterRegistry(); + try { + Server server = startReceiver(pki, owner, meters); + try { + var factory = new GrpcChannelFactory(); + var wrongNamespace = + factory.buildChannel( + "localhost", + server.getPort(), + pki.clientProperties(directory, pki.identity("other")), + false); + try { + var stub = + GameDesignServiceGrpc.newBlockingStub(wrongNamespace) + .withDeadlineAfter(5, TimeUnit.SECONDS); + var deniedResolve = + stub.resolveLaunchDescriptor( + AuthoredWorldLaunchDescriptorGrpcCodec.toResolveRequest(request)); + var deniedRead = + stub.getLaunchDescriptor(AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(read)); + assertThat(deniedResolve.getError().getCode()).isEqualTo("PERMISSION_DENIED"); + assertThat(deniedRead.getError().getCode()).isEqualTo("PERMISSION_DENIED"); + verifyNoInteractions(owner); + } finally { + wrongNamespace.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + server.getPort()); + try (var sessionClient = + new AuthoredWorldLaunchDescriptorClient( + endpoints, + pki.clientProperties(directory, pki.identity("session")), + factory, + NAMESPACE); + var worldClient = + new AuthoredWorldLaunchDescriptorClient( + endpoints, + pki.clientProperties(directory, pki.identity("world")), + factory, + NAMESPACE)) { + sessionClient.init(); + worldClient.init(); + + assertThatThrownBy(() -> worldClient.resolve(request)) + .isInstanceOf(IllegalStateException.class) + .hasRootCauseMessage("Game Design rejected launch descriptor resolution"); + verifyNoInteractions(owner); + + assertThat(sessionClient.resolve(request)).isEqualTo(evidence); + assertThat(sessionClient.get(read)).isEqualTo(evidence); + assertThat(worldClient.get(read)).isEqualTo(evidence); + } + } finally { + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } finally { + meters.close(); + } + + verify(owner).resolveLaunchDescriptor(request); + verify(owner, times(2)) + .getLaunchDescriptor( + READ_REQUEST_ID, + TENANT_ID, + request.worldSlug(), + request.controlPlaneRequestId(), + evidence.requestDigest(), + evidence.resultDigest()); + verifyNoMoreInteractions(owner); + } + + private static Server startReceiver( + Pki pki, LaunchDescriptorService owner, SimpleMeterRegistry meters) throws Exception { + var service = + new GameDesignGrpcService( + mock(PingService.class), + mock(RevisionService.class), + mock(VersionService.class), + owner, + mock(CompleteLaunchBindingService.class), + mock(TemplateRemapSetService.class), + mock(VersionAssetArtifactService.class), + mock(SettingsAuthorityService.class), + mock(GameAuthoredHelpTopicService.class), + new TemporalVersionPublishWorkflowMetadataResolver(Optional.empty(), Optional.empty()), + meters); + ReflectionTestUtils.setField(service, "workloadNamespace", NAMESPACE); + + var auth = + new AuthTokenInterceptor( + new JwtUtil("test-secret-key-test-secret-key-32-bytes", 60_000L), publicMethods()); + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(pki.keyManagerFactory(pki.identity("server")))) + .trustManager(pki.trustManagerFactory()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, auth, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private static Set publicMethods() throws IOException { + var yaml = + new YamlPropertySourceLoader() + .load("application.yml", new FileSystemResource("src/main/resources/application.yml")); + return Set.copyOf( + new Binder(ConfigurationPropertySources.from(yaml)) + .bind("firemud.auth.grpc.public-methods", Bindable.listOf(String.class)) + .orElseThrow( + () -> new IllegalStateException("Missing Game Design gRPC method policy"))); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadMtlsTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadMtlsTest.java new file mode 100644 index 0000000000..737d0f7992 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadMtlsTest.java @@ -0,0 +1,815 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.ForwardingServerCall.SimpleForwardingServerCall; +import io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.MetadataUtils; +import java.io.IOException; +import java.math.BigInteger; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.Base64; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.v1.AuthoredWorldSourceReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; +import net.firedevops.firemud.test.TlsTestSupport; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.StandardEnvironment; +import org.springframework.core.io.FileSystemResource; +import org.springframework.grpc.server.service.GrpcService; + +/** + * Physical socket proof for Game Design's authored-world source reads. + * + *

The standalone, unregistered owner adapter, peer-identity interceptor, JWT interceptor, and + * shared source client run over ephemeral mTLS sockets. Owner repositories are mocked and return + * complete, digest-valid evidence; this suite does not prove persistence, Account caller + * authorization or membership bootstrap, World intake, local association, publication, or runtime + * activation. + */ +class AuthoredWorldSourceReadMtlsTest { + private static final String NAMESPACE = "test"; + private static final String SOURCE_METHOD = + "gamedesign.v1.AuthoredWorldSourceReadService/ResolveAuthoredWorldSource"; + private static final String AUTHORIZATION = "authorization"; + private static final String JWT_SECRET = "test-secret-key-test-secret-key-32-bytes"; + private static final UUID REGISTRATION_REQUEST_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID TENANT_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID READ_REQUEST_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1L); + private static final AuthoredWorldSourceEvidence SOURCE_EVIDENCE = sourceEvidence(); + private static final AuthoredWorldSourceGrpcCodec.ReadRequest READ_REQUEST = + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, READ_REQUEST_ID, SOURCE_OPERATION_ID, TENANT_ID, "harbor-world"); + private static TestPki pki; + + private GameAuthoredWorldSourceRepository authoredWorldRepository; + private Server server; + private AtomicReference responseMutation; + + @BeforeAll + static void generateEphemeralPki() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + KeyPair caKeyPair = newRsaKeyPair(); + X500Name caName = new X500Name("CN=Authored Source Test CA, O=FireMUD Test"); + X509Certificate caCertificate = + issueCertificate( + caName, caKeyPair.getPublic(), caName, caKeyPair.getPrivate(), true, null, false); + pki = + new TestPki( + caCertificate, + issueLeaf( + caName, + caKeyPair.getPrivate(), + "game-design-service", + "spiffe://firemud/ns/test/sa/game-design-service", + true), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "wrong-game-design-server-workload", + "spiffe://firemud/ns/test/sa/world-management-service", + true), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "wrong-game-design-server-namespace", + "spiffe://firemud/ns/other-test/sa/game-design-service", + true), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "world-management-service", + "spiffe://firemud/ns/test/sa/world-management-service", + false), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "game-session-service", + "spiffe://firemud/ns/test/sa/game-session-service", + false), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "account-service", + "spiffe://firemud/ns/test/sa/account-service", + false), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "cross-namespace-world-management-service", + "spiffe://firemud/ns/other-test/sa/world-management-service", + false), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "cross-namespace-account-service", + "spiffe://firemud/ns/other-test/sa/account-service", + false), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "trusted-certificate-without-workload-uri", + null, + false)); + } + + @BeforeEach + void startPhysicalReceiver() throws Exception { + authoredWorldRepository = mock(GameAuthoredWorldSourceRepository.class); + when(authoredWorldRepository.read(SOURCE_OPERATION_ID, TENANT_ID, "harbor-world", NAMESPACE)) + .thenReturn(Optional.of(SOURCE_EVIDENCE)); + responseMutation = new AtomicReference<>(ResponseMutation.NONE); + server = startReceiver(pki.gameDesignServerCertificate()); + } + + @AfterEach + void stopPhysicalReceiver() throws Exception { + if (server != null) { + stopServer(server); + server = null; + } + } + + @Test + void exactWorldReaderResolvesCompleteSourceReceiptThroughSharedClient(@TempDir Path directory) + throws Exception { + for (TestCertificate clientCertificate : List.of(pki.worldManagementCertificate())) { + Path clientDirectory = directory.resolve(UUID.randomUUID().toString()); + AuthoredWorldSourceClient client = + newSharedClient(clientDirectory, server, clientCertificate); + try { + client.init(); + + assertThat(client.read(READ_REQUEST)).isEqualTo(SOURCE_EVIDENCE); + } finally { + client.close(); + } + } + + verify(authoredWorldRepository, times(1)) + .read(SOURCE_OPERATION_ID, TENANT_ID, "harbor-world", NAMESPACE); + } + + @Test + void wrongServiceNamespaceAndSharedCertificatesAreDeniedBeforeOwnerRead() throws Exception { + for (TestCertificate clientCertificate : + List.of( + pki.accountServiceCertificate(), + pki.gameSessionCertificate(), + pki.wrongNamespaceCertificate(), + pki.noWorkloadUriCertificate())) { + ManagedChannel channel = channel(server, clientCertificate, jwtToken()); + try { + assertStatus( + () -> sourceStub(channel).resolveAuthoredWorldSource(wireReadRequest()), + Status.Code.PERMISSION_DENIED); + } finally { + stopChannel(channel); + } + } + + verifyNoInteractions(authoredWorldRepository); + } + + @Test + void missingClientCertificateFailsWithTlsHandshakeEvidenceBeforeOwnerRead() throws Exception { + ManagedChannel channel = channel(server, null, null); + try { + assertTlsDenied( + () -> sourceStub(channel).resolveAuthoredWorldSource(wireReadRequest()), SOURCE_METHOD); + } finally { + stopChannel(channel); + } + + verifyNoInteractions(authoredWorldRepository); + } + + @Test + void jwtOnlyCallerWithoutClientCertificateFailsWithTlsHandshakeEvidence() throws Exception { + ManagedChannel channel = channel(server, null, jwtToken()); + try { + assertTlsDenied( + () -> sourceStub(channel).resolveAuthoredWorldSource(wireReadRequest()), SOURCE_METHOD); + } finally { + stopChannel(channel); + } + + verifyNoInteractions(authoredWorldRepository); + } + + @Test + void validJwtWithTrustedCertificateButNoWorkloadUriIsDeniedByPeerGuard() throws Exception { + ManagedChannel channel = channel(server, pki.noWorkloadUriCertificate(), jwtToken()); + try { + assertStatus( + () -> sourceStub(channel).resolveAuthoredWorldSource(wireReadRequest()), + Status.Code.PERMISSION_DENIED); + } finally { + stopChannel(channel); + } + + verifyNoInteractions(authoredWorldRepository); + } + + @Test + void sharedClientRefusesWrongGameDesignServerWorkloadAndNamespace(@TempDir Path directory) + throws Exception { + for (TestCertificate serverCertificate : + List.of(pki.wrongServerWorkloadCertificate(), pki.wrongServerNamespaceCertificate())) { + InboundRpcCapture inboundRpcCapture = new InboundRpcCapture(); + Server wrongIdentityServer = startReceiver(serverCertificate, inboundRpcCapture); + AuthoredWorldSourceClient client = + newSharedClient( + directory.resolve(UUID.randomUUID().toString()), + wrongIdentityServer, + pki.worldManagementCertificate()); + try { + client.init(); + assertServerPeerRefused(() -> client.read(READ_REQUEST)); + inboundRpcCapture.assertNoInboundRequests(); + } finally { + client.close(); + stopServer(wrongIdentityServer); + } + } + + verifyNoInteractions(authoredWorldRepository); + } + + @Test + void sharedClientRejectsChangedRequestEchoSourceDigestAndUnknownFieldsOverSocket( + @TempDir Path directory) throws Exception { + AuthoredWorldSourceClient client = + newSharedClient(directory, server, pki.worldManagementCertificate()); + try { + client.init(); + + responseMutation.set(ResponseMutation.CHANGE_READ_REQUEST_ID); + assertClientCodecRejected(() -> client.read(READ_REQUEST), "read request echo changed"); + + responseMutation.set(ResponseMutation.CHANGE_SOURCE_DISPLAY_NAME); + assertClientCodecRejected( + () -> client.read(READ_REQUEST), "Request digest does not match the registration tuple"); + + responseMutation.set(ResponseMutation.CHANGE_EVIDENCE_DIGEST); + assertClientCodecRejected( + () -> client.read(READ_REQUEST), "Evidence digest does not match the immutable tuple"); + + responseMutation.set(ResponseMutation.ADD_UNKNOWN_FIELD); + assertClientCodecRejected( + () -> client.read(READ_REQUEST), "Authored-world source response contains unsupported"); + } finally { + client.close(); + } + + verify(authoredWorldRepository, times(4)) + .read(SOURCE_OPERATION_ID, TENANT_ID, "harbor-world", NAMESPACE); + } + + @Test + void unknownReadRequestFieldsAreRejectedByStandaloneServiceBeforeOwnerRead() throws Exception { + ManagedChannel channel = channel(server, pki.worldManagementCertificate(), jwtToken()); + ResolveAuthoredWorldSourceRequest unknownFieldRequest = + wireReadRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + try { + assertStatus( + () -> sourceStub(channel).resolveAuthoredWorldSource(unknownFieldRequest), + Status.Code.INVALID_ARGUMENT); + } finally { + stopChannel(channel); + } + + verifyNoInteractions(authoredWorldRepository); + } + + @Test + void sourceReadStaysStandaloneAndLegacyAssociationRpcRemainsAbsent() throws Exception { + assertThat(AuthoredWorldSourceReadGrpcService.class.getAnnotation(GrpcService.class)).isNull(); + assertThat(TenantIdentityServiceGrpc.getServiceDescriptor().getMethods()) + .extracting(io.grpc.MethodDescriptor::getFullMethodName) + .doesNotContain( + "gamedesign.v1.TenantIdentityService/ResolveAuthoredWorldSource", + "gamedesign.v1.TenantIdentityService/ResolveLegacyGameSessionTenantAssociation"); + for (String profile : List.of("application.yml", "application-prod.yml")) { + assertThat(publicMethods(profile)) + .contains(SOURCE_METHOD) + .doesNotContain( + "gamedesign.v1.TenantIdentityService/ResolveAuthoredWorldSource", + "gamedesign.v1.TenantIdentityService/ResolveLegacyGameSessionTenantAssociation"); + } + verifyNoInteractions(authoredWorldRepository); + } + + private Server startReceiver(TestCertificate serverCertificate) throws Exception { + return startReceiver(serverCertificate, null); + } + + private Server startReceiver( + TestCertificate serverCertificate, InboundRpcCapture inboundRpcCapture) throws Exception { + AuthoredWorldSourceReadGrpcService service = + new AuthoredWorldSourceReadGrpcService(authoredWorldRepository, NAMESPACE); + Set unauthenticatedMethods = publicMethods("application.yml"); + ServerInterceptor[] interceptors = + inboundRpcCapture == null + ? new ServerInterceptor[] { + responseMutationInterceptor(responseMutation), + new AuthTokenInterceptor(new JwtUtil(JWT_SECRET, 60_000L), unauthenticatedMethods), + new GrpcPeerIdentityInterceptor() + } + : new ServerInterceptor[] { + inboundRpcCapture, + responseMutationInterceptor(responseMutation), + new AuthTokenInterceptor(new JwtUtil(JWT_SECRET, 60_000L), unauthenticatedMethods), + new GrpcPeerIdentityInterceptor() + }; + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverCertificate.privateKey(), serverCertificate.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, interceptors)) + .build() + .start(); + } + + private AuthoredWorldSourceClient newSharedClient( + Path directory, Server receiver, TestCertificate clientCertificate) throws Exception { + Files.createDirectories(directory); + Path caCertificate = + writePem(directory.resolve("test-ca.crt"), "CERTIFICATE", pki.caCertificate().getEncoded()); + Path certificate = + writePem( + directory.resolve("client.crt"), + "CERTIFICATE", + clientCertificate.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve("client.key"), + "PRIVATE KEY", + clientCertificate.privateKey().getEncoded()); + + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(certificate.toString()); + tls.setPrivateKey(privateKey.toString()); + tls.setCaCert(caCertificate.toString()); + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + receiver.getPort()); + return new AuthoredWorldSourceClient(endpoints, tls, new GrpcChannelFactory(), NAMESPACE); + } + + private ManagedChannel channel(Server receiver, TestCertificate clientCertificate, String jwt) + throws Exception { + NettyChannelBuilder builder = + NettyChannelBuilder.forAddress(new InetSocketAddress("127.0.0.1", receiver.getPort())) + .sslContext(clientSslContext(clientCertificate)); + if (jwt != null) { + Metadata headers = new Metadata(); + headers.put( + Metadata.Key.of(AUTHORIZATION, Metadata.ASCII_STRING_MARSHALLER), "Bearer " + jwt); + builder.intercept(MetadataUtils.newAttachHeadersInterceptor(headers)); + } + return builder.build(); + } + + private static io.grpc.netty.shaded.io.netty.handler.ssl.SslContext clientSslContext( + TestCertificate clientCertificate) throws Exception { + var builder = GrpcSslContexts.forClient().trustManager(pki.caCertificate()); + if (clientCertificate != null) { + builder.keyManager(clientCertificate.privateKey(), clientCertificate.certificate()); + } + return builder.build(); + } + + private static AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceBlockingStub + sourceStub(ManagedChannel channel) { + return AuthoredWorldSourceReadServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS); + } + + private static ResolveAuthoredWorldSourceRequest wireReadRequest() { + return AuthoredWorldSourceGrpcCodec.toReadRequest(READ_REQUEST); + } + + private String jwtToken() { + JwtUtil jwtUtil = new JwtUtil(JWT_SECRET, 60_000L); + return jwtUtil.generateToken( + "service:world-management-service", + Map.of( + "accountId", + "", + "globalRoles", + List.of(), + "scopedRoles", + Map.of(), + "internalService", + true, + "serviceName", + "world-management-service")); + } + + private static ServerInterceptor responseMutationInterceptor( + AtomicReference pendingMutation) { + return new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + ServerCall forwardingCall = + new SimpleForwardingServerCall<>(call) { + @Override + public void sendMessage(RespT message) { + super.sendMessage( + mutateResponse(message, pendingMutation.getAndSet(ResponseMutation.NONE))); + } + }; + return next.startCall(forwardingCall, headers); + } + }; + } + + @SuppressWarnings("unchecked") + private static Response mutateResponse(Response response, ResponseMutation mutation) { + if (mutation == ResponseMutation.NONE) { + return response; + } + if (!(response instanceof ResolveAuthoredWorldSourceResponse source)) { + throw new IllegalStateException("Response mutation does not match the source read RPC"); + } + return (Response) + switch (mutation) { + case CHANGE_READ_REQUEST_ID -> + source.toBuilder().setRequestId("55555555-5555-4555-8555-555555555555").build(); + case CHANGE_SOURCE_DISPLAY_NAME -> + source.toBuilder().setWorldDisplayName("Changed display name").build(); + case CHANGE_EVIDENCE_DIGEST -> + source.toBuilder().setEvidenceDigest("sha256:" + "f".repeat(64)).build(); + case ADD_UNKNOWN_FIELD -> + source.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + case NONE -> source; + }; + } + + private static void assertStatus(Runnable call, Status.Code expectedCode) { + Throwable failure = catchFailure(call); + assertThat(failure) + .as("RPC should fail with %s: %s", expectedCode, diagnostics(failure)) + .isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()) + .as("RPC denial evidence: %s", diagnostics(failure)) + .isEqualTo(expectedCode); + } + + private static void assertServerPeerRefused(Runnable call) { + Throwable failure = catchFailure(call); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(Status.fromThrowable(failure).getDescription()) + .contains("exact authenticated server workload identity"); + } + + private static final class InboundRpcCapture implements ServerInterceptor { + private final AtomicInteger rpcCount = new AtomicInteger(); + private final AtomicInteger requestMessageCount = new AtomicInteger(); + private final AtomicReference methodName = new AtomicReference<>(); + private final AtomicReference requestMetadata = new AtomicReference<>(); + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + rpcCount.incrementAndGet(); + methodName.set(call.getMethodDescriptor().getFullMethodName()); + requestMetadata.set(headers); + ServerCall.Listener listener = next.startCall(call, headers); + return new SimpleForwardingServerCallListener<>(listener) { + @Override + public void onMessage(ReqT message) { + requestMessageCount.incrementAndGet(); + super.onMessage(message); + } + }; + } + + private void assertNoInboundRequests() { + assertThat(rpcCount.get()).isZero(); + assertThat(requestMessageCount.get()).isZero(); + assertThat(methodName.get()).isNull(); + assertThat(requestMetadata.get()).isNull(); + } + } + + private static void assertClientCodecRejected(Runnable call, String expectedEvidence) { + Throwable failure = catchFailure(call); + assertThat(failure).isInstanceOf(IllegalStateException.class); + assertThat(diagnostics(failure)).contains(expectedEvidence); + } + + private static void assertTlsDenied(Runnable call, String method) { + Throwable failure = catchFailure(call); + assertThat(failure) + .as( + "%s must fail with client-certificate handshake evidence: %s", + method, diagnostics(failure)) + .isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()) + .as( + "%s must fail at TLS rather than by application timeout: %s", + method, diagnostics(failure)) + .isEqualTo(Status.Code.UNAVAILABLE); + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as( + "%s cause chain must identify client-certificate rejection: %s", + method, diagnostics(failure)) + .isTrue(); + } + + private static Set publicMethods(String resourceName) throws IOException { + ConfigurableEnvironment environment = new StandardEnvironment(); + environment + .getPropertySources() + .remove(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME); + environment + .getPropertySources() + .remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); + for (var propertySource : + new YamlPropertySourceLoader() + .load(resourceName, new FileSystemResource("src/main/resources/" + resourceName))) { + environment.getPropertySources().addFirst(propertySource); + } + return Set.copyOf( + Binder.get(environment) + .bind("firemud.auth.grpc.public-methods", Bindable.listOf(String.class)) + .orElse(List.of())); + } + + private static AuthoredWorldSourceEvidence sourceEvidence() { + String tenantSlug = "firemud"; + String worldSlug = "harbor-world"; + String worldDisplayName = "Harbor World"; + String sourceGameTenantKey = "legacy-game-17"; + String provenanceKind = "NEW_GAME_ROW"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION_REQUEST_ID, TENANT_ID, tenantSlug, worldSlug, worldDisplayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + tenantSlug, + worldSlug, + worldDisplayName, + 17L, + sourceGameTenantKey, + provenanceKind); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + tenantSlug, + worldSlug, + worldDisplayName, + 17L, + sourceGameTenantKey, + provenanceKind, + evidenceDigest); + } + + private static Path writePem(Path path, String label, byte[] encoded) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(encoded); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + + private static void stopServer(Server server) throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + private static void stopChannel(ManagedChannel channel) throws InterruptedException { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + private static Throwable catchFailure(Runnable action) { + try { + action.run(); + return null; + } catch (Throwable throwable) { + return throwable; + } + } + + private static String diagnostics(Throwable throwable) { + if (throwable == null) { + return "RPC unexpectedly completed"; + } + StringBuilder result = new StringBuilder(); + for (Throwable current = throwable; current != null; current = current.getCause()) { + if (!result.isEmpty()) { + result.append(" <- "); + } + result.append(current.getClass().getName()).append(": ").append(current.getMessage()); + } + return result.toString(); + } + + private static TestCertificate issueLeaf( + X500Name caName, + PrivateKey caPrivateKey, + String commonName, + String workloadUri, + boolean serverCertificate) + throws Exception { + KeyPair keyPair = newRsaKeyPair(); + X500Name subject = new X500Name("CN=" + commonName + ", O=FireMUD Test"); + GeneralName[] subjectAltNames = + workloadUri == null + ? new GeneralName[] { + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + } + : new GeneralName[] { + new GeneralName(GeneralName.uniformResourceIdentifier, workloadUri), + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + }; + X509Certificate certificate = + issueCertificate( + subject, + keyPair.getPublic(), + caName, + caPrivateKey, + false, + new GeneralNames(subjectAltNames), + serverCertificate); + return new TestCertificate(keyPair.getPrivate(), certificate); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerPrivateKey, + boolean ca, + GeneralNames subjectAltNames, + boolean serverCertificate) + throws Exception { + Instant now = Instant.now().minusSeconds(60L); + JcaX509v3CertificateBuilder builder = + new JcaX509v3CertificateBuilder( + issuer, + BigInteger.valueOf(CERTIFICATE_SERIAL.getAndIncrement()), + Date.from(now), + Date.from(now.plusSeconds(60L * 60L * 24L * 14L)), + subject, + publicKey); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca)); + if (ca) { + builder.addExtension( + Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); + } else { + builder.addExtension( + Extension.keyUsage, + true, + new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + serverCertificate ? KeyPurposeId.id_kp_serverAuth : KeyPurposeId.id_kp_clientAuth)); + builder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); + } + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuerPrivateKey))); + } + + private static KeyPair newRsaKeyPair() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private record TestCertificate(PrivateKey privateKey, X509Certificate certificate) {} + + private enum ResponseMutation { + NONE, + CHANGE_READ_REQUEST_ID, + CHANGE_SOURCE_DISPLAY_NAME, + CHANGE_EVIDENCE_DIGEST, + ADD_UNKNOWN_FIELD + } + + private record TestPki( + X509Certificate caCertificate, + TestCertificate gameDesignServerCertificate, + TestCertificate wrongServerWorkloadCertificate, + TestCertificate wrongServerNamespaceCertificate, + TestCertificate worldManagementCertificate, + TestCertificate gameSessionCertificate, + TestCertificate accountServiceCertificate, + TestCertificate wrongNamespaceCertificate, + TestCertificate crossNamespaceAccountCertificate, + TestCertificate noWorkloadUriCertificate) {} +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredWorldSourceDeliveryServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredWorldSourceDeliveryServiceTest.java new file mode 100644 index 0000000000..4f09ce648a --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredWorldSourceDeliveryServiceTest.java @@ -0,0 +1,391 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.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.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ReadRequest; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository.DeliveryClaim; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameAuthoredWorldSourceDeliveryServiceTest { + private static final String NAMESPACE = "authored-world-test"; + private static final UUID SOURCE_OPERATION_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID REGISTRATION_REQUEST_ID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID INTAKE_REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID WORLD_OPERATION_ID = uuid("55555555-5555-4555-8555-555555555555"); + + private final GameAuthoredWorldSourceDeliveryRepository repository = + mock(GameAuthoredWorldSourceDeliveryRepository.class); + private final WorldAuthoredSourceIntakeClient worldClient = + mock(WorldAuthoredSourceIntakeClient.class); + private final RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + private final GameAuthoredWorldSourceDeliveryService service = + new GameAuthoredWorldSourceDeliveryService( + repository, worldClient, transactionManager, NAMESPACE); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void exactCompletedRetryReturnsDurableReceiptWithoutCallingWorld() { + DeliveryClaim completed = claim(Optional.of(receipt(request(), WORLD_OPERATION_ID, 'a'))); + when(repository.read(SOURCE_OPERATION_ID)).thenReturn(Optional.of(completed)); + + DeliveryClaim result = service.deliver(SOURCE_OPERATION_ID); + + assertThat(result).isEqualTo(completed); + verify(repository).read(SOURCE_OPERATION_ID); + verify(repository, never()).acknowledge(any(), any()); + verifyNoInteractions(worldClient); + assertThat(transactionManager.beginCount).hasValue(0); + } + + @Test + void missingDeliveryClaimIsDeniedWithoutCallingWorld() { + when(repository.read(SOURCE_OPERATION_ID)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.deliver(SOURCE_OPERATION_ID)) + .isInstanceOf(GameAuthoredWorldSourceDeliveryService.DeliveryNotFoundException.class); + + verify(repository).read(SOURCE_OPERATION_ID); + verify(repository, never()).acknowledge(any(), any()); + verifyNoInteractions(worldClient); + } + + @Test + void wrongNamespaceClaimIsDeniedBeforeCallingWorld() { + DeliveryClaim wrongNamespace = claim(NAMESPACE, Optional.empty()); + when(repository.read(SOURCE_OPERATION_ID)).thenReturn(Optional.of(wrongNamespace)); + GameAuthoredWorldSourceDeliveryService otherNamespaceService = + new GameAuthoredWorldSourceDeliveryService( + repository, worldClient, transactionManager, "different-namespace"); + + assertThatThrownBy(() -> otherNamespaceService.deliver(SOURCE_OPERATION_ID)) + .isInstanceOf(GameAuthoredWorldSourceDeliveryService.DeliveryConflictException.class); + + verify(repository).read(SOURCE_OPERATION_ID); + verify(repository, never()).acknowledge(any(), any()); + verifyNoInteractions(worldClient); + } + + @Test + void writableAmbientTransactionIsDeniedBeforeOwnerReadOrWorldCall() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> service.deliver(SOURCE_OPERATION_ID)) + .isInstanceOf(IllegalStateException.class); + + verifyNoInteractions(repository, worldClient); + } + + @Test + void mismatchedWorldIntakeOrReadbackNeverAcknowledges() { + DeliveryClaim pending = claim(Optional.empty()); + CommittedReceipt expected = receipt(pending.request(), WORLD_OPERATION_ID, 'a'); + when(repository.read(SOURCE_OPERATION_ID)).thenReturn(Optional.of(pending)); + when(worldClient.intake(pending.request())) + .thenReturn(receipt(pending.request(), uuid("66666666-6666-4666-8666-666666666666"), 'b')); + when(worldClient.read(any(ReadRequest.class))).thenReturn(expected); + + assertThatThrownBy(() -> service.deliver(SOURCE_OPERATION_ID)) + .isInstanceOf(GameAuthoredWorldSourceDeliveryService.DeliveryConflictException.class) + .hasMessageContaining("same complete receipt"); + verify(repository, never()).acknowledge(any(), any()); + + org.mockito.Mockito.reset(repository, worldClient); + when(repository.read(SOURCE_OPERATION_ID)).thenReturn(Optional.of(pending)); + when(worldClient.intake(pending.request())).thenReturn(expected); + when(worldClient.read(any(ReadRequest.class))) + .thenReturn(receipt(pending.request(), uuid("77777777-7777-4777-8777-777777777777"), 'c')); + + assertThatThrownBy(() -> service.deliver(SOURCE_OPERATION_ID)) + .isInstanceOf(GameAuthoredWorldSourceDeliveryService.DeliveryConflictException.class) + .hasMessageContaining("same complete receipt"); + + verify(worldClient).intake(pending.request()); + verify(worldClient).read(any(ReadRequest.class)); + verify(repository, never()).acknowledge(any(), any()); + } + + @Test + void ambiguousWorldIntakeOrReadbackLeavesClaimPending() { + DeliveryClaim pending = claim(Optional.empty()); + CommittedReceipt expected = receipt(pending.request(), WORLD_OPERATION_ID, 'a'); + + when(repository.read(SOURCE_OPERATION_ID)).thenReturn(Optional.of(pending)); + when(worldClient.intake(pending.request())) + .thenThrow(new IllegalStateException("lost intake reply")); + assertThatThrownBy(() -> service.deliver(SOURCE_OPERATION_ID)) + .hasMessageContaining("lost intake reply"); + verify(repository, never()).acknowledge(any(), any()); + + org.mockito.Mockito.reset(repository, worldClient); + when(repository.read(SOURCE_OPERATION_ID)).thenReturn(Optional.of(pending)); + when(worldClient.intake(pending.request())).thenReturn(expected); + when(worldClient.read(any(ReadRequest.class))) + .thenThrow(new IllegalStateException("World readback unavailable")); + + assertThatThrownBy(() -> service.deliver(SOURCE_OPERATION_ID)) + .hasMessageContaining("World readback unavailable"); + + verify(repository, never()).acknowledge(any(), any()); + } + + @Test + void exactWorldReceiptIsAcknowledgedInShortTransactionAndReadBackAfterCommit() { + DeliveryClaim pending = claim(Optional.empty()); + CommittedReceipt worldReceipt = receipt(pending.request(), WORLD_OPERATION_ID, 'a'); + DeliveryClaim acknowledged = claim(Optional.of(worldReceipt)); + AtomicInteger reads = new AtomicInteger(); + AtomicBoolean acknowledgementWasTransactional = new AtomicBoolean(); + AtomicBoolean readbackWasOutsideTransaction = new AtomicBoolean(); + AtomicBoolean worldCallsWereOutsideTransaction = new AtomicBoolean(true); + when(repository.read(SOURCE_OPERATION_ID)) + .thenAnswer( + invocation -> { + if (reads.incrementAndGet() == 1) { + return Optional.of(pending); + } + readbackWasOutsideTransaction.set( + !TransactionSynchronizationManager.isActualTransactionActive()); + return Optional.of(acknowledged); + }); + when(worldClient.intake(pending.request())) + .thenAnswer( + invocation -> { + worldCallsWereOutsideTransaction.compareAndSet( + true, !TransactionSynchronizationManager.isActualTransactionActive()); + return worldReceipt; + }); + when(worldClient.read(any(ReadRequest.class))) + .thenAnswer( + invocation -> { + worldCallsWereOutsideTransaction.compareAndSet( + true, !TransactionSynchronizationManager.isActualTransactionActive()); + return worldReceipt; + }); + when(repository.acknowledge(pending, worldReceipt)) + .thenAnswer( + invocation -> { + acknowledgementWasTransactional.set( + TransactionSynchronizationManager.isActualTransactionActive()); + return acknowledged; + }); + + DeliveryClaim result = service.deliver(SOURCE_OPERATION_ID); + + assertThat(result).isEqualTo(acknowledged); + assertThat(reads).hasValue(2); + assertThat(acknowledgementWasTransactional).isTrue(); + assertThat(readbackWasOutsideTransaction).isTrue(); + assertThat(worldCallsWereOutsideTransaction).isTrue(); + assertThat(transactionManager.definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(transactionManager.definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(transactionManager.definition.isReadOnly()).isFalse(); + ArgumentCaptor readRequest = ArgumentCaptor.forClass(ReadRequest.class); + InOrder remoteOrder = inOrder(worldClient); + remoteOrder.verify(worldClient).intake(pending.request()); + remoteOrder.verify(worldClient).read(readRequest.capture()); + assertThat(readRequest.getValue().binding()).isEqualTo(pending.request()); + assertThat(readRequest.getValue().requestId()) + .isNotEqualTo(pending.request().intakeRequestId()) + .isNotEqualTo(pending.source().operationId()); + verify(repository).acknowledge(pending, worldReceipt); + } + + @Test + void lostAcknowledgementRecoversDurablePriorBeforeAnyRedelivery() { + DeliveryClaim pending = claim(Optional.empty()); + CommittedReceipt worldReceipt = receipt(pending.request(), WORLD_OPERATION_ID, 'a'); + DeliveryClaim acknowledged = claim(Optional.of(worldReceipt)); + AtomicInteger reads = new AtomicInteger(); + when(repository.read(SOURCE_OPERATION_ID)) + .thenAnswer( + invocation -> Optional.of(reads.incrementAndGet() == 1 ? pending : acknowledged)); + when(worldClient.intake(pending.request())).thenReturn(worldReceipt); + when(worldClient.read(any(ReadRequest.class))).thenReturn(worldReceipt); + when(repository.acknowledge(pending, worldReceipt)) + .thenThrow(new IllegalStateException("commit acknowledgement was lost")); + + DeliveryClaim recovered = service.deliver(SOURCE_OPERATION_ID); + assertThat(recovered).isEqualTo(acknowledged); + DeliveryClaim retry = service.deliver(SOURCE_OPERATION_ID); + + assertThat(retry).isEqualTo(acknowledged); + verify(worldClient).intake(pending.request()); + verify(worldClient).read(any(ReadRequest.class)); + verify(repository).acknowledge(pending, worldReceipt); + } + + @Test + void matchingConcurrentReceiptIsReturnedAndChangedReceiptIsDenied() { + DeliveryClaim pending = claim(Optional.empty()); + CommittedReceipt worldReceipt = receipt(pending.request(), WORLD_OPERATION_ID, 'a'); + DeliveryClaim concurrentWinner = claim(Optional.of(worldReceipt)); + when(repository.read(SOURCE_OPERATION_ID)) + .thenReturn(Optional.of(pending), Optional.of(concurrentWinner)); + when(worldClient.intake(pending.request())).thenReturn(worldReceipt); + when(worldClient.read(any(ReadRequest.class))).thenReturn(worldReceipt); + when(repository.acknowledge(pending, worldReceipt)).thenReturn(concurrentWinner); + + assertThat(service.deliver(SOURCE_OPERATION_ID)).isEqualTo(concurrentWinner); + + org.mockito.Mockito.reset(repository, worldClient); + CommittedReceipt otherReceipt = receipt(pending.request(), WORLD_OPERATION_ID, 'b'); + DeliveryClaim changedWinner = claim(Optional.of(otherReceipt)); + when(repository.read(SOURCE_OPERATION_ID)) + .thenReturn(Optional.of(pending), Optional.of(changedWinner)); + when(worldClient.intake(pending.request())).thenReturn(worldReceipt); + when(worldClient.read(any(ReadRequest.class))).thenReturn(worldReceipt); + when(repository.acknowledge(pending, worldReceipt)) + .thenThrow(new IllegalStateException("different World receipt is already acknowledged")); + + assertThat(otherReceipt).isNotEqualTo(worldReceipt); + assertThatThrownBy(() -> service.deliver(SOURCE_OPERATION_ID)) + .isInstanceOf(GameAuthoredWorldSourceDeliveryService.DeliveryConflictException.class) + .hasMessageContaining("different World receipt won"); + verify(repository).acknowledge(pending, worldReceipt); + } + + private static DeliveryClaim claim(Optional acknowledgedReceipt) { + return claim(NAMESPACE, acknowledgedReceipt); + } + + private static DeliveryClaim claim( + String namespace, Optional acknowledgedReceipt) { + AuthoredWorldSourceEvidence source = source(namespace); + IntakeRequest request = + new IntakeRequest( + 1, + namespace, + INTAKE_REQUEST_ID, + TENANT_ID, + source.worldSlug(), + source.operationId(), + source.evidenceDigest()); + return new DeliveryClaim(source, request, acknowledgedReceipt); + } + + private static AuthoredWorldSourceEvidence source(String namespace) { + String tenantSlug = "authored-tenant"; + String worldSlug = "violet-wilds"; + String displayName = "Violet Wilds"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + namespace, REGISTRATION_REQUEST_ID, TENANT_ID, tenantSlug, worldSlug, displayName); + return new AuthoredWorldSourceEvidence( + 1, + namespace, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + tenantSlug, + worldSlug, + displayName, + 17L, + "authored-tenant-key", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + namespace, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + tenantSlug, + worldSlug, + displayName, + 17L, + "authored-tenant-key", + "NEW_GAME_ROW")); + } + + private static IntakeRequest request() { + AuthoredWorldSourceEvidence source = source(NAMESPACE); + return new IntakeRequest( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + source.worldSlug(), + source.operationId(), + source.evidenceDigest()); + } + + private static CommittedReceipt receipt( + IntakeRequest request, UUID operationId, char receiptMarker) { + return new CommittedReceipt( + request.schemaVersion(), + request.targetNamespace(), + request.intakeRequestId(), + operationId, + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.expectedSourceEvidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(request), + digest(receiptMarker)); + } + + private static String digest(char marker) { + return "sha256:" + String.valueOf(marker).repeat(64); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class RecordingTransactionManager + extends AbstractPlatformTransactionManager { + private TransactionDefinition definition; + private final AtomicInteger beginCount = new AtomicInteger(); + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition transactionDefinition) { + definition = transactionDefinition; + beginCount.incrementAndGet(); + } + + @Override + protected void doCommit(DefaultTransactionStatus status) {} + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredWorldSourceDeliveryWorkerTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredWorldSourceDeliveryWorkerTest.java new file mode 100644 index 0000000000..2d04852853 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredWorldSourceDeliveryWorkerTest.java @@ -0,0 +1,188 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository.DeliveryClaim; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameAuthoredWorldSourceDeliveryWorkerTest { + private static final String NAMESPACE = "authored-world-worker-test"; + + @Test + void boundedNamespacePagesAdvancePastAmbiguousClaimThenCycleForExactRetry() { + GameAuthoredWorldSourceDeliveryRepository repository = + mock(GameAuthoredWorldSourceDeliveryRepository.class); + GameAuthoredWorldSourceDeliveryService deliveryService = + mock(GameAuthoredWorldSourceDeliveryService.class); + DeliveryClaim first = claim(1); + DeliveryClaim second = claim(2); + when(repository.readPending(NAMESPACE, null, 1)).thenReturn(List.of(first), List.of(first)); + when(repository.readPending(NAMESPACE, first.request().intakeRequestId(), 1)) + .thenReturn(List.of(second)); + when(repository.readPending(NAMESPACE, second.request().intakeRequestId(), 1)) + .thenReturn(List.of()); + doThrow(new IllegalStateException("ambiguous remote response")) + .when(deliveryService) + .deliver(first.source().operationId()); + + GameAuthoredWorldSourceDeliveryWorker worker = + new GameAuthoredWorldSourceDeliveryWorker(repository, deliveryService, 1, NAMESPACE); + + assertThat(worker.runPass()).isOne(); + assertThat(worker.runPass()).isOne(); + assertThat(worker.runPass()).isZero(); + assertThat(worker.runPass()).isOne(); + + InOrder pageOrder = inOrder(repository); + pageOrder.verify(repository).readPending(NAMESPACE, null, 1); + pageOrder.verify(repository).readPending(NAMESPACE, first.request().intakeRequestId(), 1); + pageOrder.verify(repository).readPending(NAMESPACE, second.request().intakeRequestId(), 1); + pageOrder.verify(repository).readPending(NAMESPACE, null, 1); + InOrder dispatchOrder = inOrder(deliveryService); + dispatchOrder.verify(deliveryService).deliver(first.source().operationId()); + dispatchOrder.verify(deliveryService).deliver(second.source().operationId()); + dispatchOrder.verify(deliveryService).deliver(first.source().operationId()); + } + + @Test + void invalidPollingBoundsFailBeforeTheWorkerCanStart() { + assertThatThrownBy( + () -> + new GameAuthoredWorldSourceDeliveryWorker( + mock(GameAuthoredWorldSourceDeliveryRepository.class), + mock(GameAuthoredWorldSourceDeliveryService.class), + GameAuthoredWorldSourceDeliveryRepository.MAX_PENDING_BATCH_SIZE + 1, + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("batch size"); + } + + @Test + void rejectsAnAmbientTransactionBeforeSelectingOrDispatchingClaims() { + GameAuthoredWorldSourceDeliveryRepository repository = + mock(GameAuthoredWorldSourceDeliveryRepository.class); + GameAuthoredWorldSourceDeliveryService deliveryService = + mock(GameAuthoredWorldSourceDeliveryService.class); + var worker = + new GameAuthoredWorldSourceDeliveryWorker(repository, deliveryService, 1, NAMESPACE); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(worker::runPass) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient transaction"); + verifyNoInteractions(repository, deliveryService); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } + + @Test + void overlappingPassDoesNotClaimOrDispatchTheSamePageAgain() throws Exception { + GameAuthoredWorldSourceDeliveryRepository repository = + mock(GameAuthoredWorldSourceDeliveryRepository.class); + GameAuthoredWorldSourceDeliveryService deliveryService = + mock(GameAuthoredWorldSourceDeliveryService.class); + DeliveryClaim claim = claim(3); + CountDownLatch pageReadStarted = new CountDownLatch(1); + CountDownLatch releasePageRead = new CountDownLatch(1); + when(repository.readPending(NAMESPACE, null, 1)) + .thenAnswer( + invocation -> { + pageReadStarted.countDown(); + if (!releasePageRead.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("test did not release the pending page read"); + } + return List.of(claim); + }); + GameAuthoredWorldSourceDeliveryWorker worker = + new GameAuthoredWorldSourceDeliveryWorker(repository, deliveryService, 1, NAMESPACE); + ExecutorService executor = Executors.newSingleThreadExecutor(); + Future firstPass = executor.submit(worker::runPass); + try { + assertThat(pageReadStarted.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(worker.runPass()).isZero(); + releasePageRead.countDown(); + assertThat(firstPass.get(5, TimeUnit.SECONDS)).isOne(); + verify(repository).readPending(NAMESPACE, null, 1); + } finally { + releasePageRead.countDown(); + executor.shutdownNow(); + } + } + + private static DeliveryClaim claim(int suffix) { + String tail = String.format("%012d", suffix); + UUID sourceOperationId = uuid("11111111-1111-4111-8111-" + tail); + UUID registrationRequestId = uuid("22222222-2222-4222-8222-" + tail); + UUID tenantId = uuid("33333333-3333-4333-8333-" + tail); + UUID intakeRequestId = uuid("44444444-4444-4444-8444-" + tail); + String tenantSlug = "tenant-" + suffix; + String worldSlug = "world-" + suffix; + String displayName = "World " + suffix; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, tenantId, tenantSlug, worldSlug, displayName); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + 100L + suffix, + "legacy-tenant-" + suffix, + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + 100L + suffix, + "legacy-tenant-" + suffix, + "NEW_GAME_ROW")); + IntakeRequest request = + new IntakeRequest( + 1, + NAMESPACE, + intakeRequestId, + tenantId, + worldSlug, + sourceOperationId, + source.evidenceDigest()); + return new DeliveryClaim(source, request, Optional.empty()); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java index 4878462249..7c80d96d6d 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java @@ -459,6 +459,125 @@ void candidateOriginMustUseCanonicalHttpsAssetsPath() { assertEquals(original, candidateService.readExportCandidate(TENANT_ID, VERSION_NUMBER)); } + @Test + void selectedFullV4RepairReusesFrozenCandidateWithExactModernWorldEvidence() throws Exception { + ExportedAssetManifest published = exporter.exportAssets(TENANT_ID, VERSION_NUMBER); + var selected = selectedFullBundle(published, false, false); + markPublished(); + FrozenAssetExportCandidate original = + candidateService.readExportCandidate(TENANT_ID, VERSION_NUMBER); + objectStore.clear(); + clearInvocations(s3Client, artifactRepository); + + assertEquals(published, exporter.repairPublishedAssets(TENANT_ID, VERSION_NUMBER, selected)); + assertEquals(original, candidateService.readExportCandidate(TENANT_ID, VERSION_NUMBER)); + ArgumentCaptor puts = ArgumentCaptor.forClass(PutObjectRequest.class); + verify(s3Client, times(2)).putObject(puts.capture(), any(RequestBody.class)); + assertEquals( + List.of("*", "*"), + puts.getAllValues().stream().map(PutObjectRequest::ifNoneMatch).toList()); + assertEquals(2, objectStore.size()); + verify(artifactRepository, never()).save(any(VersionAssetArtifact.class)); + } + + @Test + void selectedFullV4ForeignWorldTargetIsDeniedBeforeAnyRepairObjectWrite() throws Exception { + ExportedAssetManifest published = exporter.exportAssets(TENANT_ID, VERSION_NUMBER); + var selected = selectedFullBundle(published, true, false); + markPublished(); + objectStore.clear(); + clearInvocations(s3Client); + + assertThrows( + IllegalArgumentException.class, + () -> exporter.repairPublishedAssets(TENANT_ID, VERSION_NUMBER, selected)); + verify(s3Client, never()).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + assertEquals(0, objectStore.size()); + } + + @Test + void selectedFullV4MixedParticipantProfileIsDeniedBeforeAnyRepairObjectWrite() throws Exception { + ExportedAssetManifest published = exporter.exportAssets(TENANT_ID, VERSION_NUMBER); + var selected = selectedFullBundle(published, false, true); + markPublished(); + objectStore.clear(); + clearInvocations(s3Client); + + assertThrows( + IllegalArgumentException.class, + () -> exporter.repairPublishedAssets(TENANT_ID, VERSION_NUMBER, selected)); + verify(s3Client, never()).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + assertEquals(0, objectStore.size()); + } + + private void markPublished() { + attempt.setStatus(PublishAttemptStatus.SUCCEEDED); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(4L); + artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); + artifact.setStateEpoch(3L); + } + + // Isolated upstream evidence, not proof that a live World/Account producer is enabled. + private PublishedReleaseBundleDto selectedFullBundle( + ExportedAssetManifest manifest, boolean foreignTarget, boolean mixedProfile) + throws Exception { + var selector = + PublishedWorldSelectorFixtures.selectedFullSeed( + new net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof( + foreignTarget ? UUID.randomUUID() : CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_ID, + TENANT_ID, + 3L, + TENANT_ID, + "NEW_GAME_ROW"), + "genesis:8b0c1a0f-b8c9-4c4b-9021-381f57699003"); + var participants = + new java.util.ArrayList<>( + PublishedWorldSelectorFixtures.participants( + VERSION_ID, + selector, + net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence + .SELECTED_FULL_SCHEMA_VERSION)); + if (mixedProfile) { + var original = participants.get(3); + participants.set( + 3, + new net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto( + original.participantKey(), + original.scopeValue(), + original.baseVersionId(), + original.appliedCommitId(), + original.contentDigest(), + 5, + original.abilitySchemaDigest(), + original.errorCode(), + original.errorMessage())); + } + return new PublishedReleaseBundleDto( + 1L, + TENANT_ID, + VERSION_ID, + VERSION_NUMBER, + "v4", + selector.request().publishWorkflowId(), + manifest.manifestHash(), + manifest.requiredManifestAssetKeys(), + participants, + List.of(), + "generation-1", + false, + null, + java.time.LocalDateTime.now(), + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + "opaque-release-ref", + manifest.manifestSchemaVersion(), + manifest.artifactDigests(), + selector); + } + private PublishedReleaseBundleDto publishedBundle(ExportedAssetManifest manifest) { return publishedBundleWithHash(manifest, manifest.manifestHash()); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java index 49a92deed2..56f5c0b682 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java @@ -7,6 +7,7 @@ import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -75,6 +76,8 @@ class VersionServiceImplTest { private static final String PUBLISH_REQUEST_ID = "publish-request-1"; private static final String PARTICIPANT_DEPENDENCY_FAILURE_CODE = "PARTICIPANT_DEPENDENCY_UNAVAILABLE"; + private static final String LIVE_ABILITY_DIGEST = "sha256:" + "b".repeat(64); + private static final String REQUESTED_ABILITY_DIGEST = "sha256:" + "c".repeat(64); private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); private static final UUID CANONICAL_TENANT_ID = UUID.fromString("12345678-1234-4234-8234-123456789abc"); @@ -1403,23 +1406,26 @@ void publishVersionDoesNotStartTemporalWorkflowWithoutOwnerFreeze() { .assertGatePassed(any(VersionDto.class), any(List.class)); } - @Test - void publishPluginVersionRequiresPublishedBaseVersionAbilityDigestMatch() { + @ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {true, false}) + void publishPluginVersionRequiresPublishedBaseVersionAbilityDigestMatch( + boolean hasOwnerEvidence) { Version version = new Version(); version.setId(7L); version.setTenantId("tenant-1"); when(versionRepository.findByTenantIdAndId("tenant-1", 7L)).thenReturn(Optional.of(version)); PublishedPluginVersion uploaded = uploadedPluginVersion("tenant-1", "plugin-1", "plugin-v1"); - uploaded.setAbilitySchemaDigest("digest-requested"); + uploaded.setAbilitySchemaDigest(REQUESTED_ABILITY_DIGEST); when(publishedPluginVersionRepository.findByTenantIdAndPluginIdAndPluginVersionId( "tenant-1", "plugin-1", "plugin-v1")) .thenReturn(Optional.of(uploaded)); when(pluginBundleStorageService.loadPluginBundle("tenant-1", "plugin-1", "plugin-v1")) .thenReturn(new byte[] {1, 2, 3}); when(pluginBundleIntakeService.parseAndVerify(any())) - .thenReturn(parsedPluginBundle("plugin-1", "plugin-v1", 7L, "digest-requested")); + .thenReturn(parsedPluginBundle("plugin-1", "plugin-v1", 7L, REQUESTED_ABILITY_DIGEST)); when(publishedReleaseBundleService.getPublishedReleaseBundle("tenant-1", 7L)) - .thenReturn(publishedReleaseBundle("tenant-1", 7L, "digest-live")); + .thenReturn( + publishedReleaseBundle("tenant-1", 7L, hasOwnerEvidence ? LIVE_ABILITY_DIGEST : null)); IllegalArgumentException thrown = assertThrows( @@ -1430,7 +1436,7 @@ void publishPluginVersionRequiresPublishedBaseVersionAbilityDigestMatch() { "plugin-1", "plugin-v1", 7L, - "digest-requested", + REQUESTED_ABILITY_DIGEST, "bundle-1", 1, null, @@ -1440,7 +1446,11 @@ void publishPluginVersionRequiresPublishedBaseVersionAbilityDigestMatch() { "ALLOWED", "notes")); - assertTrue(thrown.getMessage().contains("VALIDATION_FAILED_DESIGN")); + assertTrue( + thrown + .getMessage() + .contains(hasOwnerEvidence ? "VALIDATION_FAILED_DESIGN" : "lacks exact Game Logic")); + verify(pluginBundleStorageService, never()).exportPluginAssets(any(), any(), any(), any()); } @Test @@ -1462,7 +1472,7 @@ void publishPluginVersionRejectsRevokedSignerMetadata() { "plugin-1", "plugin-v1", 7L, - "digest-live", + LIVE_ABILITY_DIGEST, "bundle-1", 1, null, @@ -1494,7 +1504,7 @@ void publishPluginVersionRejectsBlockedComponentPolicy() { "plugin-1", "plugin-v1", 7L, - "digest-live", + LIVE_ABILITY_DIGEST, "bundle-1", 1, null, @@ -1519,9 +1529,9 @@ void publishPluginVersionRejectsPublishRequestThatDoesNotMatchUploadedBundleMeta when(pluginBundleStorageService.loadPluginBundle("tenant-1", "plugin-1", "plugin-v1")) .thenReturn(new byte[] {1, 2, 3}); when(pluginBundleIntakeService.parseAndVerify(any())) - .thenReturn(parsedPluginBundle("plugin-1", "plugin-v1", 7L, "digest-live")); + .thenReturn(parsedPluginBundle("plugin-1", "plugin-v1", 7L, LIVE_ABILITY_DIGEST)); when(publishedReleaseBundleService.getPublishedReleaseBundle("tenant-1", 7L)) - .thenReturn(publishedReleaseBundle("tenant-1", 7L, "digest-live")); + .thenReturn(publishedReleaseBundle("tenant-1", 7L, LIVE_ABILITY_DIGEST)); when(pluginBundleStorageService.exportPluginAssets( org.mockito.ArgumentMatchers.eq("tenant-1"), any(ParsedPluginBundle.class), @@ -1538,7 +1548,7 @@ void publishPluginVersionRejectsPublishRequestThatDoesNotMatchUploadedBundleMeta "plugin-1", "plugin-v1", 7L, - "digest-live", + LIVE_ABILITY_DIGEST, "bundle-1", 1, "", @@ -1572,9 +1582,9 @@ void publishPluginVersionSupersedesOlderPublishedVersionsForSamePlugin() { when(pluginBundleStorageService.loadPluginBundle("tenant-1", "plugin-1", "plugin-v2")) .thenReturn(new byte[] {1, 2, 3}); when(pluginBundleIntakeService.parseAndVerify(any())) - .thenReturn(parsedPluginBundle("plugin-1", "plugin-v2", 7L, "digest-live")); + .thenReturn(parsedPluginBundle("plugin-1", "plugin-v2", 7L, LIVE_ABILITY_DIGEST)); when(publishedReleaseBundleService.getPublishedReleaseBundle("tenant-1", 7L)) - .thenReturn(publishedReleaseBundle("tenant-1", 7L, "digest-live")); + .thenReturn(publishedReleaseBundle("tenant-1", 7L, LIVE_ABILITY_DIGEST)); when(pluginBundleStorageService.exportPluginAssets( org.mockito.ArgumentMatchers.eq("tenant-1"), any(ParsedPluginBundle.class), @@ -1593,7 +1603,7 @@ void publishPluginVersionSupersedesOlderPublishedVersionsForSamePlugin() { "plugin-1", "plugin-v2", 7L, - "digest-live", + LIVE_ABILITY_DIGEST, "bundle-1", 1, "", @@ -1628,7 +1638,7 @@ void publishPluginVersionRejectsTerminalRowsWithoutMutation() { "plugin-1", "plugin-v1", 7L, - "digest-live", + LIVE_ABILITY_DIGEST, "bundle-1", 1, "", @@ -2014,7 +2024,7 @@ void listVersionsUsesTenantScopedOrdering() { } private PublishedReleaseBundleDto publishedReleaseBundle( - String tenantId, long versionId, String automationDigest) { + String tenantId, long versionId, String gameLogicAbilityDigest) { return new PublishedReleaseBundleDto( 1L, tenantId, @@ -2029,8 +2039,18 @@ private PublishedReleaseBundleDto publishedReleaseBundle( "AUTOMATION_SCRIPTING", String.valueOf(versionId), "version:" + versionId, - automationDigest, + REQUESTED_ABILITY_DIGEST, + 6, + null, + null), + new PublishParticipantDigestDto( + "GAME_LOGIC", + String.valueOf(versionId), + null, + "version:" + versionId, + "a".repeat(64), 1, + gameLogicAbilityDigest, null, null)), "genrev-1", @@ -2060,7 +2080,7 @@ private PublishedPluginVersion uploadedPluginVersion( entity.setPluginVersionId(pluginVersionId); entity.setBaseVersionId(7L); entity.setPublicationState(VersionLifecycleState.SIGNATURE_VERIFIED); - entity.setAbilitySchemaDigest("digest-live"); + entity.setAbilitySchemaDigest(LIVE_ABILITY_DIGEST); entity.setBundleDigest("bundle-1"); entity.setManifestSchemaVersion(1); entity.setDistributionManifestHash(""); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/WorldPublishedStartLocationMtlsTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/WorldPublishedStartLocationMtlsTest.java new file mode 100644 index 0000000000..055ae114e1 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/WorldPublishedStartLocationMtlsTest.java @@ -0,0 +1,379 @@ +package unit.net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.math.BigInteger; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.Base64; +import java.util.Date; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationClient; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationGrpcCodec; +import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; +import net.firedevops.firemud.test.TlsTestSupport; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedStartLocationReadServiceGrpc; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * Physical loopback proof of the current shared client's pre-send and response checks. The server + * supplies explicitly isolated selected-full evidence, not actual World/Account commits, native + * storage qualification, enabled publication or deployed workload proof. + */ +class WorldPublishedStartLocationMtlsTest { + private static final String NAMESPACE = "test"; + private static final String GAME_DESIGN_PEER = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String WORLD_PEER = "spiffe://firemud/ns/test/sa/world-management-service"; + private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1L); + private static TestPki pki; + + @BeforeAll + static void generateEphemeralPki() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + KeyPair caKeyPair = newRsaKeyPair(); + X500Name caName = new X500Name("CN=World Published Selector Test CA, O=FireMUD Test"); + X509Certificate caCertificate = + issueCertificate(caName, caKeyPair.getPublic(), caName, caKeyPair.getPrivate(), true); + pki = + new TestPki( + caCertificate, + issueLeaf(caName, caKeyPair.getPrivate(), "game-design-service", GAME_DESIGN_PEER), + issueLeaf(caName, caKeyPair.getPrivate(), "world-management-service", WORLD_PEER), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "wrong-service-world-server", + "spiffe://firemud/ns/test/sa/game-design-service"), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "wrong-namespace-world-server", + "spiffe://firemud/ns/other-test/sa/world-management-service")); + } + + @Test + void wrongWorldServiceOrNamespaceSendsNoRpcMetadataOrRequestBodyButExactPeerSucceeds( + @TempDir Path directory) throws Exception { + WorldPublishedStartLocationEvidence evidence = evidence(); + int index = 0; + for (TestCertificate wrongServer : + List.of(pki.wrongServiceServer(), pki.wrongNamespaceServer())) { + PhysicalServer receiver = startReceiver(wrongServer, evidence); + try (WorldPublishedStartLocationClient client = + newClient(receiver.server().getPort(), directory.resolve("wrong-" + index++))) { + client.init(); + Throwable failure = catchThrowable(() -> client.read(evidence.request())); + + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isFalse(); + assertThat(receiver.requestMetadataCalls()).hasValue(0); + assertThat(receiver.requestBodies()).hasValue(0); + assertThat(receiver.request()).hasValue(null); + } finally { + stopServer(receiver.server()); + } + } + + PhysicalServer receiver = startReceiver(pki.worldServer(), evidence); + try (WorldPublishedStartLocationClient client = + newClient(receiver.server().getPort(), directory.resolve("exact-world-peer"))) { + client.init(); + WorldPublishedStartLocationEvidence received = client.read(evidence.request()); + + assertThat(received).isEqualTo(evidence); + assertThat(receiver.requestMetadataCalls()).hasValue(1); + assertThat(receiver.requestBodies()).hasValue(1); + assertThat(receiver.authenticatedCallerPeer()).hasValue(GAME_DESIGN_PEER); + assertThat(receiver.request()) + .hasValue(WorldPublishedStartLocationGrpcCodec.toRequest(evidence.request())); + } finally { + stopServer(receiver.server()); + } + } + + @Test + void exactWorldPeerCannotSubstituteSelectionOrOmitRetainedEvidence(@TempDir Path directory) + throws Exception { + var evidence = evidence(); + var original = WorldPublishedStartLocationGrpcCodec.toResponse(evidence.request(), evidence); + var tampered = + List.of( + original.toBuilder().setPublicationRequestId("substituted-request").build(), + original.toBuilder().clearOriginalAccountBindingBytes().build(), + original.toBuilder() + .setAppliedResultBytes(com.google.protobuf.ByteString.copyFromUtf8("{}")) + .build()); + int index = 0; + for (var response : tampered) { + PhysicalServer receiver = startReceiver(pki.worldServer(), response); + try (WorldPublishedStartLocationClient client = + newClient(receiver.server().getPort(), directory.resolve("tampered-" + index++))) { + client.init(); + Throwable failure = catchThrowable(() -> client.read(evidence.request())); + assertThat(failure) + .isInstanceOf(IllegalStateException.class) + .hasMessage("World returned invalid published selector evidence"); + assertThat(receiver.requestMetadataCalls()).hasValue(1); + assertThat(receiver.requestBodies()).hasValue(1); + assertThat(receiver.authenticatedCallerPeer()).hasValue(GAME_DESIGN_PEER); + assertThat(receiver.request()) + .hasValue(WorldPublishedStartLocationGrpcCodec.toRequest(evidence.request())); + } finally { + stopServer(receiver.server()); + } + } + } + + private static PhysicalServer startReceiver( + TestCertificate serverCertificate, WorldPublishedStartLocationEvidence evidence) + throws Exception { + return startReceiver( + serverCertificate, + WorldPublishedStartLocationGrpcCodec.toResponse(evidence.request(), evidence)); + } + + private static PhysicalServer startReceiver( + TestCertificate serverCertificate, ReadWorldPublishedStartLocationResponse response) + throws Exception { + AtomicInteger requestMetadataCalls = new AtomicInteger(); + AtomicInteger requestBodies = new AtomicInteger(); + AtomicReference request = new AtomicReference<>(); + AtomicReference authenticatedCallerPeer = new AtomicReference<>(); + var service = + new WorldPublishedStartLocationReadServiceGrpc + .WorldPublishedStartLocationReadServiceImplBase() { + @Override + public void readWorldPublishedStartLocation( + ReadWorldPublishedStartLocationRequest readRequest, + StreamObserver responseObserver) { + requestBodies.incrementAndGet(); + request.set(readRequest); + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + authenticatedCallerPeer.set(peer == null ? null : peer.uri()); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + }; + ServerInterceptor metadataCounter = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + io.grpc.Metadata headers, + ServerCallHandler next) { + requestMetadataCalls.incrementAndGet(); + return next.startCall(call, headers); + } + }; + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverCertificate.privateKey(), serverCertificate.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, metadataCounter, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + return new PhysicalServer( + server, requestMetadataCalls, requestBodies, request, authenticatedCallerPeer); + } + + private static WorldPublishedStartLocationClient newClient(int port, Path directory) + throws Exception { + Files.createDirectories(directory); + Path clientCertificate = + writePem( + directory.resolve("game-design-client.crt"), + "CERTIFICATE", + pki.gameDesignClient().certificate().getEncoded()); + Path clientPrivateKey = + writePem( + directory.resolve("game-design-client.key"), + "PRIVATE KEY", + pki.gameDesignClient().privateKey().getEncoded()); + Path caCertificate = + writePem(directory.resolve("test-ca.crt"), "CERTIFICATE", pki.caCertificate().getEncoded()); + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(clientCertificate.toString()); + tls.setPrivateKey(clientPrivateKey.toString()); + tls.setCaCert(caCertificate.toString()); + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("127.0.0.1:" + port); + return new WorldPublishedStartLocationClient( + endpoints, tls, new GrpcChannelFactory(), NAMESPACE); + } + + private static WorldPublishedStartLocationEvidence evidence() throws Exception { + return PublishedWorldSelectorFixtures.selectedFullSeed( + new TargetProof( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 19L, + "tenant-key", + 42L, + "tenant-key", + "NEW_GAME_ROW"), + "genesis:8b0c1a0f-b8c9-4c4b-9021-381f57699003"); + } + + private static void stopServer(Server server) throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + private static TestCertificate issueLeaf( + X500Name caName, PrivateKey caPrivateKey, String commonName, String workloadUri) + throws Exception { + KeyPair keyPair = newRsaKeyPair(); + X500Name subject = new X500Name("CN=" + commonName + ", O=FireMUD Test"); + GeneralNames subjectAltNames = + new GeneralNames( + new GeneralName[] { + new GeneralName(GeneralName.uniformResourceIdentifier, workloadUri), + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + }); + X509Certificate certificate = + issueCertificate( + subject, keyPair.getPublic(), caName, caPrivateKey, false, subjectAltNames); + return new TestCertificate(keyPair.getPrivate(), certificate); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerPrivateKey, + boolean ca) + throws Exception { + return issueCertificate(subject, publicKey, issuer, issuerPrivateKey, ca, null); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerPrivateKey, + boolean ca, + GeneralNames subjectAltNames) + throws Exception { + Instant notBefore = Instant.now().minusSeconds(60); + JcaX509v3CertificateBuilder builder = + new JcaX509v3CertificateBuilder( + issuer, + BigInteger.valueOf(CERTIFICATE_SERIAL.getAndIncrement()), + Date.from(notBefore), + Date.from(notBefore.plusSeconds(60L * 60L * 24L * 14L)), + subject, + publicKey); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca)); + if (ca) { + builder.addExtension( + Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); + } else { + builder.addExtension( + Extension.keyUsage, + true, + new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + new KeyPurposeId[] {KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth})); + builder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); + } + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuerPrivateKey))); + } + + private static KeyPair newRsaKeyPair() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private static Path writePem(Path path, String type, byte[] encoded) throws IOException { + String base64 = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(encoded); + Files.writeString( + path, "-----BEGIN " + type + "-----\n" + base64 + "\n-----END " + type + "-----\n"); + return path; + } + + private record TestCertificate(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestCertificate gameDesignClient, + TestCertificate worldServer, + TestCertificate wrongServiceServer, + TestCertificate wrongNamespaceServer) {} + + private record PhysicalServer( + Server server, + AtomicInteger requestMetadataCalls, + AtomicInteger requestBodies, + AtomicReference request, + AtomicReference authenticatedCallerPeer) {} +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport.java index c4170b14a1..2474d77205 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport.java @@ -9,6 +9,8 @@ import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.sync.RedisCommands; import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.event.connection.ConnectedEvent; +import io.lettuce.core.event.connection.DisconnectedEvent; import io.lettuce.core.protocol.CommandKeyword; import io.lettuce.core.protocol.CommandType; import java.math.BigInteger; @@ -21,6 +23,7 @@ import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; @@ -32,6 +35,7 @@ import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; +import reactor.core.Disposable; @SuppressWarnings("resource") abstract class CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport { @@ -47,6 +51,9 @@ abstract class CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSup RedisClient administrator; RedisClient ownerClient; + private final AtomicInteger ownerConnected = new AtomicInteger(); + private final AtomicInteger ownerDisconnected = new AtomicInteger(); + private Disposable ownerEvents; RedisURI ownerUri; StatefulRedisConnection adminConnection; RedisCommands admin; @@ -98,6 +105,16 @@ void setUp() throws Exception { ownerUri = redisUri(PRINCIPAL, password); ownerClient = RedisClient.create(ownerUri); ownerClient.setOptions(ClientOptions.builder().autoReconnect(false).build()); + ownerEvents = + ownerClient + .getResources() + .eventBus() + .get() + .subscribe( + event -> { + if (event instanceof ConnectedEvent) ownerConnected.incrementAndGet(); + if (event instanceof DisconnectedEvent) ownerDisconnected.incrementAndGet(); + }); DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); String jdbcUrl = postgresContainer().getJdbcUrl(); @@ -143,6 +160,7 @@ void tearDown() throws Exception { try { if (fixture != null) fixture.close(); } finally { + if (ownerEvents != null) ownerEvents.dispose(); if (adminConnection != null) adminConnection.close(); if (ownerClient != null) ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); if (administrator != null) administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); @@ -182,15 +200,26 @@ void bridge(boolean authorizeCapacity) { } void bridge(boolean authorizeCapacity, int maximumRecords, long maximumBindingBytes) { - regionBinding = - CanonicalGameplayRegionOwnerCompositionFixture.installExistingOriginalCandidate( - fixture.dsl(), - ownerClient, - ownerUri, - fixture.transitionId(), - sources.request, - sources.resolver, - sources.entity); + try { + regionBinding = + CanonicalGameplayRegionOwnerCompositionFixture.installExistingOriginalCandidate( + fixture.dsl(), + ownerClient, + ownerUri, + fixture.transitionId(), + sources.request, + sources.resolver, + sources.entity); + } catch (IllegalStateException failure) { + // Keep the original failure and record only event counts; events may lag the failure thread. + failure.addSuppressed( + new IllegalStateException( + "Region fixture Redis owner events before teardown: connected=" + + ownerConnected.get() + + ", disconnected=" + + ownerDisconnected.get())); + throw failure; + } assertThat(regionBinding.owner().bridge(regionBinding.installation()).obligation()) .isEqualTo(regionBinding.acknowledgement().obligation()); var assignment = tags.assignmentForTransition(fixture.transitionId()); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 70c9b0c700..88b8079f09 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -619,9 +619,13 @@ void websocketLogoutWithoutDurableFenceRetainsSessionAndTransport() throws Excep var before = sessionContextService.findByTenantAndSessionId(22L, 41L); assertThat(before).isPresent(); - client.send("LOGOUT"); - client.awaitStartsWith("ERROR LOGOUT_UNAVAILABLE"); - assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)).isEqualTo(before); + for (int attempt = 0; attempt < 2; attempt++) { + int responseCount = client.responses().size(); + client.send("LOGOUT"); + client.awaitTranscriptContainingAllAfter( + responseCount, "ERROR LOGOUT_UNAVAILABLE", "Logout is temporarily unavailable"); + assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)).isEqualTo(before); + } client.send("WHO"); client.awaitStartsWith("OK WHO"); @@ -642,6 +646,32 @@ void unavailableWebsocketLogoutDoesNotReplayOrClearRetainedOutput() throws Excep } } + @Test + void freshLoginAfterUnavailableLogoutAndClientCloseDoesNotReplayStaleReconnectBuffer() + throws Exception { + when(screenBufferService.get(eq(22L), eq(1L), eq(123L))) + .thenReturn( + Optional.of( + new ScreenBufferService.BufferedScreen( + java.util.List.of( + ScreenBufferService.BufferedEntry.fromText( + "STALE REPLAY SHOULD NOT APPEAR")), + 1, + 1, + System.currentTimeMillis()))); + + performUnavailableLogoutAndClientClose("41"); + + List secondPayloads; + try (GameplayWebSocketDriver client = openAdmittedGameplayDriver("42")) { + secondPayloads = client.responses(); + } + + assertThat(secondPayloads) + .noneMatch(payload -> payload.contains("STALE REPLAY SHOULD NOT APPEAR")); + verify(screenBufferService, never()).get(22L, 1L, 123L); + } + @Test void unexpectedDisconnectKeepsFreshReconnectLookButDoesNotReplayPrivateContext() throws Exception { @@ -1063,6 +1093,16 @@ private URI websocketUri() { return URI.create("ws://localhost:" + port + "/ws/game"); } + private void performUnavailableLogoutAndClientClose(String sessionId) throws Exception { + try (GameplayWebSocketDriver client = openAdmittedGameplayDriver(sessionId)) { + client.send("LOGOUT"); + client.awaitStartsWith("ERROR LOGOUT_UNAVAILABLE"); + assertThat(sessionContextService.findByTenantAndSessionId(22L, Long.parseLong(sessionId))) + .isPresent(); + // Closing this client is not successful logout or a durable Account revocation. + } + } + private void bumpProductionAdmissionPointer( long newGameInstanceId, boolean requiresCharacterSelection) { GameplayAdmissionPointerSnapshot currentPointer = diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/CanonicalGatewayRoutesConfiguration.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/CanonicalGatewayRoutesConfiguration.java index f1ac488d81..4b35bf4759 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/CanonicalGatewayRoutesConfiguration.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/CanonicalGatewayRoutesConfiguration.java @@ -70,11 +70,19 @@ public GatewayProperties canonicalGatewayProperties(Environment environment) { 2, "GET"), route( - "design", + "design-ping", environment.getProperty( "FIREMUD_GATEWAY_ROUTE_DESIGN_URI", "http://game-design-service:8080"), - "/api/design/**", - 2), + "/api/design/ping", + 2, + "GET"), + route( + "design-templates-read", + environment.getProperty( + "FIREMUD_GATEWAY_ROUTE_DESIGN_URI", "http://game-design-service:8080"), + "/api/design/templates", + 2, + "GET"), route( "account-auth-login", environment.getProperty( diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupport.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupport.java index d980fa953c..79c4d7cb19 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupport.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupport.java @@ -9,9 +9,13 @@ import org.springframework.cloud.gateway.filter.FilterDefinition; import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition; import org.springframework.cloud.gateway.route.RouteDefinition; +import org.springframework.http.server.PathContainer; +import org.springframework.web.util.pattern.PathPatternParser; final class GatewayRouteTestSupport { + private static final PathPatternParser PATH_PATTERN_PARSER = new PathPatternParser(); + private GatewayRouteTestSupport() {} static RouteDefinition route(GatewayProperties gatewayProperties, String routeId) { @@ -63,16 +67,53 @@ static void assertNoConfiguredPath(GatewayProperties gatewayProperties, String p .collect(Collectors.toSet()); assertThat(configuredPaths).doesNotContain(path); + if (isConcretePath(path)) { + assertThat(configuredPaths) + .noneMatch(configuredPath -> pathPatternMatches(configuredPath, path)); + } + } + + static void assertNoRouteWithPathAndMethod( + GatewayProperties gatewayProperties, String path, String method) { + assertThat( + gatewayProperties.getRoutes().stream() + .noneMatch( + route -> + route.getPredicates().stream() + .filter(predicate -> "Path".equalsIgnoreCase(predicate.getName())) + .flatMap(predicate -> predicate.getArgs().values().stream()) + .anyMatch( + configuredPath -> pathPatternMatches(configuredPath, path)) + && (route.getPredicates().stream() + .noneMatch( + predicate -> "Method".equalsIgnoreCase(predicate.getName())) + || route.getPredicates().stream() + .filter( + predicate -> "Method".equalsIgnoreCase(predicate.getName())) + .flatMap(predicate -> predicate.getArgs().values().stream()) + .anyMatch(method::equals)))) + .as("route %s %s must not be configured", method, path) + .isTrue(); } static void assertSocialChatAndFriendsAreEdgeGated(GatewayProperties gatewayProperties) { assertThat(gatewayProperties.getRoutes().stream().map(RouteDefinition::getId)) .doesNotContain("social-chat", "social-friends"); assertNoConfiguredPath(gatewayProperties, "/api/social/**"); + assertNoConfiguredPath(gatewayProperties, "/api/social/chat/messages"); + assertNoConfiguredPath(gatewayProperties, "/api/social/friends"); assertNoConfiguredPathStartsWith(gatewayProperties, "/api/social/chat"); assertNoConfiguredPathStartsWith(gatewayProperties, "/api/social/friends"); } + private static boolean isConcretePath(String path) { + return path.indexOf('*') < 0 && path.indexOf('{') < 0 && path.indexOf('}') < 0; + } + + private static boolean pathPatternMatches(String configuredPath, String probePath) { + return PATH_PATTERN_PARSER.parse(configuredPath).matches(PathContainer.parsePath(probePath)); + } + static void assertHasStripPrefixTwo(GatewayProperties gatewayProperties, String routeId) { assertHasStripPrefix(gatewayProperties, routeId, "2"); } diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupportTest.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupportTest.java new file mode 100644 index 0000000000..0e093e9b69 --- /dev/null +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupportTest.java @@ -0,0 +1,123 @@ +package net.firedevops.firemud.springcloudgateway.config; + +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoConfiguredPath; +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoRouteWithPathAndMethod; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.LinkedHashMap; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.springframework.cloud.gateway.config.GatewayProperties; +import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition; +import org.springframework.cloud.gateway.route.RouteDefinition; + +class GatewayRouteTestSupportTest { + + @Test + void assertNoConfiguredPathRejectsWildcardAndPathVariableMatches() { + assertThatThrownBy( + () -> + assertNoConfiguredPath( + gatewayProperties(route(List.of("/api/design/**"), null)), + "/api/design/assets")) + .isInstanceOf(AssertionError.class); + + assertThatThrownBy( + () -> + assertNoConfiguredPath( + gatewayProperties(route(List.of("/api/design/{resource}"), null)), + "/api/design/assets")) + .isInstanceOf(AssertionError.class); + } + + @Test + void assertNoConfiguredPathPreservesExactWildcardPatternAssertion() { + assertThatThrownBy( + () -> + assertNoConfiguredPath( + gatewayProperties(route(List.of("/api/social/**"), null)), "/api/social/**")) + .isInstanceOf(AssertionError.class); + } + + @Test + void assertNoRouteWithPathAndMethodRejectsMatchingWildcardAndPathVariableRoutes() { + assertThatThrownBy( + () -> + assertNoRouteWithPathAndMethod( + gatewayProperties(route(List.of("/api/design/**"), "POST")), + "/api/design/assets", + "POST")) + .isInstanceOf(AssertionError.class); + + assertThatThrownBy( + () -> + assertNoRouteWithPathAndMethod( + gatewayProperties(route(List.of("/api/design/{resource}"), "POST")), + "/api/design/assets", + "POST")) + .isInstanceOf(AssertionError.class); + } + + @Test + void assertNoRouteWithPathAndMethodTreatsMissingMethodAsMatchingAndOtherMethodAsNonmatching() { + assertThatThrownBy( + () -> + assertNoRouteWithPathAndMethod( + gatewayProperties(route(List.of("/api/design/**"), null)), + "/api/design/assets", + "POST")) + .isInstanceOf(AssertionError.class); + + assertThatCode( + () -> + assertNoRouteWithPathAndMethod( + gatewayProperties(route(List.of("/api/design/**"), "GET")), + "/api/design/assets", + "POST")) + .doesNotThrowAnyException(); + + assertThatCode( + () -> + assertNoRouteWithPathAndMethod( + gatewayProperties(route(List.of("/api/other/**"), "POST")), + "/api/design/assets", + "POST")) + .doesNotThrowAnyException(); + } + + @Test + void assertNoRouteWithPathAndMethodChecksEveryConfiguredPathPattern() { + RouteDefinition route = route(List.of("/api/unrelated/**", "/api/design/{resource}"), "POST"); + + assertThatThrownBy( + () -> + assertNoRouteWithPathAndMethod( + gatewayProperties(route), "/api/design/assets", "POST")) + .isInstanceOf(AssertionError.class); + } + + private static GatewayProperties gatewayProperties(RouteDefinition... routes) { + GatewayProperties properties = new GatewayProperties(); + properties.setRoutes(List.of(routes)); + return properties; + } + + private static RouteDefinition route(List paths, String method) { + RouteDefinition route = new RouteDefinition(); + List predicates = new java.util.ArrayList<>(); + PredicateDefinition pathPredicate = new PredicateDefinition(); + pathPredicate.setName("Path"); + LinkedHashMap pathPatterns = new LinkedHashMap<>(); + for (int index = 0; index < paths.size(); index++) { + pathPatterns.put("_genkey_" + index, paths.get(index)); + } + pathPredicate.setArgs(pathPatterns); + predicates.add(pathPredicate); + if (method != null) { + predicates.add(new PredicateDefinition("Method=" + method)); + } + route.setPredicates(predicates); + return route; + } +} diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationProdTest.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationProdTest.java index 9b27336c46..015309e735 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationProdTest.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationProdTest.java @@ -3,7 +3,9 @@ import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasMethod; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasPath; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasStripPrefixTwo; +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoConfiguredPath; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoConfiguredPathStartsWith; +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoRouteWithPathAndMethod; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertSocialChatAndFriendsAreEdgeGated; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.route; import static org.assertj.core.api.Assertions.assertThat; @@ -47,7 +49,8 @@ class GatewayRoutesConfigurationProdTest { "admin-remote-followups", "admin-sagas", "admin-tick-remediation", - "design", + "design-ping", + "design-templates-read", "account-auth-login", "account-auth-player-bootstrap", "account-auth-bootstrap-worlds", @@ -131,13 +134,21 @@ void restEdgeRoutesStripExternalServicePrefixBeforeForwarding() { assertHasPath(gatewayProperties, "admin-remote-followups", "/api/admin/remote-followups/**"); assertHasPath(gatewayProperties, "admin-tick-remediation", "/api/admin/tick-remediation/**"); assertHasMethod(gatewayProperties, "admin-tick-remediation", "GET"); - assertHasPath(gatewayProperties, "design", "/api/design/**"); + assertHasPath(gatewayProperties, "design-ping", "/api/design/ping"); + assertHasMethod(gatewayProperties, "design-ping", "GET"); + assertHasPath(gatewayProperties, "design-templates-read", "/api/design/templates"); + assertHasMethod(gatewayProperties, "design-templates-read", "GET"); + assertNoConfiguredPath(gatewayProperties, "/api/design/**"); + assertNoConfiguredPath(gatewayProperties, "/api/design/assets"); + assertNoRouteWithPathAndMethod(gatewayProperties, "/api/design/templates", "POST"); + assertNoRouteWithPathAndMethod(gatewayProperties, "/api/design/assets", "POST"); GatewayAuthRoutesTest.assertCatalog(gatewayProperties); assertHasStripPrefixTwo(gatewayProperties, "admin-ping"); assertHasStripPrefixTwo(gatewayProperties, "admin-admission-pointers"); assertHasStripPrefixTwo(gatewayProperties, "admin-remote-followups"); assertHasStripPrefixTwo(gatewayProperties, "admin-tick-remediation"); - assertHasStripPrefixTwo(gatewayProperties, "design"); + assertHasStripPrefixTwo(gatewayProperties, "design-ping"); + assertHasStripPrefixTwo(gatewayProperties, "design-templates-read"); assertHasStripPrefixTwo(gatewayProperties, "account-auth-login"); } } diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTest.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTest.java index ec9c68b5e0..faff14a346 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTest.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTest.java @@ -3,7 +3,9 @@ import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasMethod; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasPath; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasStripPrefixTwo; +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoConfiguredPath; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoConfiguredPathStartsWith; +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoRouteWithPathAndMethod; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertSocialChatAndFriendsAreEdgeGated; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.route; import static org.assertj.core.api.Assertions.assertThat; @@ -46,7 +48,8 @@ class GatewayRoutesConfigurationTest { "admin-remote-followups", "admin-sagas", "admin-tick-remediation", - "design", + "design-ping", + "design-templates-read", "account-auth-login", "account-auth-player-bootstrap", "account-auth-bootstrap-worlds", @@ -141,8 +144,16 @@ void restEdgeRoutesStripExternalServicePrefixBeforeForwarding() { assertHasStripPrefixTwo(gatewayProperties, "admin-sagas"); assertHasStripPrefixTwo(gatewayProperties, "admin-tick-remediation"); - assertHasPath(gatewayProperties, "design", "/api/design/**"); - assertHasStripPrefixTwo(gatewayProperties, "design"); + assertHasPath(gatewayProperties, "design-ping", "/api/design/ping"); + assertHasMethod(gatewayProperties, "design-ping", "GET"); + assertHasStripPrefixTwo(gatewayProperties, "design-ping"); + assertHasPath(gatewayProperties, "design-templates-read", "/api/design/templates"); + assertHasMethod(gatewayProperties, "design-templates-read", "GET"); + assertHasStripPrefixTwo(gatewayProperties, "design-templates-read"); + assertNoConfiguredPath(gatewayProperties, "/api/design/**"); + assertNoConfiguredPath(gatewayProperties, "/api/design/assets"); + assertNoRouteWithPathAndMethod(gatewayProperties, "/api/design/templates", "POST"); + assertNoRouteWithPathAndMethod(gatewayProperties, "/api/design/assets", "POST"); GatewayAuthRoutesTest.assertCatalog(gatewayProperties); assertHasPath(gatewayProperties, "account-accounts", "/api/account/accounts/**"); diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTestProfileTest.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTestProfileTest.java index 5347df4cba..20a4a87aca 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTestProfileTest.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRoutesConfigurationTestProfileTest.java @@ -3,7 +3,9 @@ import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasMethod; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasPath; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertHasStripPrefix; +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoConfiguredPath; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoConfiguredPathStartsWith; +import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertNoRouteWithPathAndMethod; import static net.firedevops.firemud.springcloudgateway.config.GatewayRouteTestSupport.assertSocialChatAndFriendsAreEdgeGated; import static org.assertj.core.api.Assertions.assertThat; @@ -46,7 +48,8 @@ class GatewayRoutesConfigurationTestProfileTest { "admin-remote-followups", "admin-sagas", "admin-tick-remediation", - "design", + "design-ping", + "design-templates-read", "account-auth-login", "account-auth-player-bootstrap", "account-auth-bootstrap-worlds", @@ -122,7 +125,14 @@ void testProfileRestRoutesStripExternalServicePrefix() { assertHasPath(gatewayProperties, "admin-tick-remediation", "/api/admin/tick-remediation/**"); assertHasMethod(gatewayProperties, "admin-tick-remediation", "GET"); - assertHasPath(gatewayProperties, "design", "/api/design/**"); + assertHasPath(gatewayProperties, "design-ping", "/api/design/ping"); + assertHasMethod(gatewayProperties, "design-ping", "GET"); + assertHasPath(gatewayProperties, "design-templates-read", "/api/design/templates"); + assertHasMethod(gatewayProperties, "design-templates-read", "GET"); + assertNoConfiguredPath(gatewayProperties, "/api/design/**"); + assertNoConfiguredPath(gatewayProperties, "/api/design/assets"); + assertNoRouteWithPathAndMethod(gatewayProperties, "/api/design/templates", "POST"); + assertNoRouteWithPathAndMethod(gatewayProperties, "/api/design/assets", "POST"); assertHasPath(gatewayProperties, "session-ping", "/api/session/ping"); @@ -144,7 +154,8 @@ void testProfileRestRoutesStripExternalServicePrefix() { assertHasStripPrefix(gatewayProperties, "admin-remote-followups", "2"); assertHasStripPrefix(gatewayProperties, "admin-sagas", "2"); assertHasStripPrefix(gatewayProperties, "admin-tick-remediation", "2"); - assertHasStripPrefix(gatewayProperties, "design", "2"); + assertHasStripPrefix(gatewayProperties, "design-ping", "2"); + assertHasStripPrefix(gatewayProperties, "design-templates-read", "2"); assertHasStripPrefix(gatewayProperties, "account-auth-login", "2"); assertHasStripPrefix(gatewayProperties, "account-accounts", "2"); assertHasStripPrefix(gatewayProperties, "account-profiles", "2"); diff --git a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java index 2c03b7f106..b1de54fe85 100644 --- a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java +++ b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java @@ -453,6 +453,11 @@ void telnetItemLoopStillSucceedsAfterWebSocketLogoutRefusalOnSharedRuntime() thr webSocketClient.awaitResponseMatching( response -> response.contains("You drop Torch."), "drop response")) .contains("You drop Torch."); + SessionContextService sessionContextService = gameSession().bean(SessionContextService.class); + var originalSession = + sessionContextService.findByGameplayIdentity( + TENANT_ID, DEMO_WORLD_INSTANCE_ID, ACCOUNT_ID); + assertThat(originalSession).isPresent(); webSocketClient.send("LOGOUT"); assertThat( webSocketClient.awaitResponseMatching( @@ -460,6 +465,10 @@ void telnetItemLoopStillSucceedsAfterWebSocketLogoutRefusalOnSharedRuntime() thr "retryable logout refusal")) .contains("ERROR LOGOUT_UNAVAILABLE Logout is temporarily unavailable.") .doesNotContain("OK LOGOUT"); + assertThat( + sessionContextService.findByGameplayIdentity( + TENANT_ID, DEMO_WORLD_INSTANCE_ID, ACCOUNT_ID)) + .isEqualTo(originalSession); webSocketClient.send("INV HERE"); assertThat( webSocketClient.awaitResponseMatching(