diff --git a/.github/workflows/license-scan.yml b/.github/workflows/license-scan.yml index 594cc5911c..c9e2649515 100644 --- a/.github/workflows/license-scan.yml +++ b/.github/workflows/license-scan.yml @@ -43,6 +43,9 @@ jobs: with: filters: | gradle: + - 'config/ort/curations/**' + - 'config/ort/custom-license-texts/**' + - 'config/ort/gatling.ort.yml' - 'build.gradle.kts' - 'settings.gradle.kts' - 'gradle.properties' @@ -58,6 +61,8 @@ jobs: - '.github/workflows/release-notes.yml' - '.github/workflows/ort-advisory.yml' npm: + - 'config/ort/npm.ort.yml' + - 'config/ort/curations/**' - 'package.json' - 'package-lock.json' - 'config/openapi/package.json' @@ -136,16 +141,170 @@ jobs: with: image: ${{ steps.workflow-tool-versions.outputs.ort-image }} ort-cli-args: '-P ort.analyzer.enabledPackageManagers=Gradle' + ort-yml-path: ${{ github.workspace }}/config/ort/gatling.ort.yml + docker-cli-args: >- + -e CI=true + --mount type=bind,source=${{ github.workspace }}/config/ort/curations,target=/home/ort/.ort/config/curations/firemud,readonly + --mount type=bind,source=${{ github.workspace }}/config/ort/gatling.ort.yml,target=${{ github.workspace }}/config/ort/gatling.ort.yml,readonly + --mount type=bind,source=${{ github.workspace }}/config/ort/custom-license-texts/LicenseRef-Gatling-Highcharts-3.16.0,target=/home/ort/.ort/config/custom-license-texts/LicenseRef-Gatling-Highcharts-3.16.0,readonly run: 'cache-dependencies,labels,analyzer,evaluator,reporter' - fail-on: policy-violation + fail-on: 'violations' report-formats: 'CycloneDx,WebApp' ort-cli-report-args: '-O CycloneDX=output.file.formats=json,xml' - - name: Upload ORT results + - name: Require complete Gradle ORT analysis + id: gradle_analyzer_guard + shell: bash + run: | + if [[ "${ORT_CLI_ANALYZE_EXIT_CODE:-}" != "0" ]]; then + echo 'ORT analyzer did not complete successfully.' >&2 + exit 1 + fi + + - name: Diagnose Maven Central access after Gradle ORT failure + id: gradle_ort_diagnostic + if: ${{ failure() && (steps.ort.outcome == 'failure' || steps.gradle_analyzer_guard.outcome == 'failure') }} + continue-on-error: true + shell: bash + env: + ORT_DIAGNOSTIC_IMAGE: ${{ steps.workflow-tool-versions.outputs.ort-image }} + ORT_DIAGNOSTIC_DIRECTORY: ${{ runner.temp }}/ort-gradle-maven-diagnostic-${{ github.run_id }}-${{ github.run_attempt }} + MAVEN_POM_URL: https://repo.maven.apache.org/maven2/com/google/code/findbugs/jsr305/3.0.2/jsr305-3.0.2.pom + MAVEN_TRACE_URL: https://repo.maven.apache.org/cdn-cgi/trace + run: | + set +e + set -u -o pipefail + + raw_directory="${HOME}/.ort-maven-diagnostic-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + container_raw_directory="/home/ort/.ort-maven-diagnostic-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + summary_file="${ORT_DIAGNOSTIC_DIRECTORY}/summary.txt" + + cleanup_raw_directory() { + for raw_file in "${raw_directory}"/*; do + if [[ -f "${raw_file}" ]]; then + rm -f -- "${raw_file}" || true + fi + done + rmdir -- "${raw_directory}" 2>/dev/null || true + } + trap cleanup_raw_directory EXIT + + mkdir -p "${raw_directory}" "${ORT_DIAGNOSTIC_DIRECTORY}" + setup_exit=$? + if (( setup_exit != 0 )); then + printf 'diagnostic_setup_exit=%s\n' "${setup_exit}" + exit "${setup_exit}" + fi + + printf 'Diagnostic only; these probes do not establish license compliance.\n' > "${summary_file}" + + probe_http() { + local scope="$1" + local label="$2" + local url="$3" + local header_file="${raw_directory}/${scope}-${label}.headers" + local body_file="${raw_directory}/${scope}-${label}.body" + local error_file="${raw_directory}/${scope}-${label}.stderr" + local artifact_prefix="${ORT_DIAGNOSTIC_DIRECTORY}/${scope}-${label}" + local status="000" + local command_exit=0 + local header_bytes=0 + local body_bytes=0 + local error_bytes=0 + + if [[ "${scope}" == "runner" ]]; then + if status=$(curl --disable --silent --show-error \ + --connect-timeout 4 --max-time 10 --max-filesize 32768 \ + --dump-header "${header_file}" --output "${body_file}" \ + --write-out '%{http_code}' "${url}" 2>"${error_file}"); then + command_exit=0 + else + command_exit=$? + fi + elif [[ "${scope}" == "ort-container" ]]; then + local container_header_file="${container_raw_directory}/${scope}-${label}.headers" + local container_body_file="${container_raw_directory}/${scope}-${label}.body" + if [[ "${ORT_DIAGNOSTIC_IMAGE}" != *@sha256:* ]]; then + command_exit=90 + printf 'Refused unpinned ORT image reference.\n' > "${error_file}" + elif status=$(timeout --signal=TERM --kill-after=5s 20s docker run --rm \ + --mount "type=bind,source=${HOME},target=/home/ort" \ + --user "$(id -u):$(id -g)" \ + -e "JDK_JAVA_OPTIONS=${ORT_JDK_JAVA_OPTIONS:-}" \ + -e "ORT_DATA_DIR=/home/ort/${ORT_HOME_PATH:-.ort}" \ + --entrypoint curl "${ORT_DIAGNOSTIC_IMAGE}" \ + --disable --silent --show-error \ + --connect-timeout 4 --max-time 10 --max-filesize 32768 \ + --dump-header "${container_header_file}" --output "${container_body_file}" \ + --write-out '%{http_code}' "${url}" 2>"${error_file}"); then + command_exit=0 + else + command_exit=$? + fi + else + command_exit=90 + printf 'Unsupported diagnostic scope.\n' > "${error_file}" + fi + + if [[ ! "${status}" =~ ^[0-9]{3}$ ]]; then + status="000" + fi + + if [[ -f "${header_file}" ]]; then + sed -E 's/^(Set-Cookie|Authorization|Proxy-Authorization):.*/\1: /I' \ + "${header_file}" | head -c 8192 > "${artifact_prefix}.headers.txt" + else + : > "${artifact_prefix}.headers.txt" + fi + if [[ -f "${body_file}" ]]; then + head -c 8192 "${body_file}" > "${artifact_prefix}.body" + else + : > "${artifact_prefix}.body" + fi + if [[ -f "${error_file}" ]]; then + head -c 1024 "${error_file}" > "${artifact_prefix}.error.txt" + else + : > "${artifact_prefix}.error.txt" + fi + + header_bytes=$(wc -c < "${artifact_prefix}.headers.txt" | tr -d '[:space:]') + body_bytes=$(wc -c < "${artifact_prefix}.body" | tr -d '[:space:]') + error_bytes=$(wc -c < "${artifact_prefix}.error.txt" | tr -d '[:space:]') + printf 'probe=%s-%s command_exit=%s http_status=%s header_bytes=%s body_bytes=%s error_bytes=%s\n' \ + "${scope}" "${label}" "${command_exit}" "${status}" \ + "${header_bytes}" "${body_bytes}" "${error_bytes}" | tee -a "${summary_file}" + + last_command_exit="${command_exit}" + last_http_status="${status}" + } + + probe_http runner jsr305 "${MAVEN_POM_URL}" + runner_pom_exit="${last_command_exit}" + runner_pom_status="${last_http_status}" + probe_http ort-container jsr305 "${MAVEN_POM_URL}" + container_pom_exit="${last_command_exit}" + container_pom_status="${last_http_status}" + + if [[ "${runner_pom_exit}" != "0" || "${runner_pom_status}" != "200" || \ + "${container_pom_exit}" != "0" || "${container_pom_status}" != "200" ]]; then + probe_http runner cdn-cgi-trace "${MAVEN_TRACE_URL}" + probe_http ort-container cdn-cgi-trace "${MAVEN_TRACE_URL}" + fi + + - name: Upload ORT results, including partial analysis uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + if: ${{ always() && steps.ort.outcome != 'skipped' }} with: name: ort-result-gradle-${{ github.sha }} path: ${{ steps.ort.outputs.results-path }} + if-no-files-found: error + - name: Upload Gradle ORT connectivity diagnostics + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + if: ${{ always() && (steps.ort.outcome == 'failure' || steps.gradle_analyzer_guard.outcome == 'failure') }} + with: + name: ort-gradle-maven-diagnostic-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/ort-gradle-maven-diagnostic-${{ github.run_id }}-${{ github.run_attempt }} + if-no-files-found: error - name: Summarize ORT report if: github.event_name == 'pull_request' run: | @@ -208,16 +367,31 @@ jobs: with: image: ${{ steps.workflow-tool-versions.outputs.ort-image }} ort-cli-args: '-P ort.analyzer.enabledPackageManagers=NPM' + ort-yml-path: ${{ github.workspace }}/config/ort/npm.ort.yml + docker-cli-args: >- + --mount type=bind,source=${{ github.workspace }}/config/ort/npm.ort.yml,target=${{ github.workspace }}/config/ort/npm.ort.yml,readonly + --mount type=bind,source=${{ github.workspace }}/config/ort/curations,target=/home/ort/.ort/config/curations/firemud,readonly run: 'cache-dependencies,labels,analyzer,evaluator,reporter' - fail-on: policy-violation + fail-on: 'violations' report-formats: 'CycloneDx,WebApp' ort-cli-report-args: '-O CycloneDX=output.file.formats=json,xml' - - name: Upload ORT results + - name: Require complete NPM ORT analysis + id: npm_analyzer_guard + shell: bash + run: | + if [[ "${ORT_CLI_ANALYZE_EXIT_CODE:-}" != "0" ]]; then + echo 'ORT analyzer did not complete successfully.' >&2 + exit 1 + fi + + - name: Upload ORT results, including partial analysis uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + if: ${{ always() && steps.ort.outcome != 'skipped' }} with: name: ort-result-npm-${{ github.sha }} path: ${{ steps.ort.outputs.results-path }} + if-no-files-found: error - name: Summarize ORT report if: github.event_name == 'pull_request' run: | diff --git a/.github/workflows/ort-advisory.yml b/.github/workflows/ort-advisory.yml index a8b9bffdcd..5d2c5c57ae 100644 --- a/.github/workflows/ort-advisory.yml +++ b/.github/workflows/ort-advisory.yml @@ -63,6 +63,12 @@ jobs: with: image: ${{ steps.workflow-tool-versions.outputs.ort-image }} ort-cli-args: '-P ort.analyzer.enabledPackageManagers=Gradle,NPM' + ort-yml-path: ${{ github.workspace }}/config/ort/npm.ort.yml + docker-cli-args: >- + -e CI=true + --mount type=bind,source=${{ github.workspace }}/config/ort/npm.ort.yml,target=${{ github.workspace }}/config/ort/npm.ort.yml,readonly + --mount type=bind,source=${{ github.workspace }}/config/ort/curations,target=/home/ort/.ort/config/curations/firemud,readonly + --mount type=bind,source=${{ github.workspace }}/config/ort/custom-license-texts/LicenseRef-Gatling-Highcharts-3.16.0,target=/home/ort/.ort/config/custom-license-texts/LicenseRef-Gatling-Highcharts-3.16.0,readonly run: 'cache-dependencies,labels,analyzer,evaluator,advisor,reporter,upload-results' fail-on: 'violations' report-formats: 'CycloneDx,WebApp' diff --git a/config/ort/curations/firemud.yml b/config/ort/curations/firemud.yml new file mode 100644 index 0000000000..04e8419e84 --- /dev/null +++ b/config/ort/curations/firemud.yml @@ -0,0 +1,32 @@ +--- +- id: Maven:io.javaoperatorsdk:operator-framework:5.6.2 + curations: + comment: 'The parent POM declares Apache 2 License and links to Apache 2.0: https://repo.maven.apache.org/maven2/io/javaoperatorsdk/java-operator-sdk/5.6.2/java-operator-sdk-5.6.2.pom' + declared_license_mapping: + Apache 2 License: Apache-2.0 +- id: Maven:io.javaoperatorsdk:operator-framework-core:5.6.2 + curations: + comment: 'The parent POM declares Apache 2 License and links to Apache 2.0: https://repo.maven.apache.org/maven2/io/javaoperatorsdk/java-operator-sdk/5.6.2/java-operator-sdk-5.6.2.pom' + declared_license_mapping: + Apache 2 License: Apache-2.0 +- id: Maven:io.javaoperatorsdk:operator-framework-spring-boot-starter:6.7.1 + curations: + comment: 'The published POM declares Apache 2 License and links to Apache 2.0: https://repo.maven.apache.org/maven2/io/javaoperatorsdk/operator-framework-spring-boot-starter/6.7.1/operator-framework-spring-boot-starter-6.7.1.pom' + declared_license_mapping: + Apache 2 License: Apache-2.0 +- id: Maven:jaxen:jaxen:2.0.6 + curations: + comment: 'The tagged source license has the three BSD clauses, including non-endorsement; the POM''s BSD License 2.0 label + is not the SPDX BSD-2-Clause license: https://github.com/jaxen-xpath/jaxen/blob/v2.0.6/LICENSE.txt' + declared_license_mapping: + BSD License 2.0: BSD-3-Clause +- id: Maven:io.gatling.highcharts:gatling-charts-highcharts:3.16.0 + curations: + comment: >- + The exact published 3.16.0 JAR (SHA-1 d415db5ef3cc13f5bc7b45504a5dd0b247e8b17e) + contains this custom license text in META-INF/LICENSE. Preserve the text + verbatim under a package-specific LicenseRef; this metadata does not grant + rights or change the terms. Retention of the report generator remains + subject to human policy approval. + declared_license_mapping: + Gatling Highcharts: LicenseRef-Gatling-Highcharts-3.16.0 diff --git a/config/ort/custom-license-texts/LicenseRef-Gatling-Highcharts-3.16.0 b/config/ort/custom-license-texts/LicenseRef-Gatling-Highcharts-3.16.0 new file mode 100644 index 0000000000..ae5d6d0123 --- /dev/null +++ b/config/ort/custom-license-texts/LicenseRef-Gatling-Highcharts-3.16.0 @@ -0,0 +1,17 @@ +This module is protected by a specific license because it integrates the HighCharts & HighStock software, developed by the HighSoft company and protected by a specific licence granted to eBusiness Information in the context of the Gatling software project. + +eBusiness Information grants this license allowing the use, free-of-charge of the report generation module as delivered. No code modification is authorised, no re-use of the code, no copying of all or any part of the code is allowed. The components generated by the report generation module of the Gatling product can not be modified or re-used even partially. + +In particular, it is forbidden to re-use, copy or modify the HighSoft javascript components. For all use of the HighSoft components outside of the Gatling report generation module, please contact HighSoft company directly. + +This license does not permit the transfer of the intellectual rights associated with the software to the user of the licence of the Gatling software report generation module, or any of the other components within the software. + +This module is provided in its current state: +no complaints will be managed by eBusiness Information +no guarantee is provided by eBusiness Information for the correct working of the module, its potential impact on the beneficiary's information systems, the accuracy of the results or any problem found as a result of the direct or indirect use of the Gatling software report generation module. +The beneficiary uses the Gatling software report generation module at his own risk, any issues found as a result of the use of this software are his responsibility. +If any of the clauses in this present licence are declared null and void or inapplicable by the law, a ruling or as a result of decision of justice, then this clause would be excluded from the licence but all the other clauses would remain valid. + +This license and its terms and conditions are issued in accordance with French law. The involved parties agree that all disputes or controversies arising from the agreement as a result of interpretation, execution and/or termination of the license should be resolved amicably, out of court. + +If this is not possible, any resulting claim will be submitted to the Nanterre Court of Justice, it remains the only legal authority considered competent to deal with these claims, this includes claims relating to incidents, guarantees or multiple party claims. All claims must be notified and handled in French. \ No newline at end of file diff --git a/config/ort/gatling.ort.yml b/config/ort/gatling.ort.yml new file mode 100644 index 0000000000..1f163d2a58 --- /dev/null +++ b/config/ort/gatling.ort.yml @@ -0,0 +1,11 @@ +resolutions: + rule_violations: + - message: '^The license LicenseRef-Gatling-Highcharts-3\.16\.0 is currently not covered by policy rules\. The license was declared in package ''Maven:io\.gatling\.highcharts:gatling-charts-highcharts:3\.16\.0''\.$' + reason: NOT_MODIFIED_EXCEPTION + comment: >- + User-approved exception for the exact UNHANDLED_LICENSE message for + Gatling Highcharts 3.16.0. This covers internal use of the delivered, + unchanged report generator, without + distributing, copying, reusing, or modifying its code or generated + components. This resolution does not change the LicenseRef text or + generated notices. diff --git a/config/ort/npm.ort.yml b/config/ort/npm.ort.yml new file mode 100644 index 0000000000..30fb3d48d9 --- /dev/null +++ b/config/ort/npm.ort.yml @@ -0,0 +1,23 @@ +--- +license_choices: + package_license_choices: + - package_id: "NPM::jszip:3.10.2" + license_choices: + - given: "GPL-3.0-or-later OR MIT" + choice: "MIT" + comment: >- + Select the explicitly offered MIT alternative for this exact dependency. + The retained package identifies this upstream revision and its dual-license text: + https://github.com/Stuk/jszip/blob/020fa3384c994f923123141bbeebae0c3a44dd0d/LICENSE.markdown + +resolutions: + rule_violations: + - message: '^The license LicenseRef-Gatling-Highcharts-3\.16\.0 is currently not covered by policy rules\. The license was declared in package ''Maven:io\.gatling\.highcharts:gatling-charts-highcharts:3\.16\.0''\.$' + reason: NOT_MODIFIED_EXCEPTION + comment: >- + User-approved exception for the exact UNHANDLED_LICENSE message for + Gatling Highcharts 3.16.0. This covers internal use of the delivered, + unchanged report generator, without + distributing, copying, reusing, or modifying its code or generated + components. This resolution does not change the LicenseRef text or + generated notices. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 2738a109b0..11898fa62b 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,7 +8,7 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status -The selected-recipient intake source prepares distinct Entity/Automation source reservations and finalized authorizations, retained source-writer exclusion, and exact terminal settlement. Prepared final authorization and terminal migrations V1008–V1010 follow the actual V1006 activation-alignment and V1007 source-disclosure parent, including Saga V1000–V1002, while preserving prior protection/disposal guards. These components remain unregistered and unqualified; the [recipient-intake tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation) owns current proof, qualification limits and remaining dependencies. +The selected-recipient intake source prepares distinct Entity/Automation source reservations and finalized authorizations, retained source-writer exclusion, and exact terminal settlement. Expired preliminary recovery pages use a caller-held `(expiry epoch second, operation UUID)` keyset cursor that advances across every examined row, including invalid rows and candidates whose abort does not commit; a caller continues while a cursor is returned and starts a fresh sweep only after an empty page. Prepared final authorization and terminal migrations V1008–V1010 follow the actual V1006 activation-alignment and V1007 source-disclosure parent, including Saga V1000–V1002, while preserving prior protection/disposal guards. These components remain unregistered and unqualified; the [recipient-intake tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation) owns current proof, qualification limits and remaining dependencies. The additive [V1003 source-protection storage](../../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql) provides passive original StartSession admission and activation protection relations and source-writer exclusions. It adds no registered producer or transport. Qualification and remaining composition gates are recorded in the [source-protection tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage). @@ -354,4 +354,4 @@ Forward [V1004.2](../../../../services/account-service/src/main/resources/db/mig Forward [V1004.3](../../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql) requires all four Base64 carriers in the Account activation request to match the canonical encoding of their decoded tuple, projection, launch-read, and PREPARING bytes before protection acquisition. This prevents accepted whitespace spellings from being retained in an immutable request that later settlement must compare. It changes only the existing acquisition guard and does not backfill rows, authenticate World, or activate the source path. Current proof and limits are recorded in the [source-protection tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage). -V1003 preserves canonical predecessor SQL and retained owner rows; it never backfills protection, adopts missing historical evidence, fabricates owner proof or registers runtime authority. Its scoped PostgreSQL fixtures explicitly stipulate upstream capture/redemption/World rows with upstream producer triggers disabled while leaving the protection and source-writer guards under test enabled. Such execution establishes storage integrity, exclusion and retained-history behavior only. Genuine current-owner acquisition, authenticated terminal reads/settlement, continuously protected admission and activation remain unproved. Forward [Account V1007](../../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql) provides preliminary selected-owner reservation and source-writer storage; forward V1008–V1010 prepare finalized owner authorization/recovery and exact terminal settlement, with focused owner-storage and upgrade proof. Authenticated cross-owner composition, full-native qualification and registration remain open as recorded in the [selected-recipient tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation). +V1003 preserves canonical predecessor SQL and retained owner rows; it never backfills protection, adopts missing historical evidence, fabricates owner proof or registers runtime authority. Its scoped PostgreSQL fixtures explicitly stipulate upstream capture/redemption/World rows with upstream producer triggers disabled while leaving the protection and source-writer guards under test enabled. Such execution establishes storage integrity, exclusion and retained-history behavior only. Genuine current-owner acquisition, authenticated terminal reads/settlement, continuously protected admission and activation remain unproved. Forward [Account V1007](../../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql) provides preliminary selected-owner reservation and source-writer storage; forward V1008–V1010 prepare finalized owner authorization/recovery and exact terminal settlement, with focused owner-storage and upgrade proof. The receiving stage also prepares bounded recovery for expired abandoned preliminary reservations. Authenticated cross-owner composition, full-native qualification and registration remain open as recorded in the [selected-recipient tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation). diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 602bd309c5..238b4f5ab9 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -6,9 +6,11 @@ Game Design is the canonical authored-history, publication-coordination, release ## Implementation Status +R45 qualifies the controlled five-store selected-full owner composition, including schema-4 bundle write, independent readback and exact retry; detailed proof attribution and limits are recorded in the [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-full-owner-publication-preparation). Account authorization and source/provenance, creator, issuer, environment, asset metadata and PKI inputs remain controlled. Owner components remain standalone and unregistered, public fresh/PENDING publication remains denied, and the default Game Logic Spring composition remains denied. This does not establish genuine creator, issuer, environment, release or continuous-protection authority, activation, actor placement or operational delivery. + The recipient-intake preparation adds an unregistered Account-authenticated read of all six selected source families. Its required branding source owner uses existing [Game Design V1007 branding-source storage](../../../../services/game-design-service/src/main/resources/db/migration/V1007__branding_asset_source_history.sql), and command snapshot parsing converges on the shared typed contract while retaining owner-local capture context. No retained source is inferred or upgraded to complete. Qualification and selected-owner producer dependencies remain in the [recipient-intake tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation). -The shared strict selected-full attestation and terminal codecs, read-only World lifecycle support for schema 4 and a class-only guarded World evidence fixture are source-prepared and unqualified in this read stage. The actual Game Design writer/storage integration, fixture factory execution and five-store owner composition remain in the full selected-owner successor; this preparation supplies no fresh publication authority. Public fresh/PENDING publication remains denied and no activation or component registration is enabled. Current execution attribution and remaining qualification are recorded in the [selected-template tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-template-publication-and-original-launch-reads). +The shared strict selected-full codecs, read-only World lifecycle support for schema 4 and class-only guarded World evidence fixture are exercised in the R45 owner composition. Its detailed qualification and controlled-input limits are recorded in the [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-full-owner-publication-preparation); the separate [selected-template tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-template-publication-and-original-launch-reads) retains that slice's own scope and proof status. This owner composition grants no genuine creator, issuer, environment, release or continuous-protection authority, and enables no registration or activation. Standalone Template source/reference owners, selected-publication reservation and the exact original StartSession template read are prepared over existing guarded storage. They remain unregistered; qualified owner-local storage does not supply genuine Account, World or immutable-release authority. Current source, proof and retention limitations belong to [the authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-template-publication-and-original-launch-reads). diff --git a/design/architecture/microservices/game-logic-service/api-contracts.md b/design/architecture/microservices/game-logic-service/api-contracts.md index 1c9ef57cab..7d796d48a0 100644 --- a/design/architecture/microservices/game-logic-service/api-contracts.md +++ b/design/architecture/microservices/game-logic-service/api-contracts.md @@ -6,7 +6,7 @@ This document defines the Game Logic Service REST and gRPC surfaces, exposure cl - The current Game Logic adapters still return `shared.v1.ErrorDetail` for many failures and record `grpc.app_error`; that is implementation drift and a migration/proof gap, not a second contract. - Causal-read status is target-only: the complete `CausalReadFence` and participant-proof enforcement described below are not current behavior. The live `ResolveLook` request/proto and World/Entity adapters remain floor-free, so protobuf propagation, adapter evidence, and focused causal-floor proof are implementation gaps. -- The publish-gate digest handler enforces the distinct workload/method authorization and exact Game Design publication binding implemented by `PublicationReadGuard` and `PublicationDigestRequestBinding` (tenant, version scope, stable publish request, derived workflow identity, and request digest), with focused denial and response-scope checks. For a full-version request, the owner digest fails closed because Game Logic has no owner-local manifest and provenance sufficient to attest the version's rule inputs; it does not attest those inputs as an empty manifest. End-to-end full-version publication therefore remains blocked. The target workload, tenant/scope/request/workflow/digest context, exact response identity comparison, and denial proof are canonical in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity). +- The prepared publish-gate adapter can read the exact retained owner terminal, selected source and manifest through `GameLogicPublicationSourceReadService`, preserving the original authorization and both manifest/ability digests. R45 exercises this standalone adapter in the controlled selected-full owner composition; the [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-full-owner-publication-preparation) records its exact proof attribution and controlled-input limits. The default Spring composition and the no-receipt lookup remain denied, and this proof establishes no genuine upstream authority or publication enablement. The canonical selected contract is owned by [Game Design Version Control](../game-design-service/version-control.md#selected-full-publication-profile). ### Player execution context @@ -53,6 +53,18 @@ Expected response: ## gRPC +### Selected-source intake command + +The standalone [`RetainGameplayRuleIntake`](../../../../protos/game-logic/v1/gameplay_rule_intake_service.proto) method admits only the exact verified same-namespace Game Design workload, authenticated before decoding. Its versioned request carries independent transport correlation and the complete original Account intake authorization bytes/digest; the closed response echoes the exact binding and original immutable terminal. The intake owner rejects the canonical original Draft and Game Logic intake-authorization credential contexts; player or operator context supplies no intake mutation authority. A service identity alone does not authorize retention: the exact Account HELD operation and synchronized Game Design source remain mandatory under the [selected-input owner contract](runtime-and-data.md#draft-digest-contract). The adapter is unregistered and grants no publication, activation or runtime permission. + +### Selected-source terminal read + +The separate, unregistered [`ReadGameplayRuleIntakeTerminal`](../../../../protos/game-logic/v1/gameplay_rule_intake_terminal_service.proto) method accepts only verified same-namespace Account callers, authenticating before decoding source evidence. Its versioned request binds the namespace, fresh read correlation and exact original Account intake authorization bytes/digest. Its closed response echoes that tuple and returns either the original canonical terminal and digest or explicit absence; absence is not an abort. The read is allowlisted to Account and performs no source creation, retention, abort, settlement, or admission. The [Account owner contract](../account-service/api-contracts.md#grpc-apis) defines held-order fencing and exact settlement authority; the [runtime/data owner](runtime-and-data.md#draft-digest-contract) defines intake and definitive-abort semantics. The [selected intake tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) and [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) record unregistered transport, bounded-message and physical proof gates. + +The selected-full `GetDraftDesignDigest` adapter reads the exact retained source bound to the original Account-finalized receipt. A source-read failure that prevents producing that result uses a non-OK transport status under the [canonical classification](../../system-architecture-grpc.md#outcome-and-transport-classification), with a bounded generic description and no forwarded cause or trailers. Missing retained evidence uses `FAILED_PRECONDITION`; a conflicting retained binding uses `ALREADY_EXISTS`. Game Design preserves the original selection and retries only explicit transient dependency failures such as `UNAVAILABLE` and `DEADLINE_EXCEEDED`; those semantic precondition and binding failures do not become transient retries. The adapter records the bounded status code in `grpc.app_error` and its server diagnostic without logging arbitrary upstream descriptions. This standalone path remains unregistered. + +### Gameplay methods + - `Ping(PingRequest) returns (PingResponse)` is the basic connectivity check defined in [`game_logic_service.proto`](../../../../protos/game-logic/v1/game_logic_service.proto). - `ExecuteCommand(ExecuteCommandRequest) returns (ExecuteCommandResponse)` evaluates a parsed gameplay command and returns the outcome. - `SendCommunication` is the target gameplay communication contract: it inherits the complete validated `PlayerExecutionContext` from Game Session, classifies a world/gameplay communication type, resolves topology/perception/capability/effect facts, and forwards one bounded plan with stable identity, authorized candidate views, and owner handoffs. The current Game Logic adapter first requires `account_id` to be present, positive, and numeric; malformed, missing, or non-positive account identity returns `INVALID_ARGUMENT` before Entity Management or Social calls. It then projects the flat request to Social & Groups as `tenant_id`, that validated account identity as `sender_id`, mapped communication `type`, normalized text as `content`, the resolved recipient when applicable, and `effect_id`; it never falls back to `character_id` for sender authority. It does not forward `session_id`, room context, target kind/name, or legacy `session_attestation` unchanged. Game Logic owns validating the incoming request fields against the target context, but focused tenant/session/character/target mismatch and projection proof remains an implementation gap. Until that target context is propagated, the live request remains the flat field set documented under [Player execution context](#player-execution-context), including legacy `session_attestation`; those request fields are data to validate against the target context, never caller authority. Account messaging, ordinary group/channel communication, browser social actions, and ordinary account/social mail are Social-owned classes and may use an authenticated in-game adapter without becoming Game Logic actions or exposing private content to tenant-authored scripts. Deliberately world-specific mail is a gameplay communication class under [ADR 0147](../../decisions/adr-0147-explicit-communication-classes-and-owner-delivery.md); [ADR 0148](../../decisions/adr-0148-social-relationship-authority-and-entity-owned-value.md) remains the value and attachment authority. See active ADR 0147, mapped from reviewed archive record `archive-ADR-0134`. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 8ca2757ded..a6e08805a0 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -145,6 +145,12 @@ Entry format: - Observation: The global-ID update rewrote a retained row's tenant before returning it under the supplied tenant; tenant-filtered readback did not protect the original row. The native counterexample changed the complete row and `xmin`, while the restored exact tenant predicate preserves both owner rows and their versions. - Expected pattern: Test controlled pre-phase rows as well as later guarded owners. Keep the create-only ID refusal before mapper/repository access, and separate this owner-local SQL proof from authenticated creator or hosted-content readiness. +- `2026-10-16`: Check existing successor repairs before reworking a failed fixture. + - Context: While fixing the three #3251 publication transaction failures, two focused local gates failed before the worker noticed that the already-reconciled #2967 tree contained the complete selected-full schema-4 fixture repair. + - Observation: The first attempts corrected stale collector stubs but missed the dependent fixture profile. + - Expected pattern: Compare the bounded failing test and its called helpers against known receiving successors before changing or rerunning it; reuse the complete canonical repair without removing assertions. + - Outcome: The exact four-path backport at `4265a81f008d0dbd343cd9adf6413bd3ac5c8904` then passed 66 unit and 10 native cases. The failed attempts retain their original outcomes; this lesson does not establish a general infrastructure cause. + - `2026-10-16`: Derive focused Gradle selectors from declared Java packages - Context: a Gameplay capture proof supplied `integration.net...` as the selector, and Gradle executed no tests before failing discovery. - Observation: `integration` came from the categorized source root, while the class declared `net...`; a categorized source root is not necessarily part of the Java package, and a zero-test discovery failure establishes no test proof. @@ -195,6 +201,17 @@ Entry format: - Observation: It reported the extra check; no runtime tests or source edits resulted from it. The handoff also said no validation ran, which obscured the distinction. - Expected pattern: Treat standalone whitespace checks as validation under the closed allowance. Report the actual check and its outcome, and wait for the orchestrator’s named gate. Main gave that bounded correction and selected receiving proof separately; the extra check earns no test credit. +- `2026-10-18`: Follow up the PostgreSQL endpoint refusal with one scoped reproduction + - Context: the new Automation Flyway test-time refusal met the reconsideration trigger in the `2026-10-13` PostgreSQL endpoint-diagnosis observation. + - Observation: one focused five-store reproduction passed with zero failures, errors or skips and no endpoint refusal. All five exact containers were observed running with host-port bindings and absent after the Gradle child ended. Six inspect errors and 20 unparsed records arose only after the case completed during sequential teardown, so continuous ownership through cleanup is not established. + - Expected pattern: retain the original failed test evidence and capture only exact run-owned container states and ports before teardown when a new refusal justifies focused reproduction; keep a successful reproduction distinct from an explained cause. + - Outcome: the preceding Automation Flyway refusal remains failed evidence with unknown cause; the passing reproduction does not explain it. No speculative host or readiness change is selected. + - Reconsideration trigger: a later physical test-time endpoint refusal, or separately retained evidence that identifies the refused endpoint's failure mechanism. + +- `2026-10-18`: Verify LOC report identity after a PR fast-forward + - Context: `cloc-report.py pr 3248` ran immediately after the existing branch advanced from `6c3eed5d651b` to `eb40332cdb9f`. + - Observation: GitHub still returned the preceding PR head/base payload, so the canonical helper completed successfully with LOC metadata for the old candidate. The worker caught the mismatch before editing the body and regenerated after payload convergence; no stale report was published. The tool-level consistency guard remains an improvement reported to Overseer. + - Expected pattern: compare generated head/base metadata with verified current remote refs before publication; a mismatch must refresh or fail closed. A successful LOC command alone does not prove current candidate attribution. - 2026-10-18: In the CI maintenance PR #3264 Hosted retry, an ad hoc multiline shell read a snapshot file before its producer finished; the JSON check failed but the following provider POST still executed because that shell did not enable errexit. The prior and completed fresh snapshots both showed no active Hosted request, so no conflict was observed. Keep a dependent external mutation in a separate tool call after checking producer completion and validated output; use explicit `set -euo pipefail` for dependent shell batches. - 2026-10-18: CodeRabbit full review 5560170943 for PR #3264 emitted a complete 1/1 publication with one outside-diff Major but no bounded actionable-comment count. The existing manual adoption correctly refused automatic attribution with `Hosted publication has no unique bounded actionable-comment count`. Exact trigger 6241278398, reviewed head `187ab53426caf78cd6a01b61e092b800186aaec2`, provider result and accepted obligation were retained in the CI validation throughput controller job history without invented Hosted credit; no controller adapter change was made in this CI patch. Reconsider format support only in a separately scoped controller maintenance task. @@ -242,6 +259,12 @@ Entry format: - Expected pattern: Preserve the immutable capture and original attempt identity, report the recording gap, and use an explicitly bounded canonical recovery before adjudication and finalization. Do not rerun a completed review, invent credit, or use an unrelated schema migration to repair its record. - Status and reconsideration: Overseer owns bounded recovery in #3271; no live recovery or migration is authorized yet. The exact persistence cause remains unconfirmed. Revisit after that maintenance change is qualified and promoted and the original capture is recovered through its exact native command. +- `2026-10-15`: Normalize nested fixture payloads before computing a digest golden + - Context: Selected-full digest fixture R41/R42 produced different fixed-golden values from otherwise unchanged source. + - Observation: The fixture serialized `Map.of` payloads into strings inside a canonical binding; outer canonicalization preserves string contents and therefore does not normalize the inner map order. + - Expected pattern: Restored explicit RFC 8785 normalization of each fixture payload before binding creation. Updating a golden from one failing run alone did not establish a stable vector; retain equality/mutation checks and verify the normalized vector before claiming deterministic proof. + - Outcome: No production digest or retained bytes were changed. R44 and the fresh R45 JVM agree on the normalized vector; all 686 GDS unit cases pass in R45. + - `2026-10-19`: Independent maintenance temporarily becomes the product queue's parent - Context: Controller recovery maintenance PR #3271 was inserted before the existing product front to obtain the next admissible shared review slot. - Observation: the current controller queue is strictly linear and has no independent maintenance root. Inserting an open maintenance PR before the product front changes the product front's effective parent even though the patches are independent, creating an integration fence until maintenance merges. @@ -271,3 +294,23 @@ Entry format: - `2026-10-23`: Isolate uv managed-Python launchers as well as installations - Observation: A temporary docs-lock generator set `UV_PYTHON_INSTALL_DIR` inside its task directory, but uv 0.13.5 also created `~/.local/bin/python3.15`. The exact newly created task-owned symlink was verified and removed; no preexisting launcher was overwritten. - Expected pattern: Set `UV_PYTHON_BIN_DIR` to a task-private path before temporary installation and confirm it with `uv python dir --bin`; this override was verified locally. Alternatively, `uv python install --no-bin` is supported by the installed help. Installation-directory isolation alone does not isolate launchers. + +- `2026-10-23`: Preserve incomplete ORT license-scan evidence after Maven Central 403s + - Context: PR #3251 License Gate run `39934774515`, job `120353147724`, recorded 403 responses for 392 distinct Maven Central URLs during Gradle analysis; the response origin remains unknown. + - Observation: ORT exited with analyzer errors, emitted unknown-dependency rule warnings, and could not create the WebApp report within its 5120 MiB heap. CycloneDX reports were generated, but artifact upload did not run, so the scan supplies no qualified license proof. + - Expected pattern: Keep the required gate fail-closed and establish the 403 response origin before selecting a correction; do not infer a fix from the secondary reporter OOM or unknown-dependency warnings. + - Status: Root informed for recurrence and recovery tracking; no cause or repository correction established. + +- `2026-10-24`: Enforce ORT analyzer completion separately from report generation + - Observation: The pinned ORT CI action accepts `violations`, while both license jobs supplied the unrecognized `policy-violation` value. The action also intentionally tolerates analyzer exit code 2 so evaluation and reporting can continue; a successful report therefore does not establish complete dependency analysis or enforced policy. + - Correction and proof: Use the supported violation gate and explicitly require analyzer exit code 0 in both jobs, retaining partial results and Gradle failure diagnostics. Focused tests execute the actual workflow guards for successful, failed, missing and malformed statuses. This repairs enforcement independently of the earlier Maven Central 403 incident; its response origin remains unknown and local tests do not establish hosted scan success. + +- `2026-10-24`: Preserve uncertain coordination delivery during controller response failures + - Observation: Gameplay's own bound CLI inbox read and native inbox/job reads returned `invalid_response`; the native attempt to notify FireController Worker returned the same error. The message delivery outcome is unknown, so no successful report or handled inbox state is claimed. + - Expected pattern: Retain the original notification key and request for supported recovery, avoid debugging or changing the service, and continue independent local work. Fresh instructions, review capture and official progress recording remain unavailable until the owning connection recovers. + +- `2026-10-24`: Carry the build environment and explicit package metadata into ORT containers + - Observation: The ORT analyzer container did not inherit `CI`, so this project's Node Gradle plugin enabled a download repository that ORT cannot analyze. ORT 97 also disables repository package curations by default, even when it discovers a valid `.ort.yml`. + - Expected pattern: Forward the existing CI environment contract explicitly and enable the documented repository-curation option while retaining global providers. Normalize only exact package/version metadata supported by upstream license text, and record a package-specific choice for an explicitly offered alternative. Custom licenses require their own policy decision; do not relabel them as SPDX aliases or waive unresolved policy errors. + - Proof limit: Workflow wiring, YAML, failure guards and upstream metadata are checked locally. Only actual analyzer/evaluator results can qualify the hosted correction; the earlier Maven Central 403 response origin remains unknown. + - Live-policy correction: The default evaluator rejects package curations inside `.ort.yml` even when the analyzer supports them. Keep exact package metadata in a read-only child mount under the existing global `DefaultDir` provider instead, preserving its other entries and rules; keep the valid OR-license choice in an NPM-scoped repository configuration so Gradle-only scans do not reject an absent package choice. Configuration-schema support alone did not establish policy acceptance, and actual hosted proof remains required. 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 85b2a01644..2f6fabe7de 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 @@ -8,12 +8,50 @@ This is a non-normative implementation tracker for game authoring, publishing, a ### 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. Selected-full Game Design and Game Logic publication composition and five-store proof remain downstream in the existing 3251 closure. 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). +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). At source `f9e3f879d137b9a6fa54085e9c0b797586636a00`, the focused gate passed 1,105 cases across 224 suites (Gradle reported 4m 22s): 915 Common, 184 Common Security, five `EntityRetainedAuthoredActorCoreSourceService` cases, and one physical `AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest` case. There were zero failures, errors or skips. Common and Common Security full checks passed, along with affected style and documentation checks. This qualifies only these recorded scopes; it is not a fresh whole-service Entity or Automation rerun. The shared selected-source digest helper was introduced at `fdcc676597d33a154c92967baf33ad540387ddf8`, after this `f9e3f879d137b9a6fa54085e9c0b797586636a00` source checkpoint; its later current-source executions are attributed below, not to this gate. The earlier independent four-module attempt at `6365c186390587f31c96aa5e442cbbc6cc7f43a0` completed 2,694 invocations but its aggregate failed when the existing `ScriptDefinitionRepositoryIntegrationTest` failed during initialization with a PostgreSQL connection refusal. All other owner unit and native scopes passed, including eleven Entity and eleven Automation selected-source PostgreSQL cases. The cause of that refusal remains unknown. The exact unchanged 12-case `ScriptDefinition` replacement and the unfinished four-module checks subsequently passed; that does not erase the original failed aggregate or establish a passing fresh whole-service Entity and Automation gate. +### Gameplay source catalog and legacy handoff proof + +The existing Game Design gameplay source PostgreSQL owner test now retains a nonempty action, ability, effect, resource and admission-tag catalog beside an ordinary asset in one owner outcome. Exact retry and independent repository reads preserve the original source bytes. A disjoint asset change inherits the gameplay epoch and original binding; explicit ability and action deletion advances the gameplay epoch while preserving the prior snapshot. Additional cases deny legacy effective commands and generic gameplay-rule history before or after the typed snapshot, including an explicitly emptied rule inventory. Generic history under a different private tenant or Version does not contaminate the exact selected source. + +All eleven owning native invocations freshly pass with zero failures, errors or skips. Canonical formatting, Integration Checkstyle and SpotBugs pass; style checks remain up to date against the formatted source. Passive capture identifies one run-owned PostgreSQL container and independently confirms its absence after completion. The donor's earlier absent-command deletion fixture failure and the subsequent boxing-only static failure are retained separately from the passing run. This is controlled current-default storage and handoff-refusal proof; it does not establish Game Logic intake, an authenticated creator or issuer, currentness, publication enablement, a genuine immutable release, activation or a Gameplay handoff. No production, migration or registration changes are included. + +### Publish-attempt revision and terminal retention proof + +The restored publish-attempt native regression reads two independent copies of a pending attempt, advances the winning revision from one to two and refuses the stale writer with the current CAS conflict code. A legal failure transition advances the revision to three; a later terminal rewrite is refused. Both refusals preserve the complete persisted attempt row and PostgreSQL row version. The existing transaction-boundary case separately confirms an actual writable Read Committed owner transaction. + +Both focused native cases freshly pass with zero failures, errors or skips. Canonical formatting, style, Integration Checkstyle and SpotBugs pass; passive capture identifies the one run-owned PostgreSQL container and independently confirms its absence after completion. This proves local repository revision and terminal guards. It does not execute the held publication finalizer or enable legacy digest backfill, public publication, creator or issuer authority, currentness, activation or a genuine Gameplay handoff. Other publication transaction cases retain their preceding attribution; no production, installed migration or registration changes are included. + +### Canonical Version identity storage proof + +The restored Version identity native owner test preserves the original retained Version fields and row version through the V35.1 identity migration and later default migrations, leaves its canonical identity unmapped and refuses a later identity backfill. Fresh Version creation and update retain the exact persisted Game provenance, including a Game retained through V29. Wrong-tenant, missing, null and nil canonical lookups preserve Version and Game row versions; database guards reject identity replacement, mismatched source, nil identity and canonical truncation, while the explicitly unmapped retained Version remains deletable. + +All six native cases freshly pass with zero failures, errors or skips against the canonical PostgreSQL image and owning filesystem migrations. Canonical formatting, style, Integration Checkstyle and SpotBugs pass; passive capture identifies the one run-owned PostgreSQL container and independently confirms its absence after completion. This proves owner-local identity and historical retention mechanics with controlled setup. It does not establish creator or issuer authority, currentness, publication enablement, an immutable production release, activation or a genuine Gameplay handoff. No production, installed migration or registration changes are included. + +### Selected-full owner publication preparation + +The source candidate prepares complete selected-owner publication consumption under the [canonical selected-full profile](../../architecture/microservices/game-design-service/version-control.md#selected-full-publication-profile). It reuses the actual parent World closure producer, adds its full-profile consumer mapping, and composes the selected Game Design digest read/collector with independently retained Entity, Automation and Game Logic receipts. The Game Logic adapter reads the exact retained terminal, selected source and manifest through the existing owner repository and returns both manifest and ability projections; its default Spring composition remains denied. Private selected writer mechanics use the exact canonical selection/request binding and selected gate. Public Game Design fresh/PENDING publication remains denied. Existing Game Design V1020 storage is reused; no Game Design migration is added. + +Entity's new V1011 prepares the freshly founded empty selected source catalogue and its complete explicit family/equipment evidence; Automation's new V1003 prepares empty selected source retention. Both are forward additions over their current combined service/Saga parents. Their command/read transports and owner services remain standalone and unregistered. These are bounded empty-source components, not arbitrary Entity authoring, script publication or runtime rule execution. Inherited Account migration history and numbering are unchanged by this candidate. + +Focused component qualification passes. R45 freshly executes all 686 Game Design unit cases and the five-store PostgreSQL composition with zero failures, errors or skips; GDS static analysis, formatting and documentation checks pass. The composition uses real Game Design, World, Entity, Automation and Game Logic stores, actual empty Entity/Automation source receipts, a retained Game Logic terminal and authenticated participant digest reads. Existing owner services retain an empty asset snapshot and exact candidate; one owner transaction commits the selected v4 bundle, Version and artifact publication states, successful attempt and original operation seal. Independent immutable bundle readback and exact retry preserve stored bytes and row versions. The Java bundle repository now accepts canonical v4/World-4 alongside exact retained v2/World-3, using existing V1020 SQL guards without a migration change. + +R38 freshly passes 178 Common Security units and 23 native PostgreSQL cases: Entity 11, Automation 11 and Game Logic one, with zero skips. Automation 1,206, Common 818, shared-test-support 55, Entity 261 and Game Logic 117 units retain their original R36 passing attribution; their unchanged scopes are up-to-date in R38. Complete retained migration rows/xmin, including Flyway's null-version marker, and source/Saga retention assertions remain preserved. R45 passive capture owns all five run-created PostgreSQL containers without ownership gaps or observer errors; this focused success does not release inherited broader PostgreSQL/Redis infrastructure holds. + +Upstream Account authorization, source/provenance inputs, creator, issuer, environment and PKI remain explicitly controlled where used. Empty asset manifest metadata and the candidate delivery origin are controlled; no object-store write or public delivery is proved. These standalone unregistered owner components do not establish genuine authority, current or continuous protection, runtime activation, actor placement or operational delivery. Historical release bytes retain their original scoped read/retry meaning. All four genuine Gameplay handoffs remain open and broader Unit 1B/corpus stays paused. + +Gameplay receiving revision `46a0fb3731a6368b55d5c69a99b522299e5ac704` freshly passes the existing `SelectedFullOwnerPublicationPostgresIntegrationTest`: one five-store physical case, zero failures, errors or skips. `linkCheck` and `lintMarkdown` also pass in that invocation. The preceding focused attempt failed during the Automation Flyway store at `localhost:59128`; the scoped passive reproduction passed without a refusal and does not establish the earlier cause. It observed all five run-owned containers running with host-port bindings and absent at child completion, but six inspect errors and 20 unparsed records occurred after case completion during sequential teardown, so continuous ownership through cleanup is not claimed. The previously recorded R45 686 Game Design unit and R38 owner-suite attributions were not rerun. Account authorization and source/provenance, creator, issuer, environment, asset metadata and PKI inputs remain controlled; the owner components remain standalone and unregistered, public fresh/PENDING publication remains denied, and this result establishes no genuine authority, activation or Unit 1B release. + +### Selected-full release service refusal proof + +The existing release-bundle service test independently substitutes each of the five participant digest schemas and verifies that the service refuses the mixed vector before saving a release. The current full `4/3/1/6/2` positive, immutable selected retry, source-capture and command validation cases remain intact; historical schema-3 consumer support is not widened. + +The focused release service, release contract, complete-binding and descriptor owner classes freshly pass 72 unit cases with zero failures, errors or skips. Canonical formatting, style, Test Checkstyle and SpotBugs pass. These tests use controlled evidence and mocked owner repositories or services; they do not execute SQL or establish a genuine immutable release, creator or issuer authority, currentness, publication enablement, activation or a Gameplay handoff. + ### Historical membership and upstream source validation proof The existing runtime membership validator test now checks three supported Account source event formats alongside a positive issuer source while retaining the original historical membership bytes. It verifies positive upstream evidence before returning an empty missing-membership result. Freshly resealed membership events cannot lead the current issuer generation, Account generation, issuance fence or historical Account cutoff sequence; equal and earlier valid Account cutoffs retain their original bytes. The added source fixtures use representable initialized counters above JavaScript's exact-integer range, while the existing maximum-counter case remains intact. The current exact tenant-generation and billing-cutoff rules retain their preceding tests and attribution. @@ -78,7 +116,7 @@ All eight focused owner cases freshly pass with zero failures, errors or skips. ### Selected template publication and original launch reads -The prepared source adds owner-local Template configuration genesis, synchronized revision/application, selected source capture and normalized tenant reference-phase owners over the already guarded tables. `SelectedDraftPublicationOwner` retains the exact selection, pending attempt, complete source capture and immutable template/World relation in one caller-owned writable transaction; existing operation bytes are never upgraded and old descriptor or reference provenance is not backfilled. The original StartSession template-association read authenticates Game Session and independently verifies Account’s exact redeemed operation before its read-only snapshot. It accepts only current selector-bound release-v2 evidence for the configured path and refuses older non-selector releases rather than fabricating later bundles. These components are unregistered and add no migration or runtime enabling flag. +The prepared source adds owner-local Template configuration genesis, synchronized revision/application, selected source capture and normalized tenant reference-phase owners over the already guarded tables. `SelectedDraftPublicationOwner` retains the exact selection, pending attempt, complete source capture and immutable template/World relation in one caller-owned writable transaction; existing operation bytes are never upgraded and old descriptor or reference provenance is not backfilled. The original StartSession template-association read authenticates Game Session and independently verifies Account’s exact redeemed operation before its read-only snapshot. Its configured path accepts selector-bearing release-v2 and selected-full release-v4 evidence, with exact release, original operation, terminal content and World selector-evidence checks; retained non-selector releases are refused rather than upgraded. The selected-full v4 path and exact retained Game Logic receipt/source read remain controlled and unregistered, with no public StartSession or production publication enablement. These components add no migration or runtime enabling flag. The same closure prepares the actual Game Design original launch-descriptor and authored actor-core projection, Game Session retention bound to its original Human owner attempt, and the Entity-only World published-spawn requirements read with strict Common transport, described in [the World tracker](./world-runtime-and-movement.md#published-spawn-requirements-read-preparation). Game Session's forward V1013 retains the core against the actual existing launch association; it does not allocate another owner or backfill retained rows. These components remain unregistered. @@ -86,7 +124,7 @@ The latest supported whole-source Game Design gate remains the historical receiv The prior `a35e155da930714ded1c8ff93d097d9ce2df00b6` attempt failed compiling the native fixture and receives no native proof credit. On source `aa3aa977a5f3d13cdc33b99636e8bd7a9ff33f87`, `StartSessionLaunchDescriptorProducer` and `AuthoredInitialActorCoreReadService` use one shared `SelectedGameplayRuleSourceJoin` predicate for operation, selected-binding and canonical-byte equality across the frozen Gameplay capture, selected source snapshot and retained Game Logic receipt, implementing the [canonical selected-source contract](../../architecture/microservices/game-design-service/version-control.md#selected-publication-storage-and-retained-operations). The corrected focused retry freshly passed all seven cases in `SelectedDraftGameLogicReceiptPostgresIntegrationTest`, including equal-byte acceptance and same-binding unequal-byte refusal after current owner capture and immutable receipt readback; the operation remained `PENDING`, with controlled Account and Game Logic inputs. Integration Checkstyle, SpotBugs and Spotless checks also passed. This qualifies the shared production predicate at the owner boundary, not a public StartSession lifecycle journey, runtime registration, current upstream authority or closure of a genuine Gameplay handoff. -This read-stage preparation also carries the strict shared attestation and terminal codecs, read-only World lifecycle support for the [canonical selected-full profile](../../architecture/microservices/game-design-service/version-control.md#selected-full-publication-profile), and a class-only guarded World fixture. The eight prepared code paths comprise the two shared models and their focused proofs, the World lifecycle reader and its unit proof, the guarded native fixture and its class-only build export. These postimages are source-prepared and unqualified; no factory execution or passing fresh writer/readback is claimed. Actual Game Design writer/storage integration and five-store proof remain in the full selected-owner successor. Public fresh/PENDING publication remains default-denied; no registration, activation or genuine creator, issuer, environment, release or continuous-protection authority is granted. All four genuine Gameplay handoffs remain open and broader Unit 1B remains paused. +The read-stage preparation's strict shared attestation and terminal codecs, read-only World lifecycle support for the [canonical selected-full profile](../../architecture/microservices/game-design-service/version-control.md#selected-full-publication-profile), and class-only guarded World fixture are exercised by the R45 five-store owner composition described above. This linked qualification covers the controlled owner composition only: public fresh/PENDING publication remains default-denied, no component registration or activation is enabled, and no genuine creator, issuer, environment, release or continuous-protection authority is established. All four genuine Gameplay handoffs remain open and broader Unit 1B remains paused. At candidate `a9d9f27a4139c2be2cbf9b7c1df4c4a33d6b8bf3`, the follow-on correction proof qualifies 103 focused cases across 11 classes, with zero failures, errors or skips, from fresh scoped executions and verified unchanged final postimages. All 103 cases were not rerun together at this candidate. It covers the selected-template producer and read paths, Template source/reference-phase storage, Game Session authored-core retention, World published-spawn owner read and strict Common mTLS transport. Controller `current-gameplay` update 2155 records the scoped attribution and verification that all four exact run-owned PostgreSQL containers were absent after their runs. This is focused correction evidence, not a fresh whole-service gate or registered packaged-runtime proof. It does not establish genuine upstream authority, production registration, publication, activation or a genuine Gameplay handoff. @@ -270,7 +308,7 @@ The published `888f` GDS foundation slice contains source-operation/outbox stora | `AR-1.2` Procedural, LLM-assisted, and external authoring tools | `partial` | `proven` for bounded procedural generation and the owner-local typed generation mutation algorithm; registered typed generation ingress, LLM-assisted authoring, destructive plans, staging bounds, and large-grid behavior remain unproved. Whole-game package import/export, filesystem/Git interchange, and portable snapshots are outside the current target per [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md), not merely unproved. The [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) typed creator-API/scoped-proposal path is target-only and remains unimplemented/unproved. | [LLM content tools](../../architecture/system-architecture-llm-content-tools.md); [procedural generation](../../architecture/system-architecture-procedural-generation.md); [generation control](../../architecture/microservices/world-management-service/procedural-generation-control.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md); [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) | [GenerationServiceImpl.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImpl.java); [DungeonGenerator.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/DungeonGenerator.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java) | [GenerationServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImplTest.java); [DungeonGeneratorTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/DungeonGeneratorTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md) | Partial: bounded procedural generation and owner-local typed generation mutation tests exist, but registered typed generation ingress, destructive plan protocol, staging bounds, and large-grid proof remain incomplete. Whole-game portability remains non-target under ADR 0125; model-assisted authoring remains target-only under ADR 0126 with no production contract or focused proof. | | `AR-1.3` Script, plugin, mod, and extension packaging | `partial` | `proven` only for signed plugin intake, design-time script-patch publication, and bounded local activation-preflight/control-plane seams; full activation admission and canonical compatibility remain unproved because the dedicated Game Logic ability-schema attestation, tenant runtime readiness, and exact instance pin/epoch gates are not wired. Broader mod/extension packaging, creator tooling, and distribution lifecycle also remain unproved. | [Modding framework](../../architecture/microservices/game-design-service/modding-framework.md); [scripting control-plane API](../../architecture/system-architecture-scripting-control-plane-api.md); [scripting rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md) | [PluginBundleIntakeServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleIntakeServiceImpl.java); [PluginBundleStorageServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleStorageServiceImpl.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [V18 published plugins](../../../services/game-design-service/src/main/resources/db/migration/V18__published_plugin_versions.sql) | [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java); [PluginActivationPreflightServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [AutomationScriptingControlPlaneGrpcServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingControlPlaneGrpcServiceTest.java) | [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: signed plugin and script-patch publication/readiness seams exist, but live compatibility preflight uses Automation's aggregate participant digest instead of the required dedicated Game Logic-owned ability-schema attestation. Canonical ability-schema compatibility, broader mod/extension package formats, creator tooling, distribution lifecycle, complete runtime readiness convergence, and complete target signature-set persistence/exposure remain incomplete. Current live intake selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set. ADR 0111 owns the accepted target provenance and lifecycle boundary. | | `AR-1.4` Game-authored assets, branding, and release manifests | `partial` | `proven` 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.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; current happy-path full-version publication and bundle creation are refused, and private finalization tests substitute a mocked bundle service; this does not prove historical revision/version lineage. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. 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) | [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) | [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. Participant tokens remain synthetic; World emits digest schema 3, and the full-Version gate requires schema 3. 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-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. | | `AR-2.3` Tenant/game overrides, safety caps, validation, and effective configuration | `partial` | `proven` only for tenant/game settings persistence, validation, functional effective resolution/readback, and resolver seams; the current route authorization does not enforce tenant binding: the shared classifier accepts a tenant-scoped privileged role for any tenant and the controller accepts unbound tenant or session selectors, so cross-tenant effective-settings reads are currently possible. Cross-tenant denial proof is tracked separately and remains unproved. Safety caps, presets, complete hot-reload/invalidation, and all scoped consumers also 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); [SharedSettingsAuthorityReader.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedSettingsAuthorityReader.java); [GameDesignSettingsAuthorityClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/GameDesignSettingsAuthorityClient.java); [EffectiveSettingsController.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java); [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); [EffectiveSettingsControllerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerIntegrationTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [platform operations](./platform-operations-and-delivery.md) | Partial: tenant/game persistence, validation, and functional effective readback/resolver seams exist, but route-aware authorization, scoped/global role binding, cross-tenant denial proof, safety caps, presets, complete hot-reload/invalidation, and all scoped consumers remain incomplete under accepted [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md); implementation and proof gaps remain. | @@ -345,7 +383,7 @@ The broader authored-action model is not complete. The locked expansion boundary Asset lifecycle status and proof remain partial: durable `version_asset` mappings and a version-scoped export snapshot have independent readback. Normal export consumes that frozen snapshot and records candidate manifest/artifact digests before object writes. Published exact-byte repair independently reads the candidate and checks it against the exact release bundle before object writes; repair does not create a snapshot or candidate. Candidate origin and snapshot-integrity checks are present, while integrated migration closure and focused physical database/object-store execution remain unproved. Destructive lifecycle operation safety, global publication/purge fencing, restart recovery, and runtime readiness remain unproved. The canonical upload, hosted-gate, version-scoped export, attestation, lifecycle, and purge rules are 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). -Full-version publish attempts remain persisted for historical exact terminal replay, while script-patch publication continues to use the live durable `publish_attempt`/participant-observation framework. Public and registered Temporal ingress deny fresh and PENDING requests before mutation because no production source creates a genuine version-to-Draft association. FAILED replay returns the stored result; SUCCEEDED replay requires exact immutable release readback. Source capture, candidate export, finalization, and sealing remain non-ingress package-private conditional mechanics, not production publication. The candidate path retains its frozen origin and snapshot integrity, and the finalizer requires a captured operation and same-transaction terminal seal. The local owner-proof boundary rejects `POST /assets` before multipart access or persistence and refuses state-changing `CompareAndSetVersionState` before Version mutation; neither establishes Account authority or lifecycle-transition safety. Physical database, object-store, rollback, concurrent retry, committed/absent/ambiguous recovery, and live Temporal-owner execution remain unproved. World emits schema `3`, and the full-Version gate requires schema `3`; current participant observations still use synthetic scope tokens, and same-commit convergence remains incomplete. Full-version publication also lacks Game Logic owner-local manifest/provenance for version rule inputs; see [Game Logic API Contracts](../../architecture/microservices/game-logic-service/api-contracts.md#implementation-status). The canonical digest, candidate, and asset lifecycle contracts 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 current release storage preserves canonical Version identity, an opaque reference, manifest schema, artifact digests, and exact persisted bundle readback; canonical target-commit provenance and a public tenant projection remain absent. `GetPublishedReleaseBundle` is the canonical read surface, while attestation, ordering, and recovery are owned by [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md). +Full-version publish attempts remain persisted for historical exact terminal replay, while script-patch publication continues to use the live durable `publish_attempt`/participant-observation framework. Public and registered Temporal ingress deny fresh and PENDING requests before mutation because no production source creates a genuine version-to-Draft association. FAILED replay returns the stored result; SUCCEEDED replay requires exact immutable release readback. Source capture, candidate export, finalization, and sealing remain non-ingress package-private conditional mechanics, not production publication. The candidate path retains its frozen origin and snapshot integrity, and the finalizer requires a captured operation and same-transaction terminal seal. The local owner-proof boundary rejects `POST /assets` before multipart access or persistence and refuses state-changing `CompareAndSetVersionState` before Version mutation; neither establishes Account authority or lifecycle-transition safety. Physical database, object-store, rollback, concurrent retry, committed/absent/ambiguous recovery, and live Temporal-owner execution remain unproved. The retained full-Version gate and public participant observations still use World schema `3` and synthetic scope tokens; same-commit convergence remains incomplete. The separate controlled selected-full profile supports World schema `4` and its World4 lifecycle evidence, while the controlled Game Logic path can read the exact selected source against its immutable retained receipt. These capabilities do not supply production publication authority or close the remaining Game Logic owner-local manifest/provenance gap for full-version rule inputs; see [Game Logic API Contracts](../../architecture/microservices/game-logic-service/api-contracts.md#implementation-status). The selected-full, digest and provenance target contract is owned by [Version Control](../../architecture/microservices/game-design-service/version-control.md#selected-full-publication-profile); the canonical candidate and asset lifecycle contracts are owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow). The current release storage preserves canonical Version identity, an opaque reference, manifest schema, artifact digests, and exact persisted bundle readback; canonical target-commit provenance and a public tenant projection remain absent. `GetPublishedReleaseBundle` is the canonical read surface, while attestation, ordering, and recovery are owned by [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md). Game Design hosts the durable `publish` Temporal workflow family; its current workflow/readiness boundary and proof gaps are defined by [Temporal workflows](../../architecture/system-architecture-temporal-workflows.md) and [ADR 0115](../../architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md). The current `VersionServiceImpl` emits an empty `affectedScripts` set and has no readiness trigger/workflow for script-patch readiness, `onLoad`, rollout, or supersede. Gameplay-time script execution and tick handoff remain outside Temporal. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 5f732c4deb..2c3656bec0 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,7 +10,11 @@ This is a non-normative implementation tracker for player access and session. Ca This preparation is owned by [AA-1.3](#capability-status), which remains `partial` / `drift-found`. Its production and focused proof anchors are recorded in that row. -Preliminary source reservations remain held until exact explicit abort, including after the creator credential expires; expiry or a lost Game Design response does not establish safe settlement. Exact original recovery and abort remain available after credential expiry, but an abandoned reservation has no Account-owned autonomous recovery path here. Before registering these owners, the selected-recipient finalization and terminal-settlement stage (#3251) must prove Account-owned recovery for abandoned preliminary reservations and exact terminal release for finalized owners. Preserve the complete source fence until sufficient owner evidence exists; do not release it through a guessed timeout. This is an activation blocker, with reconsideration at that lifecycle stage; current source preparation remains unregistered. +Preliminary source reservations remain held until exact explicit abort or the prepared Account-owned expired-preliminary recovery operation commits that same immutable abort. The internal recovery entry accepts a bounded page of at most 128 candidates from its configured namespace, selects only original COMMITTED, REVOKING, or REVOKED issuances past their actual PostgreSQL expiry, and revalidates exact retained scope and issuer evidence under the canonical source-lock then reservation-lock order. Each candidate commits independently, and a candidate failure does not roll back other candidates; returned page counts and cursor do not establish global completion or readiness. Finalized owners are excluded and remain protected until exact authenticated terminal settlement. Lost responses, unknown state or a guessed timeout do not authorize release. The operation has no transport registration, scheduler or invocation policy; those remain activation prerequisites. + +The query's 128-row limit bounds the returned raw candidate page, but does not establish bounded scan, decode or sort work as retained history grows: it decodes namespace from stored scope frames and joins retained issuer expiry data before ordering across the join. No EXPLAIN, scaled benchmark or index-backed cost proof was run, so retained-history operational cost and query-plan qualification remain open. Reconsider that qualification when this currently unregistered recovery operation receives authorized scheduling or production invocation. Account retention and runtime/data architecture own any future design; no SQL, schema, index, retention or invocation-policy change is recorded here. + +The focused recovery preparation passes eight unit cases at `cda9f4b0bb33265edaf3f0b32c348984472b1d14` and the one new physical PostgreSQL expiry/race case at `7ff2e65bc7fd1bd7d97f9a7034dfd65a39f8f381`, with zero failures, errors or skips in those separate scopes. Eight other native authorization/settlement cases passed in the earlier nine-case run, whose aggregate remains failed; this is not a new passing nine-case aggregate. A later saved native Account XML reports all 12 PostgreSQL invocations passing, including the same-expiry keyset case and the two parameterized retained-expired-issuer invocations (`REVOKING` and `REVOKED`). In that saved attempt, the two focused Account unit suites also pass all 13 cases (10 service and 3 repository). These are Account-suite attributions only: the 240.326-second Gradle attempt failed three Game Design mock tests, so no aggregate pass is claimed. Its Account source is tied to published `f9e1758af8fae53d056da9058e78f50dad1e540e` and remained unchanged through the pre-edit `2bfc318d3fd5449f5e72a31de6b0204c80148adb`; that saved proof has its own source attribution. The timeout-adjusted fixture now freshly passes all 12 PostgreSQL invocations, including the expiry/lock race, keyset continuation and both retained-issuer parameters, with zero failures, errors or skips (195.012-second Account suite on 19 October NZDT). Its enclosing 221.616-second attempt failed Game Design compilation, so it establishes no passing aggregate. All three exact logged test containers were independently absent afterward. Affected static and formatting checks pass after the fixture clock and query-alias corrections. The original expiry/race case observes the real database cutoff and actual source-lock blocking: an in-flight finalization cannot commit after original expiry, abandoned preliminary reservations abort once, and an already committed finalization remains pending until exact Entity terminal settlement. Signer, issuer, source and terminal inputs remain controlled fixtures; no genuine authority, autonomous runtime recovery or activation is established. Prior failed selector, fixture and SQL attempts retain their original evidence. R31 freshly passes all eight Account final-authorization, exact Entity/Automation terminal-storage and retained-upgrade cases with zero skips. Account's 1,500 unit cases pass with four existing skips, Common's 811 units pass with zero skips, and World's 593 units retain the unchanged R30 pass. A real Java writer-exclusion omission exposed by R30 is corrected: the shared settlement check now includes the existing pending selected-owner reservation predicate, matching the retained SQL guard. The shared synthetic terminal codec fixture is carried at its first consumer. R35 freshly passes the successor disclosure composition at the actual V1008–V1010 repository frontier, including physical source-writer exclusion until exact reservation abort; its static, formatting and documentation checks pass. The earlier V1007-only source proof retains separate R28 attribution. Full-native PostgreSQL/Redis limits remain; controlled source, terminal and PKI inputs establish no genuine authority. @@ -68,7 +72,7 @@ Focused proof is split by unchanged source attribution: twelve shared validator ### Original StartSession source-protection storage -The bounded V1003 receiving cut, hardened by forward V1004, adds passive Account admission and activation protection storage and immutable terminal-settlement integrity, while preserving every canonical parent migration and original owner evidence. Its existing source-writer hooks retain World participation and other published owner guards. Forward [Account V1007 preliminary selected-owner reservation storage and source-writer hooks](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql) are now received for Entity and Automation participation. Forward V1008–V1010 prepare finalized owner authorization/recovery and exact terminal settlement, with focused owner-storage and upgrade proof; authenticated cross-owner composition, full qualification and registration remain open as recorded in the [selected-recipient intake tracker](#selected-recipient-source-intake-preparation). AA-1.3 stays `partial` / `drift-found`; all genuine Gameplay handoffs remain open and broader Unit 1B remains paused. +The bounded V1003 receiving cut, hardened by forward V1004, adds passive Account admission and activation protection storage and immutable terminal-settlement integrity, while preserving every canonical parent migration and original owner evidence. Its existing source-writer hooks retain World participation and other published owner guards. Forward [Account V1007 preliminary selected-owner reservation storage and source-writer hooks](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql) are now received for Entity and Automation participation. Forward V1008–V1010 prepare finalized owner authorization/recovery and exact terminal settlement, with focused owner-storage and upgrade proof; this receiving stage also prepares bounded recovery for expired abandoned preliminary reservations. Authenticated cross-owner composition, full qualification and registration remain open as recorded in the [selected-recipient intake tracker](#selected-recipient-source-intake-preparation). AA-1.3 stays `partial` / `drift-found`; all genuine Gameplay handoffs remain open and broader Unit 1B remains paused. The pre-review preparation on actual develop `d0b0743c09e15aeeffd52bde4aa0e8fca159c40c` passed all 15 focused Account PostgreSQL cases with zero failures/errors/skips: 13 admission and two activation cases, including the default-location fresh 113-artifact manifest and unchanged actual 112-artifact parent upgrade. jOOQ generation, compilation, formatting, Checkstyle, integration SpotBugs and documentation checks pass. The broader local 236-case Account integration run had two unavailable endpoint fixtures and remains a failed local gate; identical Account/Common/proto/build inputs at published `a1a6d13f0f4953261e1fdd7154f50f83e17be84e` pass the own Account source-CI artifact 11822625688 with 240 integration cases (zero failures, errors or skips) and 1,295 unit cases (zero failures or errors, four existing filesystem skips). Fresh rebuilt images also pass both unchanged legacy LOGIN/PLAY/LOOK transport baselines. These results qualify the bounded protection storage and existing behavior only. Those pre-review results did not exercise the activation acquisition guards. The corrected [admission storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java) and [activation storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java) stipulate upstream data while leaving the protection/source-writer guards enabled; they establish no genuine owner production, authenticated terminal settlement, continuous canonical admission, actor placement or region delivery. Canonical obligations remain in [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md), with local consequences in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#original-startsession-source-protection-storage). diff --git a/dev-tools/tests/test_license_workflow_enforcement.py b/dev-tools/tests/test_license_workflow_enforcement.py new file mode 100644 index 0000000000..22197d8149 --- /dev/null +++ b/dev-tools/tests/test_license_workflow_enforcement.py @@ -0,0 +1,255 @@ +#!/usr/bin/env python3 +"""Contract tests for fail-closed ORT analyzer completion in the license gate.""" + +from __future__ import annotations + +import hashlib +import re +import shlex +import subprocess +import unittest +from pathlib import Path + +import yaml + +ROOT = Path(__file__).resolve().parents[2] +WORKFLOW = ROOT / ".github/workflows/license-scan.yml" +ADVISORY_WORKFLOW = ROOT / ".github/workflows/ort-advisory.yml" +ANALYZER_EXIT_ENV = "ORT_CLI_ANALYZE_EXIT_CODE" +GATLING_LICENSE_REF = "LicenseRef-Gatling-Highcharts-3.16.0" +GATLING_LICENSE_PATH = ROOT / "config/ort/custom-license-texts" / GATLING_LICENSE_REF +GATLING_LICENSE_SHA256 = "cadfc4af543cb6702bbf3aeedbf896c372b923f6ce7bf4d5e79cc40feb3c9681" + + +def workflow_data() -> dict: + return yaml.safe_load(WORKFLOW.read_text(encoding="utf-8")) + + +def step_by_id(job: dict, step_id: str) -> dict: + return next(step for step in job["steps"] if step.get("id") == step_id) + + +def step_by_name(job: dict, name: str) -> dict: + return next(step for step in job["steps"] if step.get("name") == name) + + +class LicenseWorkflowEnforcementTest(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.jobs = workflow_data()["jobs"] + + def test_both_scans_use_the_actions_supported_violation_gate(self) -> None: + for job_name in ("ort-gradle", "ort-npm"): + with self.subTest(job=job_name): + ort_step = step_by_id(self.jobs[job_name], "ort") + self.assertEqual("violations", ort_step["with"]["fail-on"]) + + def test_analyzer_guards_execute_fail_closed_for_both_scans(self) -> None: + cases = (("0", 0), ("2", 1), (None, 1), ("malformed", 1)) + for job_name, guard_id in ( + ("ort-gradle", "gradle_analyzer_guard"), + ("ort-npm", "npm_analyzer_guard"), + ): + guard = step_by_id(self.jobs[job_name], guard_id) + self.assertEqual("bash", guard["shell"]) + script = guard["run"] + self.assertIn(ANALYZER_EXIT_ENV, script) + + for value, expected_exit in cases: + with self.subTest(job=job_name, analyzer_exit=value): + environment = ( + {} + if value is None + else {ANALYZER_EXIT_ENV: value} + ) + result = subprocess.run( + [ + "/bin/bash", + "--noprofile", + "--norc", + "-e", + "-o", + "pipefail", + "-c", + script, + ], + cwd=ROOT, + env=environment, + capture_output=True, + check=False, + text=True, + timeout=5, + ) + self.assertEqual(expected_exit, result.returncode, result.stderr) + + def test_repository_metadata_is_selected_and_applied_in_ci(self) -> None: + gradle_inputs = step_by_id(self.jobs["ort-gradle"], "ort")["with"] + docker_args = shlex.split(gradle_inputs["docker-cli-args"]) + self.assertIn(["-e", "CI=true"], [docker_args[i:i + 2] for i in range(len(docker_args))]) + for job_name in ("ort-gradle", "ort-npm"): + with self.subTest(job=job_name): + inputs = step_by_id(self.jobs[job_name], "ort")["with"] + args = shlex.split(inputs["docker-cli-args"].replace("${{ github.workspace }}", "/workspace/FireMUD")) + mounts = [args[i + 1] for i, arg in enumerate(args[:-1]) if arg == "--mount"] + self.assertIn( + "type=bind,source=/workspace/FireMUD/config/ort/curations," + "target=/home/ort/.ort/config/curations/firemud,readonly", + mounts, + ) + npm_inputs = step_by_id(self.jobs["ort-npm"], "ort")["with"] + self.assertEqual("${{ github.workspace }}/config/ort/npm.ort.yml", npm_inputs["ort-yml-path"]) + self.assertIn( + "--mount type=bind,source=${{ github.workspace }}/config/ort/npm.ort.yml," + "target=${{ github.workspace }}/config/ort/npm.ort.yml,readonly", + npm_inputs["docker-cli-args"], + ) + self.assertEqual( + "${{ github.workspace }}/config/ort/gatling.ort.yml", + gradle_inputs["ort-yml-path"], + ) + self.assertIn( + "--mount type=bind,source=${{ github.workspace }}/config/ort/gatling.ort.yml," + "target=${{ github.workspace }}/config/ort/gatling.ort.yml,readonly", + gradle_inputs["docker-cli-args"], + ) + self.assertFalse((ROOT / ".ort.yml").exists()) + self.assertNotIn("curations", yaml.safe_load((ROOT / "config/ort/npm.ort.yml").read_text())) + gradle_config = yaml.safe_load( + (ROOT / "config/ort/gatling.ort.yml").read_text(encoding="utf-8") + ) + npm_config = yaml.safe_load( + (ROOT / "config/ort/npm.ort.yml").read_text(encoding="utf-8") + ) + self.assertNotIn("license_choices", gradle_config) + self.assertIn("license_choices", npm_config) + filters = yaml.safe_load(step_by_id(self.jobs["changes"], "filter")["with"]["filters"]) + for ecosystem in ("gradle", "npm"): + with self.subTest(ecosystem=ecosystem): + self.assertIn("config/ort/curations/**", filters[ecosystem]) + self.assertIn("config/ort/npm.ort.yml", filters["npm"]) + self.assertNotIn("config/ort/npm.ort.yml", filters["gradle"]) + self.assertIn("config/ort/gatling.ort.yml", filters["gradle"]) + self.assertNotIn("config/ort/gatling.ort.yml", filters["npm"]) + + def test_custom_license_text_is_routed_mounted_and_curated_exactly(self) -> None: + custom_license_mount = ( + "type=bind,source=/workspace/FireMUD/config/ort/custom-license-texts/" + f"{GATLING_LICENSE_REF},target=/home/ort/.ort/config/custom-license-texts/" + f"{GATLING_LICENSE_REF},readonly" + ) + for workflow_path in (WORKFLOW, ADVISORY_WORKFLOW): + workflow = yaml.safe_load(workflow_path.read_text(encoding="utf-8")) + if workflow_path == WORKFLOW: + ort_steps = [step_by_id(workflow["jobs"]["ort-gradle"], "ort")] + else: + ort_steps = [ + step + for job in workflow["jobs"].values() + for step in job.get("steps", []) + if step.get("id") == "ort" + ] + with self.subTest(workflow=workflow_path.name): + self.assertTrue(ort_steps) + for step in ort_steps: + args = shlex.split( + step["with"]["docker-cli-args"].replace( + "${{ github.workspace }}", "/workspace/FireMUD" + ) + ) + mounts = [ + args[index + 1] + for index, arg in enumerate(args[:-1]) + if arg == "--mount" + ] + self.assertIn(custom_license_mount, mounts) + + filters = yaml.safe_load( + step_by_id(self.jobs["changes"], "filter")["with"]["filters"] + ) + self.assertIn("config/ort/custom-license-texts/**", filters["gradle"]) + + curations = yaml.safe_load( + (ROOT / "config/ort/curations/firemud.yml").read_text(encoding="utf-8") + ) + gatling = [ + curation + for curation in curations + if curation["id"] + == "Maven:io.gatling.highcharts:gatling-charts-highcharts:3.16.0" + ] + self.assertEqual(1, len(gatling)) + self.assertEqual( + {"Gatling Highcharts": GATLING_LICENSE_REF}, + gatling[0]["curations"]["declared_license_mapping"], + ) + self.assertEqual( + GATLING_LICENSE_SHA256, + hashlib.sha256(GATLING_LICENSE_PATH.read_bytes()).hexdigest(), + ) + + def test_gatling_resolution_matches_only_the_observed_violation(self) -> None: + observed_message = ( + "The license LicenseRef-Gatling-Highcharts-3.16.0 is currently not " + "covered by policy rules. The license was declared in package " + "'Maven:io.gatling.highcharts:gatling-charts-highcharts:3.16.0'." + ) + rejected_messages = { + "altered package": observed_message.replace( + "Maven:io.gatling.highcharts", "Maven:io.example.highcharts" + ), + "altered version": observed_message.replace( + "gatling-charts-highcharts:3.16.0", + "gatling-charts-highcharts:3.16.1", + ), + "altered license": observed_message.replace( + GATLING_LICENSE_REF, "LicenseRef-Gatling-Highcharts-3.16.1" + ), + "other error": observed_message.replace( + "currently not covered by policy rules", + "is prohibited by policy rules", + ), + "message suffix": observed_message + " Additional failure details.", + } + config_paths = ( + ROOT / "config/ort/gatling.ort.yml", + ROOT / "config/ort/npm.ort.yml", + ) + + for config_path in config_paths: + config = yaml.safe_load(config_path.read_text(encoding="utf-8")) + resolutions = config["resolutions"]["rule_violations"] + with self.subTest(config=config_path.name): + self.assertEqual(1, len(resolutions)) + resolution = resolutions[0] + self.assertEqual("NOT_MODIFIED_EXCEPTION", resolution["reason"]) + pattern = resolution["message"] + self.assertIsNotNone(re.fullmatch(pattern, observed_message, re.DOTALL)) + for case, message in rejected_messages.items(): + with self.subTest(rejected=case): + self.assertIsNone(re.fullmatch(pattern, message, re.DOTALL)) + + def test_guard_failures_retain_results_and_gradle_diagnostics(self) -> None: + gradle = self.jobs["ort-gradle"] + npm = self.jobs["ort-npm"] + + result_step_name = "Upload ORT results, including partial analysis" + gradle_results = step_by_name(gradle, result_step_name) + npm_results = step_by_name(npm, result_step_name) + expected_results_condition = "${{ always() && steps.ort.outcome != 'skipped' }}" + for upload in (gradle_results, npm_results): + with self.subTest(upload=upload["name"]): + self.assertEqual(expected_results_condition, upload["if"]) + self.assertEqual("error", upload["with"]["if-no-files-found"]) + + diagnostic = step_by_id(gradle, "gradle_ort_diagnostic") + diagnostic_upload = step_by_name( + gradle, "Upload Gradle ORT connectivity diagnostics" + ) + for step in (diagnostic, diagnostic_upload): + condition = step["if"] + self.assertIn("steps.ort.outcome == 'failure'", condition) + self.assertIn("steps.gradle_analyzer_guard.outcome == 'failure'", condition) + + +if __name__ == "__main__": + unittest.main() diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java index 00f57bc7ca..c81b8955e9 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java @@ -22,8 +22,11 @@ import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import org.jooq.DSLContext; import org.jooq.Record; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.transaction.support.TransactionSynchronizationManager; /** @@ -31,6 +34,11 @@ * Automation {@code COMMITTED_EMPTY} terminal settlement. */ public final class AccountSelectedOwnerIntakeSourceReservationRepository { + public static final int MAX_EXPIRED_PRELIMINARY_RECOVERY_BATCH_SIZE = 128; + + private static final Logger LOGGER = + LoggerFactory.getLogger(AccountSelectedOwnerIntakeSourceReservationRepository.class); + private static final String RESERVATIONS = "account_selected_owner_intake_source_read_reservations"; private static final String SOURCES = "account_selected_owner_intake_source_read_sources"; @@ -51,6 +59,26 @@ public enum State { ABORTED } + /** Keyset position for continuing one caller-owned expired-reservation sweep. */ + public record RecoveryCursor(long expiresAtEpochSecond, UUID operationId) { + public RecoveryCursor { + DraftAuthorizationFenceBinding.requireUuid(operationId); + } + } + + /** Valid scopes decoded from one raw page, with its continuation based on the last raw row. */ + record ExpiredPreliminarySourceReadPage( + List scopes, + int examinedCount, + RecoveryCursor nextCursor) { + ExpiredPreliminarySourceReadPage { + scopes = List.copyOf(scopes); + if (examinedCount < 0 || scopes.size() > examinedCount) { + throw new IllegalArgumentException("Invalid expired preliminary recovery page"); + } + } + } + /** Historical evidence only. RESERVED does not imply a live source-read permission. */ public record Recovery(SelectedOwnerIntakeSourceReadScope scope, State state) { public Recovery { @@ -209,6 +237,120 @@ Recovery abortSourceRead(SelectedOwnerIntakeSourceReadScope scope) { return new Recovery(scope, State.ABORTED); } + /** Finds one bounded, keyset-paged batch of exact expired reservations for one namespace. */ + ExpiredPreliminarySourceReadPage findExpiredPreliminarySourceReadScopes( + int limit, String namespace, RecoveryCursor after) { + requireTransaction(); + requireRecoveryLimit(limit); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + + String continuation = + after == null + ? "" + : " AND (issuer.expires_at_epoch_second, reservation.operation_id) > (?, ?)"; + Object[] parameters = + after == null + ? new Object[] {namespace, limit} + : new Object[] {namespace, after.expiresAtEpochSecond(), after.operationId(), limit}; + List rows = + dsl.fetch( + "SELECT reservation.*, issuer.expires_at_epoch_second AS recovery_expires_at_epoch_second, " + + "reservation.operation_id AS recovery_operation_id FROM " + + RESERVATIONS + + " reservation JOIN account_control_ui_issuance_operations issuer" + + " ON issuer.operation_id = reservation.issuance_operation_id" + + " CROSS JOIN LATERAL account_publication_authorization_read_frame(" + + "reservation.scope_bytes, 1) schema_part" + + " CROSS JOIN LATERAL account_publication_authorization_read_frame(" + + "reservation.scope_bytes, schema_part.next_position) owner_part" + + " CROSS JOIN LATERAL account_publication_authorization_read_frame(" + + "reservation.scope_bytes, owner_part.next_position) namespace_part" + + " LEFT JOIN " + + AUTHORIZATIONS + + " finalized_reservation ON finalized_reservation.operation_id = reservation.operation_id" + + " LEFT JOIN " + + ABORTS + + " aborted ON aborted.operation_id = reservation.operation_id" + + " WHERE convert_from(namespace_part.frame_value, 'UTF8') = ?" + + " AND issuer.status IN ('COMMITTED', 'REVOKING', 'REVOKED')" + + " AND extract(epoch FROM clock_timestamp()) >= issuer.expires_at_epoch_second" + + " AND finalized_reservation.operation_id IS NULL" + + " AND aborted.operation_id IS NULL" + + continuation + + " ORDER BY issuer.expires_at_epoch_second, reservation.operation_id" + + " LIMIT ?", + parameters); + List scopes = new ArrayList<>(rows.size()); + RecoveryCursor nextCursor = null; + int rowNumber = 0; + for (Record row : rows) { + rowNumber++; + nextCursor = + new RecoveryCursor( + row.get("recovery_expires_at_epoch_second", Long.class), + row.get("recovery_operation_id", UUID.class)); + try { + var scope = + SelectedOwnerIntakeSourceReadScope.fromStored(row.get("scope_bytes", byte[].class)); + if (!namespace.equals(scope.targetNamespace())) { + throw new IllegalArgumentException("Expired reservation belongs to another namespace"); + } + requireReservation(row, scope); + scopes.add(scope); + } catch (IllegalArgumentException | IllegalStateException invalidRow) { + LOGGER.warn( + "Skipped invalid expired preliminary source-read row {}/{} (failureType={})", + rowNumber, + rows.size(), + invalidRow.getClass().getSimpleName()); + } + } + return new ExpiredPreliminarySourceReadPage(scopes, rows.size(), nextCursor); + } + + /** + * Aborts one expired preliminary reservation after taking the canonical source and reservation + * locks. A concurrent finalization or a candidate that is no longer eligible is skipped. + */ + boolean abortExpiredPreliminarySourceRead( + SelectedOwnerIntakeSourceReadScope scope, String namespace) { + requireTransaction(); + Objects.requireNonNull(scope, "scope"); + if (!GrpcPeerIdentity.isValidNamespace(namespace) + || !namespace.equals(scope.targetNamespace())) { + throw new IllegalArgumentException("Exact Account workload namespace required"); + } + requireOwner(scope.owner()); + + lockReservedSources(scope); + Record row = reservation(scope); + requireReservation(row, scope); + if (aborted(scope) || authorization(scope.operationId()) != null) return false; + + UUID issuanceOperationId = row.get("issuance_operation_id", UUID.class); + if (dsl.fetchOne( + "SELECT operation_id FROM account_control_ui_issuance_operations" + + " WHERE operation_id = ? AND status IN ('COMMITTED', 'REVOKING', 'REVOKED')" + + " AND extract(epoch FROM clock_timestamp()) >= expires_at_epoch_second", + issuanceOperationId) + == null) { + return false; + } + + dsl.execute("INSERT INTO " + ABORTS + " (operation_id) VALUES (?)", scope.operationId()); + return true; + } + + private static void requireRecoveryLimit(int limit) { + if (limit <= 0 || limit > MAX_EXPIRED_PRELIMINARY_RECOVERY_BATCH_SIZE) { + throw new IllegalArgumentException( + "Expired preliminary recovery batch must be between 1 and " + + MAX_EXPIRED_PRELIMINARY_RECOVERY_BATCH_SIZE); + } + } + SelectedOwnerIntakeAuthorizationBinding finalizeSourceRead( SelectedOwnerIntakeSourceReadScope scope, SelectedOwnerIntakeSourceContent content, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java index 571ae7e553..9af79b25db 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java @@ -13,6 +13,8 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -20,12 +22,27 @@ /** Unregistered preliminary source-read producer; it grants no owner retention authority. */ public final class AccountSelectedOwnerIntakeSourceReservationService { + private static final Logger LOGGER = + LoggerFactory.getLogger(AccountSelectedOwnerIntakeSourceReservationService.class); + private final AccountControlUiActorService actors; private final DraftAuthorizationFenceRepository fences; private final AccountSelectedOwnerIntakeSourceReservationRepository repository; private final String namespace; private final TransactionTemplate ownerTransaction; + /** Outcome of one bounded recovery page; zero aborts does not mean the sweep is complete. */ + public record RecoveryPage( + int abortedCount, + int examinedCount, + AccountSelectedOwnerIntakeSourceReservationRepository.RecoveryCursor nextCursor) { + public RecoveryPage { + if (abortedCount < 0 || examinedCount < 0 || abortedCount > examinedCount) { + throw new IllegalArgumentException("Invalid expired preliminary recovery result"); + } + } + } + public AccountSelectedOwnerIntakeSourceReservationService( AccountControlUiActorService actors, DraftAuthorizationFenceRepository fences, @@ -137,6 +154,56 @@ public AccountSelectedOwnerIntakeSourceReservationRepository.Recovery abortSourc return abortSourceRead(scope); } + /** + * Performs one bounded Account-internal reconciliation page before any receiver is registered. It + * is not a transport or scheduled job: the caller owns invocation and readiness policy. Each + * candidate is rechecked and, if still eligible, durably aborted in its own independent + * READ_COMMITTED owner transaction. Finalized and concurrently changed candidates are skipped. + * + * @return counts and caller-owned continuation; a zero abort count is not global completion + */ + public RecoveryPage recoverExpiredPreliminarySourceReads( + int maximumCandidates, + AccountSelectedOwnerIntakeSourceReservationRepository.RecoveryCursor after) { + if (maximumCandidates <= 0) { + throw new IllegalArgumentException("Expired preliminary recovery batch must be positive"); + } + requireNoAmbientTransaction(); + int boundedCandidates = + Math.min( + maximumCandidates, + AccountSelectedOwnerIntakeSourceReservationRepository + .MAX_EXPIRED_PRELIMINARY_RECOVERY_BATCH_SIZE); + + var page = + Objects.requireNonNull( + ownerTransaction.execute( + ignored -> + repository.findExpiredPreliminarySourceReadScopes( + boundedCandidates, namespace, after)), + "Expired source-read candidate lookup returned no result"); + int aborted = 0; + int candidateNumber = 0; + for (SelectedOwnerIntakeSourceReadScope scope : page.scopes()) { + candidateNumber++; + try { + if (Objects.requireNonNull( + ownerTransaction.execute( + ignored -> repository.abortExpiredPreliminarySourceRead(scope, namespace)), + "Expired source-read recovery returned no result")) { + aborted++; + } + } catch (RuntimeException candidateFailure) { + LOGGER.warn( + "Skipped failed expired preliminary source-read candidate {}/{} (failureType={})", + candidateNumber, + page.scopes().size(), + candidateFailure.getClass().getSimpleName()); + } + } + return new RecoveryPage(aborted, page.examinedCount(), page.nextCursor()); + } + private Optional findScope( String originalCompactJwt, UUID intakeRequestId, Owner owner, DraftCommitBinding selected) { requireGameDesignPeer(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java index 20920fbed8..72d173c523 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java @@ -8,7 +8,10 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.time.Clock; +import java.time.Duration; +import java.time.Instant; import java.time.OffsetDateTime; +import java.time.ZoneId; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; @@ -21,6 +24,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; import net.firedevops.firemud.accountservice.service.session.AccountSelectedOwnerIntakeSourceReservationRepository.State; @@ -83,6 +87,8 @@ import org.jooq.DSLContext; 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.testcontainers.containers.GenericContainer; import org.testcontainers.containers.Network; import org.testcontainers.containers.PostgreSQLContainer; @@ -309,6 +315,392 @@ void finalizesBothOwnersExactlyAndKeepsTheirFullSourceVectorsPending() throws Ex } } + @Test + void expiredRecoveryUsesDatabaseCutoffAndPreservesFinalizedOwnerUntilExactSettlement() + throws Exception { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary, + UUID.randomUUID(), + Clock.systemUTC(), + null, + Clock.offset(Clock.systemUTC(), Duration.ofSeconds(-270)))) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selectedForSettlement(f.tenant); + settleOriginal(issued, selected); + var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl); + var reservations = + new AccountSelectedOwnerIntakeSourceReservationService( + issued.actors(), f.fences, repository, f.manager, "test"); + var preliminary = + asGameDesign( + () -> + reservations.reserveSourceRead( + issued.compact(), + UUID.randomUUID(), + Owner.AUTOMATION_SCRIPTING, + selected, + issued.environment())); + var finalizingScope = + asGameDesign( + () -> + reservations.reserveSourceRead( + issued.compact(), + UUID.randomUUID(), + Owner.ENTITY_MANAGEMENT, + selected, + issued.environment())); + var alreadyFinalized = + finalizeEntityBinding(issued, reservations, repository, selected, "recovery-committed"); + UUID issuanceOperationId = + f.dsl + .fetchSingle( + "SELECT issuance_operation_id FROM account_selected_owner_intake_source_read_reservations" + + " WHERE operation_id = ?", + preliminary.operationId()) + .get("issuance_operation_id", UUID.class); + + assertThat(issuerExpiryReached(f.dsl, issuanceOperationId)).isFalse(); + assertThat(reservations.recoverExpiredPreliminarySourceReads(128, null).abortedCount()) + .isZero(); + assertThat(f.tx(() -> repository.recoverSourceRead(preliminary).state())) + .isEqualTo(State.RESERVED); + assertThat(sourceReadPending(f.dsl, preliminary.operationId())).isTrue(); + var finalizationContent = content(finalizingScope, "recovery-race-finalized"); + var authorizationInserted = new CountDownLatch(1); + var allowFinalizationCommit = new CountDownLatch(1); + var recoveryStarted = new CountDownLatch(1); + var finalizationBackendPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + var finalizing = + executor.submit( + () -> + asGameDesign( + () -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> { + var binding = + repository.finalizeSourceRead( + finalizingScope, + finalizationContent, + current, + () -> + f.fences.requireSelectedOwnerIntakeAdmission( + current.source().sources(), selected)); + finalizationBackendPid.set( + f.dsl + .fetchSingle("SELECT pg_backend_pid()") + .get(0, Integer.class)); + authorizationInserted.countDown(); + awaitFinalizationCommit(allowFinalizationCommit); + return binding; + }))); + assertThat(authorizationInserted.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(issuerExpiryReached(f.dsl, issuanceOperationId)).isFalse(); + + awaitIssuerExpiry(f.dsl, issuanceOperationId); + var recovering = + executor.submit( + () -> { + recoveryStarted.countDown(); + return reservations + .recoverExpiredPreliminarySourceReads(128, null) + .abortedCount(); + }); + assertThat(recoveryStarted.await(10, TimeUnit.SECONDS)).isTrue(); + awaitRecoverySourceLockWait(f.dsl, finalizationBackendPid.get()); + assertThat(recovering.isDone()).isFalse(); + + allowFinalizationCommit.countDown(); + Throwable finalizationFailure = null; + try { + finalizing.get(10, TimeUnit.SECONDS); + } catch (java.util.concurrent.ExecutionException expected) { + finalizationFailure = expected; + } + assertThat(finalizationFailure).isNotNull(); + Throwable rootCause = finalizationFailure; + while (rootCause.getCause() != null) rootCause = rootCause.getCause(); + assertThat(rootCause.getMessage()) + .contains("Finalized authorization requires exact current committed creator evidence"); + assertThat(recovering.get(10, TimeUnit.SECONDS)).isEqualTo(2); + } finally { + allowFinalizationCommit.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + + assertThat(reservations.recoverExpiredPreliminarySourceReads(128, null).abortedCount()) + .isZero(); + assertThat(f.tx(() -> repository.recoverSourceRead(preliminary).state())) + .isEqualTo(State.ABORTED); + assertThat(f.tx(() -> repository.recoverSourceRead(finalizingScope).state())) + .isEqualTo(State.ABORTED); + assertThat(sourceReadPending(f.dsl, preliminary.operationId())).isFalse(); + assertThat(sourceReadPending(f.dsl, finalizingScope.operationId())).isFalse(); + assertThat( + f.dsl + .fetchSingle( + "SELECT scope_bytes FROM account_selected_owner_intake_source_read_reservations" + + " WHERE operation_id = ?", + preliminary.operationId()) + .get("scope_bytes", byte[].class)) + .isEqualTo(preliminary.canonicalBytes()); + assertThat( + f.dsl + .fetchSingle( + "SELECT count(*) FROM account_selected_owner_intake_source_read_aborts" + + " WHERE operation_id = ?", + preliminary.operationId()) + .get(0, Long.class)) + .isEqualTo(1L); + assertThat( + f.dsl + .fetchSingle( + "SELECT count(*) FROM account_selected_owner_intake_source_read_aborts" + + " WHERE operation_id = ?", + finalizingScope.operationId()) + .get(0, Long.class)) + .isEqualTo(1L); + + var committedScope = alreadyFinalized.content().scope(); + assertThat(f.tx(() -> repository.recoverSourceRead(committedScope).state())) + .isEqualTo(State.FINALIZED); + assertThat(sourceReadPending(f.dsl, alreadyFinalized.operationId())).isTrue(); + assertThat( + f.dsl + .fetchSingle( + "SELECT binding_bytes FROM account_selected_owner_intake_authorizations" + + " WHERE operation_id = ?", + alreadyFinalized.operationId()) + .get("binding_bytes", byte[].class)) + .isEqualTo(alreadyFinalized.canonicalBytes()); + var terminal = entityTerminalEvidence(alreadyFinalized, 9851, 9852); + var settlement = f.tx(() -> repository.settleEntityCommittedEmpty(terminal)); + assertThat( + f.tx( + () -> repository.findSettlement(alreadyFinalized).orElseThrow().canonicalBytes())) + .isEqualTo(settlement.canonicalBytes()); + assertThat(f.tx(() -> repository.settleEntityCommittedEmpty(terminal).canonicalBytes())) + .isEqualTo(settlement.canonicalBytes()); + assertThat(sourceReadPending(f.dsl, alreadyFinalized.operationId())).isFalse(); + } + } + + @Test + void expiredPreliminaryRecoveryContinuesAcrossSameExpiryRowsByKeyset() throws Exception { + var serviceClock = new MutableOffsetClock(Clock.systemUTC(), -270L); + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary, + UUID.randomUUID(), + Clock.systemUTC(), + null, + serviceClock)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selectedForSettlement(f.tenant); + settleOriginal(issued, selected); + var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl); + var reservations = + new AccountSelectedOwnerIntakeSourceReservationService( + issued.actors(), f.fences, repository, f.manager, "test"); + var firstScope = + asGameDesign( + () -> + reservations.reserveSourceRead( + issued.compact(), + UUID.randomUUID(), + Owner.ENTITY_MANAGEMENT, + selected, + issued.environment())); + var secondScope = + asGameDesign( + () -> + reservations.reserveSourceRead( + issued.compact(), + UUID.randomUUID(), + Owner.AUTOMATION_SCRIPTING, + selected, + issued.environment())); + UUID issuanceOperationId = + f.dsl + .fetchSingle( + "SELECT issuance_operation_id FROM account_selected_owner_intake_source_read_reservations" + + " WHERE operation_id = ?", + firstScope.operationId()) + .get("issuance_operation_id", UUID.class); + + awaitIssuerExpiry(f.dsl, issuanceOperationId); + + var firstPage = reservations.recoverExpiredPreliminarySourceReads(1, null); + assertThat(firstPage.examinedCount()).isEqualTo(1); + assertThat(firstPage.abortedCount()).isEqualTo(1); + assertThat(firstPage.nextCursor()).isNotNull(); + assertThat(firstPage.nextCursor().expiresAtEpochSecond()) + .isEqualTo(issuerExpiryEpochSecond(f.dsl, issuanceOperationId)); + + var secondPage = reservations.recoverExpiredPreliminarySourceReads(1, firstPage.nextCursor()); + assertThat(secondPage.examinedCount()).isEqualTo(1); + assertThat(secondPage.abortedCount()).isEqualTo(1); + assertThat(secondPage.nextCursor()).isNotNull(); + assertThat(secondPage.nextCursor().expiresAtEpochSecond()) + .isEqualTo(firstPage.nextCursor().expiresAtEpochSecond()); + assertThat(secondPage.nextCursor().operationId()) + .isNotEqualTo(firstPage.nextCursor().operationId()); + + var emptyPage = reservations.recoverExpiredPreliminarySourceReads(1, secondPage.nextCursor()); + assertThat(emptyPage.examinedCount()).isZero(); + assertThat(emptyPage.abortedCount()).isZero(); + assertThat(emptyPage.nextCursor()).isNull(); + assertThat(f.tx(() -> repository.recoverSourceRead(firstScope).state())) + .isEqualTo(State.ABORTED); + assertThat(f.tx(() -> repository.recoverSourceRead(secondScope).state())) + .isEqualTo(State.ABORTED); + assertThat(sourceReadPending(f.dsl, firstScope.operationId())).isFalse(); + assertThat(sourceReadPending(f.dsl, secondScope.operationId())).isFalse(); + } + } + + @ParameterizedTest + @ValueSource(strings = {"REVOKING", "REVOKED"}) + void expiredPreliminaryRecoveryAcceptsRetainedExpiredIssuersAndKeepsFinalAuthorization( + String issuerStatus) throws Exception { + var serviceClock = new MutableOffsetClock(Clock.systemUTC(), -270L); + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary, + UUID.randomUUID(), + Clock.systemUTC(), + null, + serviceClock)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selectedForSettlement(f.tenant); + settleOriginal(issued, selected); + var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl); + var reservations = + new AccountSelectedOwnerIntakeSourceReservationService( + issued.actors(), f.fences, repository, f.manager, "test"); + var preliminary = + asGameDesign( + () -> + reservations.reserveSourceRead( + issued.compact(), + UUID.randomUUID(), + Owner.AUTOMATION_SCRIPTING, + selected, + issued.environment())); + var finalized = + finalizeEntityBinding(issued, reservations, repository, selected, issuerStatus); + var finalizedScope = finalized.content().scope(); + UUID issuanceOperationId = + f.dsl + .fetchSingle( + "SELECT issuance_operation_id FROM account_selected_owner_intake_source_read_reservations" + + " WHERE operation_id = ?", + preliminary.operationId()) + .get("issuance_operation_id", UUID.class); + + assertThat(issuerExpiryReached(f.dsl, issuanceOperationId)).isFalse(); + awaitIssuerExpiry(f.dsl, issuanceOperationId); + var issuanceRepository = new AccountControlUiIssuanceRepository(f.dsl); + if ("REVOKING".equals(issuerStatus)) { + var original = + f.tx( + () -> + issuanceRepository.findToken( + AccountControlUiIssuanceRepository.hash( + issued.compact().getBytes(StandardCharsets.US_ASCII)))); + assertThat(original).isNotNull(); + var revoking = f.tx(() -> issuanceRepository.beginRecoveryFailure(original)); + assertThat(revoking.status).isEqualTo("REVOKING"); + } else { + serviceClock.advance(Duration.ofSeconds(31)); + assertThatThrownBy(fixture::issueCreator).isInstanceOf(IllegalStateException.class); + } + assertThat( + f.dsl + .fetchSingle( + "SELECT status FROM account_control_ui_issuance_operations WHERE operation_id = ?", + issuanceOperationId) + .get("status", String.class)) + .isEqualTo(issuerStatus); + + assertThat(reservations.recoverExpiredPreliminarySourceReads(128, null).abortedCount()) + .isEqualTo(1); + + assertThat(f.tx(() -> repository.recoverSourceRead(preliminary).state())) + .isEqualTo(State.ABORTED); + assertThat(f.tx(() -> repository.recoverSourceRead(finalizedScope).state())) + .isEqualTo(State.FINALIZED); + assertThat(sourceReadPending(f.dsl, preliminary.operationId())).isFalse(); + assertThat(sourceReadPending(f.dsl, finalizedScope.operationId())).isTrue(); + assertThat( + f.dsl + .fetchSingle( + "SELECT scope_bytes FROM account_selected_owner_intake_source_read_reservations" + + " WHERE operation_id = ?", + preliminary.operationId()) + .get("scope_bytes", byte[].class)) + .isEqualTo(preliminary.canonicalBytes()); + assertThat( + f.dsl + .fetchSingle( + "SELECT binding_bytes FROM account_selected_owner_intake_authorizations" + + " WHERE operation_id = ?", + finalizedScope.operationId()) + .get("binding_bytes", byte[].class)) + .isEqualTo(finalized.canonicalBytes()); + assertThat( + f.dsl + .fetchSingle( + "SELECT count(*) FROM account_selected_owner_intake_source_read_aborts" + + " WHERE operation_id = ?", + preliminary.operationId()) + .get(0, Long.class)) + .isEqualTo(1L); + assertThat( + f.dsl + .fetchSingle( + "SELECT count(*) FROM account_selected_owner_intake_source_read_aborts" + + " WHERE operation_id = ?", + finalizedScope.operationId()) + .get(0, Long.class)) + .isZero(); + + var sourceChange = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), finalized.sources(), new byte[] {2}); + assertThat(f.tx(() -> f.fences.requestSourceChange(sourceChange))).isFalse(); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(sourceChange))).isFalse(); + assertThat(reservations.recoverExpiredPreliminarySourceReads(128, null).abortedCount()) + .isZero(); + } + } + @Test void commitsExactAutomationEmptySettlementAndReleasesOnlyThatOperation() throws Exception { try (var fixture = @@ -2218,6 +2610,99 @@ private static void awaitLatch(CountDownLatch latch) { } } + private static boolean sourceReadPending(DSLContext dsl, UUID operationId) { + return dsl.fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", operationId) + .get(0, Boolean.class); + } + + private static final class MutableOffsetClock extends Clock { + private final Clock base; + private final AtomicLong offsetSeconds; + + MutableOffsetClock(Clock base, long offsetSeconds) { + this.base = base; + this.offsetSeconds = new AtomicLong(offsetSeconds); + } + + @Override + public ZoneId getZone() { + return base.getZone(); + } + + @Override + public Clock withZone(ZoneId zone) { + return new MutableOffsetClock(base.withZone(zone), offsetSeconds.get()); + } + + @Override + public Instant instant() { + return base.instant().plusSeconds(offsetSeconds.get()); + } + + void advance(Duration duration) { + offsetSeconds.addAndGet(duration.getSeconds()); + } + } + + private static boolean issuerExpiryReached(DSLContext dsl, UUID issuanceOperationId) { + return dsl.fetchSingle( + "SELECT extract(epoch FROM clock_timestamp()) >= expires_at_epoch_second" + + " FROM account_control_ui_issuance_operations WHERE operation_id = ?", + issuanceOperationId) + .get(0, Boolean.class); + } + + private static long issuerExpiryEpochSecond(DSLContext dsl, UUID issuanceOperationId) { + return dsl.fetchSingle( + "SELECT expires_at_epoch_second FROM account_control_ui_issuance_operations " + + "WHERE operation_id = ?", + issuanceOperationId) + .get("expires_at_epoch_second", Long.class); + } + + private static void awaitIssuerExpiry(DSLContext dsl, UUID issuanceOperationId) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(45); + do { + if (issuerExpiryReached(dsl, issuanceOperationId)) return; + Thread.sleep(10); + } while (System.nanoTime() < deadline); + throw new AssertionError("Original Account issuance did not reach its immutable DB expiry"); + } + + private static void awaitRecoverySourceLockWait(DSLContext dsl, int finalizationBackendPid) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + do { + if (Boolean.TRUE.equals( + dsl.fetchSingle( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity" + + " WHERE pid <> pg_backend_pid() AND datname = current_database()" + + " AND wait_event_type = 'Lock'" + + " AND ? = ANY(pg_blocking_pids(pid))" + + " AND query LIKE '%account_draft_authorization_source_locks%'" + + " AND query LIKE '%FOR UPDATE%')", + finalizationBackendPid) + .get(0, Boolean.class))) { + return; + } + Thread.sleep(10); + } while (System.nanoTime() < deadline); + throw new AssertionError("Expired recovery did not wait on finalization-held source locks"); + } + + private static void awaitFinalizationCommit(CountDownLatch latch) { + try { + if (!latch.await(90, TimeUnit.SECONDS)) { + throw new IllegalStateException("Finalization commit was not released"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted finalization lock race", interrupted); + } + } + private static void awaitSourceLockWait(DSLContext dsl, int writerBackendPid) throws InterruptedException { long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepositoryTest.java index 0e8c71be86..fa65c303a6 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepositoryTest.java @@ -1,14 +1,30 @@ package net.firedevops.firemud.accountservice.service.session; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; 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 org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** Synthetic transaction-bound repository boundary tests; no PostgreSQL proof is claimed. */ class AccountSelectedOwnerIntakeSourceReservationRepositoryTest { + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + @Test void everyReservationRecoveryAbortAndCurrentnessReadRequiresAnOwnerTransaction() { var dsl = mock(DSLContext.class); @@ -51,4 +67,56 @@ void everyReservationRecoveryAbortAndCurrentnessReadRequiresAnOwnerTransaction() verifyNoInteractions(dsl); } + + @Test + @SuppressWarnings({"rawtypes", "unchecked"}) + void expiredRecoveryAttemptsInvalidRowsAndAdvancesCursorPastThem() { + var dsl = mock(DSLContext.class); + var first = mock(Record.class); + var later = mock(Record.class); + when(first.get("scope_bytes", byte[].class)).thenReturn(new byte[0]); + when(later.get("scope_bytes", byte[].class)) + .thenThrow(new IllegalStateException("synthetic row failure")); + when(first.get("recovery_expires_at_epoch_second", Long.class)).thenReturn(10L); + when(later.get("recovery_expires_at_epoch_second", Long.class)).thenReturn(20L); + when(first.get("recovery_operation_id", java.util.UUID.class)) + .thenReturn(java.util.UUID.fromString("11111111-1111-4111-8111-111111111111")); + when(later.get("recovery_operation_id", java.util.UUID.class)) + .thenReturn(java.util.UUID.fromString("22222222-2222-4222-8222-222222222222")); + Result rows = mock(Result.class); + when(rows.size()).thenReturn(2); + when(rows.iterator()).thenReturn(List.of(first, later).iterator()); + when(dsl.fetch(anyString(), any(Object[].class))).thenReturn(rows); + TransactionSynchronizationManager.setActualTransactionActive(true); + + var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(dsl); + + var page = repository.findExpiredPreliminarySourceReadScopes(2, "test", null); + + assertThat(page.scopes()).isEmpty(); + assertThat(page.examinedCount()).isEqualTo(2); + assertThat(page.nextCursor()) + .isEqualTo( + new AccountSelectedOwnerIntakeSourceReservationRepository.RecoveryCursor( + 20L, java.util.UUID.fromString("22222222-2222-4222-8222-222222222222"))); + + verify(first).get("scope_bytes", byte[].class); + verify(later).get("scope_bytes", byte[].class); + } + + @Test + void expiredRecoveryPropagatesLookupFailuresForTheWholeOwnerTransaction() { + var dsl = mock(DSLContext.class); + when(dsl.fetch(anyString(), any(Object[].class))) + .thenThrow( + new DataAccessException("synthetic lookup failure") { + private static final long serialVersionUID = 1L; + }); + TransactionSynchronizationManager.setActualTransactionActive(true); + + var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(dsl); + + assertThatThrownBy(() -> repository.findExpiredPreliminarySourceReadScopes(2, "test", null)) + .isInstanceOf(DataAccessException.class); + } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java index 105b642c97..44b476c82c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java @@ -7,6 +7,7 @@ import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.inOrder; 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; @@ -284,6 +285,201 @@ void originalCreatorRecoveryUsesAnIndependentReadCommittedTransaction() { verify(repository).recoverSourceRead(scope); } + @Test + void expiredPreliminaryRecoveryBoundsWorkAndUsesOneOwnerTransactionPerCandidate() { + var selected = selected(); + var first = + new SelectedOwnerIntakeSourceReadScope( + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, + "test", + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + selected.requestId(), + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + selected); + var second = + new SelectedOwnerIntakeSourceReadScope( + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, + "test", + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + selected.requestId(), + UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"), + selected); + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenReturn( + new SimpleTransactionStatus(), + new SimpleTransactionStatus(), + new SimpleTransactionStatus()); + when(repository.findExpiredPreliminarySourceReadScopes(128, "test", null)) + .thenReturn( + new AccountSelectedOwnerIntakeSourceReservationRepository + .ExpiredPreliminarySourceReadPage( + List.of(first, second), + 2, + new AccountSelectedOwnerIntakeSourceReservationRepository.RecoveryCursor( + 10L, second.operationId()))); + when(repository.abortExpiredPreliminarySourceRead(first, "test")).thenReturn(true); + when(repository.abortExpiredPreliminarySourceRead(second, "test")).thenReturn(false); + + var result = service.recoverExpiredPreliminarySourceReads(129, null); + assertThat(result.abortedCount()).isEqualTo(1); + assertThat(result.examinedCount()).isEqualTo(2); + assertThat(result.nextCursor()) + .isEqualTo( + new AccountSelectedOwnerIntakeSourceReservationRepository.RecoveryCursor( + 10L, second.operationId())); + + var definitions = org.mockito.ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactions, org.mockito.Mockito.times(3)).getTransaction(definitions.capture()); + assertThat(definitions.getAllValues()) + .allSatisfy( + definition -> { + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + }); + verify(repository).findExpiredPreliminarySourceReadScopes(128, "test", null); + verify(repository).abortExpiredPreliminarySourceRead(first, "test"); + verify(repository).abortExpiredPreliminarySourceRead(second, "test"); + verifyNoInteractions(actors, fences); + } + + @Test + void expiredPreliminaryRecoveryCarriesCursorAcrossSkippedAndSuccessfulPages() { + var selected = selected(); + var later = recoveryScope(selected, "22222222-2222-4222-8222-222222222222"); + var firstCursor = + new AccountSelectedOwnerIntakeSourceReservationRepository.RecoveryCursor( + -17L, UUID.fromString("11111111-1111-4111-8111-111111111111")); + var secondCursor = + new AccountSelectedOwnerIntakeSourceReservationRepository.RecoveryCursor( + -17L, UUID.fromString("33333333-3333-4333-8333-333333333333")); + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenReturn( + new SimpleTransactionStatus(), + new SimpleTransactionStatus(), + new SimpleTransactionStatus()); + when(repository.findExpiredPreliminarySourceReadScopes(1, "test", null)) + .thenReturn( + new AccountSelectedOwnerIntakeSourceReservationRepository + .ExpiredPreliminarySourceReadPage(List.of(), 1, firstCursor)); + when(repository.findExpiredPreliminarySourceReadScopes(1, "test", firstCursor)) + .thenReturn( + new AccountSelectedOwnerIntakeSourceReservationRepository + .ExpiredPreliminarySourceReadPage(List.of(later), 1, secondCursor)); + when(repository.abortExpiredPreliminarySourceRead(later, "test")).thenReturn(true); + + var firstPage = service.recoverExpiredPreliminarySourceReads(1, null); + assertThat(firstPage.abortedCount()).isZero(); + assertThat(firstPage.examinedCount()).isEqualTo(1); + assertThat(firstPage.nextCursor()).isEqualTo(firstCursor); + + var secondPage = service.recoverExpiredPreliminarySourceReads(1, firstPage.nextCursor()); + assertThat(secondPage.abortedCount()).isEqualTo(1); + assertThat(secondPage.examinedCount()).isEqualTo(1); + assertThat(secondPage.nextCursor()).isEqualTo(secondCursor); + + verify(repository).findExpiredPreliminarySourceReadScopes(1, "test", null); + verify(repository).findExpiredPreliminarySourceReadScopes(1, "test", firstCursor); + verify(repository).abortExpiredPreliminarySourceRead(later, "test"); + var definitions = org.mockito.ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactions, times(3)).getTransaction(definitions.capture()); + assertThat(definitions.getAllValues()) + .allSatisfy( + definition -> { + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + }); + } + + @Test + void expiredPreliminaryRecoveryContinuesAfterFirstAndLaterCandidateFailures() { + var selected = selected(); + var first = recoveryScope(selected, "11111111-1111-4111-8111-111111111111"); + var successful = recoveryScope(selected, "22222222-2222-4222-8222-222222222222"); + var later = recoveryScope(selected, "33333333-3333-4333-8333-333333333333"); + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenReturn( + new SimpleTransactionStatus(), + new SimpleTransactionStatus(), + new SimpleTransactionStatus(), + new SimpleTransactionStatus()); + when(repository.findExpiredPreliminarySourceReadScopes(3, "test", null)) + .thenReturn( + new AccountSelectedOwnerIntakeSourceReservationRepository + .ExpiredPreliminarySourceReadPage( + List.of(first, successful, later), + 3, + new AccountSelectedOwnerIntakeSourceReservationRepository.RecoveryCursor( + 10L, later.operationId()))); + when(repository.abortExpiredPreliminarySourceRead(first, "test")) + .thenThrow(new IllegalStateException("synthetic source payload must not be logged")); + when(repository.abortExpiredPreliminarySourceRead(successful, "test")).thenReturn(true); + when(repository.abortExpiredPreliminarySourceRead(later, "test")) + .thenThrow(new IllegalArgumentException("synthetic credential must not be logged")); + + assertThat(service.recoverExpiredPreliminarySourceReads(3, null).abortedCount()).isEqualTo(1); + + verify(repository).abortExpiredPreliminarySourceRead(first, "test"); + verify(repository).abortExpiredPreliminarySourceRead(successful, "test"); + verify(repository).abortExpiredPreliminarySourceRead(later, "test"); + verify(transactions, times(4)).getTransaction(any(TransactionDefinition.class)); + } + + @Test + void expiredPreliminaryRecoveryContinuesAndReturnsZeroWhenEveryCandidateFails() { + var selected = selected(); + var first = recoveryScope(selected, "44444444-4444-4444-8444-444444444444"); + var second = recoveryScope(selected, "55555555-5555-4555-8555-555555555555"); + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenReturn( + new SimpleTransactionStatus(), + new SimpleTransactionStatus(), + new SimpleTransactionStatus()); + when(repository.findExpiredPreliminarySourceReadScopes(2, "test", null)) + .thenReturn( + new AccountSelectedOwnerIntakeSourceReservationRepository + .ExpiredPreliminarySourceReadPage( + List.of(first, second), + 2, + new AccountSelectedOwnerIntakeSourceReservationRepository.RecoveryCursor( + 10L, second.operationId()))); + when(repository.abortExpiredPreliminarySourceRead(first, "test")) + .thenThrow(new IllegalStateException("synthetic failure")); + when(repository.abortExpiredPreliminarySourceRead(second, "test")) + .thenThrow(new IllegalStateException("synthetic failure")); + + assertThat(service.recoverExpiredPreliminarySourceReads(2, null).abortedCount()).isZero(); + + verify(repository).abortExpiredPreliminarySourceRead(first, "test"); + verify(repository).abortExpiredPreliminarySourceRead(second, "test"); + verify(transactions, times(3)).getTransaction(any(TransactionDefinition.class)); + } + + @Test + void expiredPreliminaryRecoveryRejectsNonpositivePagesBeforeOpeningTransactions() { + assertThatThrownBy(() -> service.recoverExpiredPreliminarySourceReads(0, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> service.recoverExpiredPreliminarySourceReads(-1, null)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(actors, fences, repository, transactions); + } + + @Test + void expiredPreliminaryRecoveryRejectsAmbientTransactionsBeforeOwnerAccess() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> service.recoverExpiredPreliminarySourceReads(1, null)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageContaining("independent transaction"); + verifyNoInteractions(actors, fences, repository, transactions); + } + private static AccountControlUiAuthority.Snapshot snapshot( List sources) { var snapshot = mock(AccountControlUiAuthority.Snapshot.class); @@ -294,6 +490,18 @@ private static AccountControlUiAuthority.Snapshot snapshot( return snapshot; } + private static SelectedOwnerIntakeSourceReadScope recoveryScope( + DraftCommitBinding selected, String operationId) { + return new SelectedOwnerIntakeSourceReadScope( + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, + "test", + UUID.fromString(operationId), + UUID.randomUUID(), + selected.requestId(), + UUID.randomUUID(), + selected); + } + private static AccountControlUiIssuanceRepository.Stored stored(UUID actorId, UUID tenantId) { Record row = mock(Record.class); var operation = UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index a9bdc9d9ff..d7f60deb97 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -13,6 +13,7 @@ import java.util.Base64; import java.util.Collection; import java.util.List; +import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.accountservice.authordraft.AccountDraftTerminalReconciliationService; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; @@ -109,11 +110,42 @@ public AccountControlUiOriginalOrderFixture( Clock actorClock, String migrationTarget) throws Exception { + this( + jdbcUrl, + username, + password, + redisHost, + redisPort, + temporary, + gameDesignTenant, + actorClock, + migrationTarget, + Clock.systemUTC()); + } + + /** + * Test-only owner fixture with a separately injectable issuance clock; actor validation remains + * on its independently supplied clock. + */ + public AccountControlUiOriginalOrderFixture( + String jdbcUrl, + String username, + String password, + String redisHost, + int redisPort, + Path temporary, + UUID gameDesignTenant, + Clock actorClock, + String migrationTarget, + Clock serviceClock) + throws Exception { this.temporary = temporary; + Objects.requireNonNull(actorClock, "actorClock"); + Objects.requireNonNull(serviceClock, "serviceClock"); f = new AccountControlUiOwnerSourcesFixture( jdbcUrl, username, password, temporary, false, gameDesignTenant, migrationTarget); - var lifecycle = new AccountControlUiSignerFixture(f, temporary); + var lifecycle = new AccountControlUiSignerFixture(f, temporary, serviceClock); lifecycle.commit(); var originalSigner = f.tx(lifecycle.signer::captureCurrent); assertThat(f.tx(() -> lifecycle.signer.requireOriginal(originalSigner.receipt())).receipt()) @@ -195,11 +227,11 @@ public AccountControlUiOriginalOrderFixture( f.fences, lifecycle.signer, new AccountControlUiResponseCryptography( - new AccountControlUiKeyring(temporary.resolve("custody")), Clock.systemUTC()), + new AccountControlUiKeyring(temporary.resolve("custody")), serviceClock), coordination, actors, f.manager, - Clock.systemUTC(), + serviceClock, 300_000L, AccountControlUiOwnerSourcesFixture.CALLER); } diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java index d296be3853..b0961a0ca1 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java @@ -24,6 +24,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; @@ -113,10 +114,17 @@ final class AccountControlUiSignerFixture { final AccountJwtSignerBootstrapCoordinator coordinator; final AccountJwtSignerMaterializationService materializer; final AccountControlUiSignerOwner signer; + private final Clock clock; AccountControlUiSignerFixture(AccountControlUiOwnerSourcesFixture fixture, Path root) throws Exception { + this(fixture, root, Clock.systemUTC()); + } + + AccountControlUiSignerFixture(AccountControlUiOwnerSourcesFixture fixture, Path root, Clock clock) + throws Exception { f = fixture; + this.clock = Objects.requireNonNull(clock, "clock"); privateRoot = Files.createDirectories(root.resolve("private")); publicRoot = Files.createDirectories(root.resolve("public")); desired = new AccountJwtSignerDesiredStateRepository(f.dsl); @@ -344,7 +352,7 @@ void commit() throws Exception { new AccountJwtReadinessProbeService( readiness, f.transactions, - Clock.systemUTC(), + clock, privateRoot, Path.of("pending.key"), publicRoot, @@ -480,8 +488,8 @@ public void onCompleted() { private record PublicJwk(String json, String jsonWithoutKeyOps, String fingerprint) {} - private static Instant now() { - return Instant.ofEpochSecond(Instant.now().getEpochSecond()); + private Instant now() { + return Instant.ofEpochSecond(clock.instant().getEpochSecond()); } private static TrustFence trust() { diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts index 2487dd676f..e72218dafb 100644 --- a/services/game-design-service/build.gradle.kts +++ b/services/game-design-service/build.gradle.kts @@ -31,11 +31,26 @@ dependencies { implementation(libs.aws.sdk.s3) testCompileOnly(libs.spotbugs.annotations) add("integrationTestCompileOnly", libs.spotbugs.annotations) - add("crossServiceTestImplementation", project(":game-session-service")) + add( + "crossServiceTestImplementation", + project(mapOf("path" to ":game-session-service", "configuration" to "gameSessionClassesProof")) + ) + add( + "crossServiceTestImplementation", + project(mapOf("path" to ":entity-management-service", "configuration" to "entityClassesProof")) + ) + add( + "crossServiceTestImplementation", + project(mapOf("path" to ":automation-scripting-service", "configuration" to "automationClassesProof")) + ) add( "crossServiceTestImplementation", project(mapOf("path" to ":world-management-service", "configuration" to "worldClassesProof")) ) + add( + "crossServiceTestImplementation", + project(mapOf("path" to ":world-management-service", "configuration" to "worldSelectedPublicationProof")) + ) add( "crossServiceTestImplementation", project(mapOf("path" to ":account-service", "configuration" to "accountOriginalOrderProof")) @@ -66,6 +81,10 @@ val gameDesignClassesProof by configurations.creating { // Composed owner proofs load foreign migrations from disk; classes-only artifacts omit them. tasks.named("crossServiceTest") { + inputs.dir(rootProject.layout.projectDirectory.dir("services/entity-management-service/src/main/resources/db/migration")) + .withPropertyName("entityOwnerMigrations") + inputs.dir(rootProject.layout.projectDirectory.dir("services/automation-scripting-service/src/main/resources/db/migration")) + .withPropertyName("automationOwnerMigrations") inputs.dir(rootProject.layout.projectDirectory.dir("services/account-service/src/main/resources/db/migration")) .withPropertyName("accountOwnerMigrations") inputs.dir(rootProject.layout.projectDirectory.dir("services/game-logic-service/src/main/resources/db/migration")) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/GameLogicClient.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/GameLogicClient.java index 534d5011b6..c4346e5a06 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/GameLogicClient.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/GameLogicClient.java @@ -1,28 +1,49 @@ package net.firedevops.firemud.gamedesign.client; +import io.grpc.ManagedChannel; import jakarta.annotation.PostConstruct; import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.Objects; +import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadGrpcCodec; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt; import net.firedevops.firemud.gamelogic.v1.GameLogicServiceGrpc; -import net.firedevops.firemud.gamelogic.v1.GetDraftDesignDigestRequest; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; +import org.springframework.transaction.support.TransactionSynchronizationManager; @Component public class GameLogicClient extends AbstractReloadingBlockingGrpcClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final CommonGrpcClientProperties tlsProps; + + @Value("${firemud.grpc.workload-namespace:}") + private String workloadNamespace; + public GameLogicClient( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProps, GrpcChannelFactory channelFactory, BlockingGrpcStubCustomizer stubCustomizer) { super(endpoints, tlsProps, channelFactory, stubCustomizer, GameLogicClient.class); + this.tlsProps = tlsProps.copy(); } @PostConstruct @@ -41,57 +62,156 @@ protected String defaultTarget() { } @Override - protected GameLogicServiceGrpc.GameLogicServiceBlockingStub buildStub( - io.grpc.ManagedChannel channel) { + protected GameLogicServiceGrpc.GameLogicServiceBlockingStub buildStub(ManagedChannel channel) { return applyStubCustomizer( GameLogicServiceGrpc.newBlockingStub(channel).withCompression("gzip")); } + /** + * Legacy publication read cannot prove the selected Account authorization and is deliberately + * closed. Full-version publication must use the immutable-receipt overload below. + */ public PublishParticipantDigestDto getDraftDesignDigestForVersion( PublicationDigestRequestBinding binding) { + Objects.requireNonNull(binding, "binding"); + String versionId = requireFullVersionId(binding); + return failure( + versionId, + "SELECTED_GAME_LOGIC_RECEIPT_REQUIRED", + "exact retained Game Logic receipt is required for a full-version publication read"); + } + + /** Reads the retained full-version digest selected by the original Account receipt. */ + public PublishParticipantDigestDto getDraftDesignDigestForVersion( + PublicationDigestRequestBinding binding, SelectedDraftGameLogicReceipt receipt) { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(receipt, "receipt"); + String versionId = requireFullVersionId(binding); + requireOutsideSql(); + if (!receipt.selection().intent().publishRequestId().equals(binding.publishRequestId()) + || !receipt.workflowIdentity().equals(binding.derivedWorkflowIdentity())) { + throw new IllegalArgumentException( + "publication request differs from immutable selected Game Logic receipt"); + } + + // The receipt constructor enforces the Account-finalized RETAINED terminal. Use its exact + // original authorization, never IDs or bytes from an ambient/latest source lookup. + GameLogicPublicationSourceReadBinding expectedBinding = + new GameLogicPublicationSourceReadBinding(binding, receipt.authorization()); + var request = GameLogicPublicationSourceReadGrpcCodec.toRequest(expectedBinding); + GameLogicServiceGrpc.GameLogicServiceBlockingStub publicationReadStub; + try { + publicationReadStub = requirePublicationReadStub(); + } catch (IllegalStateException unavailableConfiguration) { + return failure( + versionId, + "PARTICIPANT_UNAVAILABLE", + "Game Logic publication source read is not configured"); + } var response = - stub() - .getDraftDesignDigest( - GetDraftDesignDigestRequest.newBuilder() - .setTenantId(binding.tenantId()) - .setVersionId(requireFullVersionId(binding)) - .setPublishRequestId(binding.publishRequestId()) - .setDerivedWorkflowIdentity(binding.derivedWorkflowIdentity()) - .setRequestDigest(binding.requestDigest()) - .build()); + publicationReadStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .getDraftDesignDigest(request); if (response.hasError() && !response.getError().getCode().isBlank()) { - return new PublishParticipantDigestDto( - "GAME_LOGIC", - binding.versionId(), - null, - null, - null, - response.getError().getCode(), - response.getError().getMessage()); + return failure(versionId, response.getError().getCode(), response.getError().getMessage()); + } + + GameLogicPublicationSourceReadGrpcCodec.Evidence evidence; + try { + evidence = + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + expectedBinding, response, workloadNamespace); + } catch (IllegalArgumentException invalid) { + return failure(versionId, "RESPONSE_BINDING_MISMATCH", invalid.getMessage()); } - if (!binding.tenantId().equals(response.getTenantId()) - || !response.hasVersionId() - || !binding.versionId().equals(response.getVersionId()) - || !response.getBaseVersionId().isEmpty()) { - return new PublishParticipantDigestDto( - "GAME_LOGIC", - binding.versionId(), - null, - null, - null, - "RESPONSE_BINDING_MISMATCH", - "owner returned tenant or typed full-version scope that does not match request"); + if (!Arrays.equals( + receipt.receipt().terminal().canonicalBytes(), evidence.terminal().canonicalBytes())) { + return failure( + versionId, + "RESPONSE_TERMINAL_MISMATCH", + "owner terminal differs from the immutable Account-finalized receipt"); } + + // The authenticated owner response remains sha256:-prefixed. Release participants carry the + // same aggregate hash as bare hex; keep the separately scoped ability digest unchanged. return new PublishParticipantDigestDto( "GAME_LOGIC", - response.getVersionId(), - response.getAppliedCommitId(), - response.getContentDigest(), - response.getDigestSchemaVersion(), + versionId, + null, + receipt.authorization().source().binding().commitId().toString(), + evidence.manifestDigest().substring("sha256:".length()), + evidence.digestSchemaVersion(), + evidence.abilitySchemaDigest(), null, null); } + private GameLogicServiceGrpc.GameLogicServiceBlockingStub requirePublicationReadStub() { + requireFileBackedMtls(tlsProps); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalStateException( + "Game Logic publication reads require the configured workload namespace"); + } + var current = stub(); + if (current == null) { + throw new IllegalStateException("Game Logic publication client is not initialized"); + } + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-logic-service"; + return current + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withMaxInboundMessageSize(GameLogicPublicationSourceReadGrpcCodec.MAX_WIRE_BYTES); + } + + private static void requireOutsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Game Logic publication source reads require no ambient SQL transaction"); + } + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalStateException( + "Game Logic publication source reads require file-backed workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalStateException( + "Game Logic publication source reads require file-backed TLS certificate, key, and CA"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalStateException( + "Game Logic publication source reads require file-backed TLS certificate, key, and CA"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalStateException( + "Game Logic publication source-read " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalStateException( + "Game Logic publication source-read " + label + " must be an existing readable file"); + } + } + + private static PublishParticipantDigestDto failure( + String versionId, String errorCode, String errorMessage) { + return new PublishParticipantDigestDto( + "GAME_LOGIC", versionId, null, null, null, null, errorCode, errorMessage); + } + private String requireFullVersionId(PublicationDigestRequestBinding binding) { if (binding.scopeKind() != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION) { throw new IllegalArgumentException("full-version binding required"); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcService.java new file mode 100644 index 0000000000..6d5b803a96 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcService.java @@ -0,0 +1,125 @@ +package net.firedevops.firemud.gamedesign.draft; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadEvidence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadGrpcCodec; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.v1.GameDesignSelectedDraftPublicationReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationRequest; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationResponse; +import org.jooq.exception.DataAccessException; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.TransientDataAccessException; + +/** + * Standalone, unregistered immutable selection owner read. Does not inspect mutable Version state + * or establish actor authorization, source holds, World freeze, release, or runtime admission. + */ +public final class GameDesignSelectedDraftPublicationReadGrpcService + extends GameDesignSelectedDraftPublicationReadServiceGrpc + .GameDesignSelectedDraftPublicationReadServiceImplBase { + private final AuthoredDraftPublishSelectionRepository repository; + private final String trustedNamespace; + + public GameDesignSelectedDraftPublicationReadGrpcService( + AuthoredDraftPublishSelectionRepository repository, String trustedNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace required"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void readSelectedDraftPublication( + ReadSelectedDraftPublicationRequest request, + StreamObserver observer) { + try { + requirePeer(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + final AuthoredDraftPublishSelectionReadEvidence.Request decoded; + try { + decoded = AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException malformed) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical selected Draft publication read required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(decoded.targetNamespace())) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Selection namespace differs from peer") + .asRuntimeException()); + return; + } + final ReadSelectedDraftPublicationResponse response; + try { + var intent = decoded.binding().intent(); + var retained = + repository.read( + intent.canonicalTenantId(), intent.canonicalVersionId(), intent.publishRequestId()); + if (retained.isEmpty()) { + throw Status.NOT_FOUND + .withDescription("Exact selected Draft publication unavailable") + .asRuntimeException(); + } + var selection = retained.orElseThrow().selection(); + if (!Arrays.equals(selection.canonicalBytes(), decoded.originalSelection()) + || !selection.digest().equals(decoded.selectionDigest())) { + throw Status.FAILED_PRECONDITION + .withDescription("Retained selection differs from request") + .asRuntimeException(); + } + response = AuthoredDraftPublishSelectionReadGrpcCodec.toSelectedResponse(decoded); + } catch (StatusRuntimeException failure) { + observer.onError( + Status.fromCode(Status.fromThrowable(failure).getCode()) + .withDescription("Selected Draft publication read denied or unavailable") + .asRuntimeException()); + return; + } catch (DataAccessException + | TransientDataAccessException + | DataAccessResourceFailureException unavailable) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Game Design selection storage unavailable") + .asRuntimeException()); + return; + } catch (RuntimeException invalid) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Retained selected Draft publication evidence is invalid") + .asRuntimeException()); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private void requirePeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + } + if (SessionContext.hasAuthenticatedCallerContext() + || (!("spiffe://firemud/ns/" + trustedNamespace + "/sa/account-service").equals(peer.uri()) + && !("spiffe://firemud/ns/" + trustedNamespace + "/sa/world-management-service") + .equals(peer.uri()))) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Account or World Management workload required") + .asRuntimeException(); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java index b8cd545f21..fc8ca116e7 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java @@ -37,12 +37,17 @@ public record PublishedReleaseBundleDto( "Manifest schema and artifact proof must be present together"); } artifactDigests = artifactDigests == null ? null : List.copyOf(artifactDigests); - if ("v2".equals(attestationSchemaVersion) != (worldPublishedStartLocationEvidence != null)) { + boolean selectedRelease = isSelectedAttestationSchema(attestationSchemaVersion); + if (selectedRelease != (worldPublishedStartLocationEvidence != null)) { throw new IllegalArgumentException( - "Selector evidence requires bundle v2 and is mandatory for v2"); + "Selector evidence requires bundle v2 or v4 and is mandatory for both"); } } + public static boolean isSelectedAttestationSchema(String schemaVersion) { + return "v2".equals(schemaVersion) || "v4".equals(schemaVersion); + } + /** Original retained bundle construction shape; cannot construct a selector-bearing v2 bundle. */ public PublishedReleaseBundleDto( Long id, diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigest.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigest.java new file mode 100644 index 0000000000..77d9cc1e30 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigest.java @@ -0,0 +1,129 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; + +/** Schema-2 digest over every exact Game Design source family at one selected Draft commit. */ +public record SelectedDraftControlPlaneDigest( + String tenantId, + String scopeValue, + String appliedCommitId, + String contentDigest, + int digestSchemaVersion) { + public static final int SCHEMA_VERSION = 2; + private static final String DOMAIN = "game-design-selected-draft-control-plane-digest/v2"; + + public SelectedDraftControlPlaneDigest { + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(scopeValue, "scopeValue"); + Objects.requireNonNull(appliedCommitId, "appliedCommitId"); + if (contentDigest == null + || !contentDigest.matches("[0-9a-f]{64}") + || digestSchemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException( + "Canonical schema-2 selected control-plane digest required"); + } + } + + /** Publication request identity is echoed separately and is not part of this content digest. */ + public static SelectedDraftControlPlaneDigest compute( + DraftCommitBinding selectedCommit, GameDesignSourceRepository.SynchronizedSources sources) { + Objects.requireNonNull(selectedCommit, "selectedCommit"); + Objects.requireNonNull(sources, "sources"); + BrandingSourceSnapshot branding = + sources + .branding() + .orElseThrow( + () -> new IllegalStateException("Selected branding source snapshot unavailable")); + TemplateConfigSourceSnapshot templateConfig = + sources + .templateConfig() + .orElseThrow( + () -> + new IllegalStateException( + "Selected template-config source snapshot unavailable")); + List snapshots = + List.of( + new Snapshot( + "COMMAND", sources.command().binding(), sources.command().canonicalBytes()), + new Snapshot( + "REALM_POLICY", sources.policy().binding(), sources.policy().canonicalBytes()), + new Snapshot("ASSET", sources.asset().binding(), sources.asset().canonicalBytes()), + new Snapshot( + "GAMEPLAY_SOURCE", + sources + .gameplayEvidence() + .orElseThrow( + () -> new IllegalStateException("Selected gameplay source unavailable")) + .binding(), + sources + .gameplayEvidence() + .orElseThrow( + () -> new IllegalStateException("Selected gameplay source unavailable")) + .canonicalBytes()), + new Snapshot("BRANDING", branding.binding(), branding.canonicalBytes()), + new Snapshot( + "TEMPLATE_CONFIG", templateConfig.binding(), templateConfig.canonicalBytes())); + + var preimage = new ByteArrayOutputStream(); + frame(preimage, DOMAIN); + frame(preimage, selectedCommit.canonicalBytes()); + for (Snapshot source : snapshots) { + if (!selectedCommit.equals(source.binding())) { + throw new IllegalStateException( + "Every selected Game Design source family must bind the exact Draft commit"); + } + frame(preimage, source.family()); + frame(preimage, source.canonicalBytes()); + } + return new SelectedDraftControlPlaneDigest( + selectedCommit.target().canonicalTenantId().toString(), + Long.toString(selectedCommit.target().gameDesignVersionRowId()), + selectedCommit.commitId().toString(), + sha256(preimage.toByteArray()), + SCHEMA_VERSION); + } + + public DesignControlPlaneDigestDto toDto() { + return new DesignControlPlaneDigestDto( + tenantId, scopeValue, appliedCommitId, contentDigest, digestSchemaVersion); + } + + private static void frame(ByteArrayOutputStream output, String value) { + frame(output, value.getBytes(StandardCharsets.UTF_8)); + } + + private static void frame(ByteArrayOutputStream output, byte[] value) { + output.writeBytes(Integer.toString(value.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(value); + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new AssertionError("SHA-256 is required by the Java platform", impossible); + } + } + + private record Snapshot(String family, DraftCommitBinding binding, byte[] canonicalBytes) { + private Snapshot { + Objects.requireNonNull(family, "family"); + Objects.requireNonNull(binding, "binding"); + canonicalBytes = Objects.requireNonNull(canonicalBytes, "canonicalBytes").clone(); + } + + @Override + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java new file mode 100644 index 0000000000..4cf1d8c1ef --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java @@ -0,0 +1,442 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; +import org.jooq.DSLContext; +import org.jooq.exception.DataAccessException; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.CannotCreateTransactionException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionSystemException; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered exact selected-publication source read; it does not authorize publication itself. + */ +public final class SelectedDraftPublicationDigestReadService { + private final OwnerRead owner; + private final TransactionTemplate snapshot; + private final String workloadNamespace; + + public SelectedDraftPublicationDigestReadService( + DSLContext dsl, PlatformTransactionManager transactions, String workloadNamespace) { + this( + new RepositoryOwnerRead( + new GameDesignPublicationOperationRepository(Objects.requireNonNull(dsl, "dsl")), + new GameDesignSourceRepository(dsl)), + transactions, + workloadNamespace); + } + + SelectedDraftPublicationDigestReadService( + OwnerRead owner, PlatformTransactionManager transactions, String workloadNamespace) { + this.owner = Objects.requireNonNull(owner, "owner"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + snapshot = new TransactionTemplate(Objects.requireNonNull(transactions, "transactions")); + snapshot.setName("game-design-selected-publication-digest-read"); + snapshot.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + snapshot.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + snapshot.setReadOnly(true); + } + + /** Returns exact local GD and retained World digests for one canonical full-version request. */ + public ReadResult read( + String targetNamespace, PublicationDigestRequestBinding publicationRequest) { + return read(targetNamespace, publicationRequest, Optional.empty()); + } + + /** Returns the same digest snapshot only when the retained Game Logic source joins exactly. */ + public ReadResult read( + String targetNamespace, + PublicationDigestRequestBinding publicationRequest, + SelectedDraftGameLogicReceipt receipt) { + if (receipt == null) { + throw Status.FAILED_PRECONDITION + .withDescription("Retained selected Game Logic receipt required") + .asRuntimeException(); + } + return read(targetNamespace, publicationRequest, Optional.of(receipt)); + } + + private ReadResult read( + String targetNamespace, + PublicationDigestRequestBinding publicationRequest, + Optional receipt) { + if (!workloadNamespace.equals(targetNamespace)) { + throw Status.PERMISSION_DENIED + .withDescription("Selected publication namespace differs from configured owner") + .asRuntimeException(); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Independent selected publication digest snapshot required") + .asRuntimeException(); + } + validateRequest(publicationRequest); + try { + return Objects.requireNonNull( + snapshot.execute(ignored -> readSnapshot(publicationRequest, receipt)), + "Selected publication digest snapshot returned no result"); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (DataAccessException + | TransientDataAccessException + | DataAccessResourceFailureException + | CannotCreateTransactionException + | TransactionSystemException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Selected publication source readback unavailable") + .withCause(unavailable) + .asRuntimeException(); + } catch (RuntimeException invalid) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact selected publication source evidence unavailable") + .withCause(invalid) + .asRuntimeException(); + } + } + + private ReadResult readSnapshot( + PublicationDigestRequestBinding publicationRequest, + Optional receipt) { + GameDesignPublicationOperationRepository.Readback readback = + owner + .read(publicationRequest.derivedWorkflowIdentity()) + .orElseThrow( + () -> + Status.NOT_FOUND + .withDescription("Selected publication operation unavailable") + .asRuntimeException()); + GameDesignPublicationOperation operation = readback.operation(); + requireOperationCorrelation(operation, publicationRequest); + + // Exact durable selection comparison precedes any source snapshot read. + owner.requireExactSelection(operation); + GameDesignSourceRepository.Capture frozen = + owner + .readSourceCapture(operation) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Complete selected source capture unavailable") + .asRuntimeException()); + requireCapture(operation, frozen); + + DraftCommitBinding selected = operation.account().input().selection().selectedCommit(); + GameDesignSourceRepository.SynchronizedSources synchronizedSources = + owner + .readSynchronized(selected.target(), selected.commitId()) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Complete synchronized selected sources unavailable") + .asRuntimeException()); + requireFrozenSources(selected, frozen, synchronizedSources); + if (receipt.isPresent() + && !SelectedGameplayRuleSourceJoin.matches( + operation, + frozen.gameplay().orElseThrow(), + synchronizedSources.gameplayEvidence().orElseThrow(), + receipt.orElseThrow())) { + throw Status.FAILED_PRECONDITION + .withDescription("Selected Gameplay source differs from retained Game Logic receipt") + .asRuntimeException(); + } + + DesignControlPlaneDigestDto designDigest = + SelectedDraftControlPlaneDigest.compute(selected, synchronizedSources).toDto(); + var worldAcknowledgement = operation.inventory().freezeEvidence().acknowledgement(); + if (!selected.commitId().toString().equals(worldAcknowledgement.appliedCommitId())) { + throw new IllegalStateException("Retained World freeze differs from selected Draft commit"); + } + var worldDigest = + new PublishParticipantDigestDto( + PublishParticipantKey.WORLD_MANAGEMENT.name(), + publicationRequest.versionId(), + null, + worldAcknowledgement.appliedCommitId(), + worldAcknowledgement.contentDigest(), + worldAcknowledgement.digestSchemaVersion(), + null, + null, + null); + return new ReadResult( + publicationRequest, publicationRequest.requestDigest(), designDigest, worldDigest); + } + + private void requireOperationCorrelation( + GameDesignPublicationOperation operation, + PublicationDigestRequestBinding publicationRequest) { + var selection = operation.account().input().selection(); + var intent = selection.intent(); + TargetProof target = selection.target(); + DraftCommitBinding selected = selection.selectedCommit(); + var world = operation.world().request(); + UUID tenant; + long numericVersion; + try { + tenant = UUID.fromString(publicationRequest.tenantId()); + numericVersion = Long.parseLong(publicationRequest.versionId()); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Canonical tenant UUID and numeric version required", malformed); + } + if (!tenant.toString().equals(publicationRequest.tenantId()) + || numericVersion <= 0 + || !tenant.equals(target.canonicalTenantId()) + || !tenant.equals(intent.canonicalTenantId()) + || target.gameDesignVersionRowId() != numericVersion + || operation.versionId() != numericVersion + || !operation.tenantKey().equals(target.gameDesignVersionTenantKey()) + || !operation.selectionDigest().equals(selection.digest()) + || !intent.canonicalVersionId().equals(target.canonicalVersionId()) + || !intent.canonicalVersionId().equals(selected.target().canonicalVersionId()) + || !publicationRequest.publishRequestId().equals(intent.publishRequestId()) + || !publicationRequest.derivedWorkflowIdentity().equals(operation.workflowId()) + || !workloadNamespace.equals(world.targetNamespace()) + || !tenant.equals(world.canonicalTenantId()) + || !intent.canonicalVersionId().equals(world.canonicalVersionId()) + || !intent.publishRequestId().equals(world.publicationRequestId()) + || !publicationRequest.derivedWorkflowIdentity().equals(world.publishWorkflowId()) + || !selection.digest().substring("sha256:".length()).equals(world.requestDigest()) + || !intent.expectedVersionStateEpoch().equals(Long.toString(world.versionStateEpoch())) + || !selected.commitId().toString().equals(world.appliedCommitId())) { + throw new IllegalStateException( + "Publication operation differs from canonical selected request"); + } + } + + private static void requireCapture( + GameDesignPublicationOperation operation, GameDesignSourceRepository.Capture capture) { + byte[] operationBytes = operation.canonicalBytes(); + for (byte[] retainedOperation : + new byte[][] { + capture.command().operation().canonicalBytes(), + capture.policy().operation().canonicalBytes(), + capture + .asset() + .orElseThrow( + () -> + new IllegalStateException("Complete frozen asset source capture unavailable")) + .operation() + .canonicalBytes(), + capture + .branding() + .orElseThrow( + () -> + new IllegalStateException( + "Complete frozen branding source capture unavailable")) + .operation() + .canonicalBytes(), + capture + .templateConfig() + .orElseThrow( + () -> + new IllegalStateException( + "Complete frozen templateConfig source capture unavailable")) + .operation() + .canonicalBytes(), + capture + .gameplay() + .orElseThrow( + () -> + new IllegalStateException( + "Complete frozen gameplay source capture unavailable")) + .operation() + .canonicalBytes() + }) { + if (!Arrays.equals(operationBytes, retainedOperation)) { + throw new IllegalStateException("Frozen source capture differs from exact operation"); + } + } + } + + private static void requireFrozenSources( + DraftCommitBinding selected, + GameDesignSourceRepository.Capture frozen, + GameDesignSourceRepository.SynchronizedSources synchronizedSources) { + BrandingSourceSnapshot branding = + synchronizedSources + .branding() + .orElseThrow( + () -> new IllegalStateException("Selected branding source snapshot unavailable")); + TemplateConfigSourceSnapshot templateConfig = + synchronizedSources + .templateConfig() + .orElseThrow( + () -> + new IllegalStateException( + "Selected template-config source snapshot unavailable")); + GameplayRuleSnapshot gameplay = + synchronizedSources + .gameplayEvidence() + .orElseThrow(() -> new IllegalStateException("Selected gameplay source unavailable")); + if (!selected.equals(synchronizedSources.command().binding()) + || !selected.equals(synchronizedSources.policy().binding()) + || !selected.equals(synchronizedSources.asset().binding()) + || !selected.equals(gameplay.binding()) + || !selected.equals(branding.binding()) + || !selected.equals(templateConfig.binding()) + || !Arrays.equals( + frozen.command().snapshot().canonicalBytes(), + synchronizedSources.command().canonicalBytes()) + || !Arrays.equals( + frozen.policy().snapshot().canonicalBytes(), + synchronizedSources.policy().canonicalBytes()) + || !Arrays.equals( + frozen + .asset() + .orElseThrow( + () -> + new IllegalStateException( + "Complete frozen asset source capture unavailable")) + .snapshot() + .canonicalBytes(), + synchronizedSources.asset().canonicalBytes()) + || !Arrays.equals( + frozen + .branding() + .orElseThrow( + () -> + new IllegalStateException( + "Complete frozen branding source capture unavailable")) + .snapshot() + .canonicalBytes(), + branding.canonicalBytes()) + || !Arrays.equals( + frozen + .templateConfig() + .orElseThrow( + () -> + new IllegalStateException( + "Complete frozen templateConfig source capture unavailable")) + .snapshot() + .canonicalBytes(), + templateConfig.canonicalBytes()) + || !Arrays.equals( + frozen + .gameplay() + .orElseThrow( + () -> + new IllegalStateException( + "Complete frozen gameplay source capture unavailable")) + .snapshot() + .canonicalBytes(), + gameplay.canonicalBytes())) { + throw new IllegalStateException( + "Frozen and synchronized source snapshots differ from the complete selected commit"); + } + } + + private static void validateRequest(PublicationDigestRequestBinding request) { + if (request == null + || request.scopeKind() != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION) { + throw Status.INVALID_ARGUMENT + .withDescription("Canonical full-version publication binding required") + .asRuntimeException(); + } + try { + var canonical = + PublicationDigestRequestBinding.full( + request.tenantId(), request.versionId(), request.publishRequestId()); + UUID tenant = UUID.fromString(request.tenantId()); + if (!Arrays.equals(canonical.canonicalPreimage(), request.canonicalPreimage()) + || !canonical.requestDigest().equals(request.requestDigest()) + || !canonical.derivedWorkflowIdentity().equals(request.derivedWorkflowIdentity()) + || !tenant.toString().equals(request.tenantId())) { + throw new IllegalArgumentException("Publication request binding is not canonical"); + } + } catch (RuntimeException malformed) { + throw Status.INVALID_ARGUMENT + .withDescription("Canonical full-version publication binding required") + .withCause(malformed) + .asRuntimeException(); + } + } + + public record ReadResult( + PublicationDigestRequestBinding requestBinding, + String requestDigest, + DesignControlPlaneDigestDto gameDesignDigest, + PublishParticipantDigestDto worldManagementDigest) { + public ReadResult { + Objects.requireNonNull(requestBinding, "requestBinding"); + Objects.requireNonNull(gameDesignDigest, "gameDesignDigest"); + Objects.requireNonNull(worldManagementDigest, "worldManagementDigest"); + requestBinding.validateSupplied(requestBinding.derivedWorkflowIdentity(), requestDigest); + requestBinding.requireOwnerScope(gameDesignDigest.tenantId(), gameDesignDigest.scopeValue()); + if (!requestBinding.versionId().equals(worldManagementDigest.scopeValue()) + || !gameDesignDigest.appliedCommitId().equals(worldManagementDigest.appliedCommitId()) + || gameDesignDigest.digestSchemaVersion() + != SelectedDraftControlPlaneDigest.SCHEMA_VERSION + || !PublishParticipantKey.WORLD_MANAGEMENT + .name() + .equals(worldManagementDigest.participantKey()) + || worldManagementDigest.baseVersionId() != null + || worldManagementDigest.contentDigest() == null + || !worldManagementDigest.contentDigest().matches("[0-9a-f]{64}") + || worldManagementDigest.digestSchemaVersion() == null + || worldManagementDigest.digestSchemaVersion() <= 0 + || !worldManagementDigest.succeeded()) { + throw new IllegalArgumentException("Paired selected publication digest scopes differ"); + } + } + } + + interface OwnerRead { + Optional read(String workflowIdentity); + + void requireExactSelection(GameDesignPublicationOperation operation); + + Optional readSourceCapture( + GameDesignPublicationOperation operation); + + Optional readSynchronized( + TargetProof target, UUID selectedCommitId); + } + + private record RepositoryOwnerRead( + GameDesignPublicationOperationRepository operations, GameDesignSourceRepository sources) + implements OwnerRead { + @Override + public Optional read( + String workflowIdentity) { + return operations.read(workflowIdentity); + } + + @Override + public void requireExactSelection(GameDesignPublicationOperation operation) { + operations.requireExactSelection(operation); + } + + @Override + public Optional readSourceCapture( + GameDesignPublicationOperation operation) { + return operations.readSourceCapture(operation); + } + + @Override + public Optional readSynchronized( + TargetProof target, UUID selectedCommitId) { + return sources.readSynchronized(target, selectedCommitId); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java index b7174e27b6..35c8cc11d8 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java @@ -561,7 +561,8 @@ private void requireReleaseMatches( || !Objects.equals(release.canonicalTenantId(), exact.association().canonicalTenantId()) || !Objects.equals(release.canonicalVersionId(), exact.association().canonicalVersionId()) || !Objects.equals(release.publishWorkflowId(), exact.association().publishWorkflowId()) - || !"v2".equals(release.attestationSchemaVersion()) + || !PublishedReleaseBundleDto.isSelectedAttestationSchema( + release.attestationSchemaVersion()) || !Objects.equals( release.worldPublishedStartLocationEvidence(), exact.worldPublishedStartLocationEvidence()) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java index 8e21ac2adb..5ce6182007 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java @@ -260,7 +260,8 @@ private Result readSnapshot(Request request, StartSessionPostAuthorizationExecut .asRuntimeException()); if (!canonicalTenantId.equals(configuredRelease.canonicalTenantId()) || !canonicalVersionId.equals(configuredRelease.canonicalVersionId()) - || !"v2".equals(configuredRelease.attestationSchemaVersion())) { + || !PublishedReleaseBundleDto.isSelectedAttestationSchema( + configuredRelease.attestationSchemaVersion())) { throw new IllegalStateException("START_SESSION_CONFIGURED_RELEASE_IDENTITY_CONFLICT"); } workflowId = configuredRelease.publishWorkflowId(); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java index 723b6d8ac8..d450711f7f 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java @@ -11,6 +11,7 @@ import java.util.UUID; import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; @@ -182,12 +183,14 @@ private PublishedReleaseBundle insertNewBundle( rejectCallerIdentitySubstitution(bundle, source); verifySelectorSource(bundle, source); if (!"v1".equals(bundle.getAttestationSchemaVersion()) - && !"v2".equals(bundle.getAttestationSchemaVersion())) { + && !PublishedReleaseBundleDto.isSelectedAttestationSchema( + bundle.getAttestationSchemaVersion())) { throw new IllegalArgumentException( "Unsupported published release bundle attestation schema " + bundle.getAttestationSchemaVersion()); } - if ("v2".equals(bundle.getAttestationSchemaVersion())) { + if (PublishedReleaseBundleDto.isSelectedAttestationSchema( + bundle.getAttestationSchemaVersion())) { PublishedReleaseBundle existing = tx.selectFrom(TABLE_REF) .where(TENANT_ID.eq(bundle.getTenantId()).and(VERSION_ID.eq(bundle.getVersionId()))) @@ -363,7 +366,8 @@ private PublishedReleaseBundle toEntity(Record record) { private static void verifySelectorSource(PublishedReleaseBundle bundle, CanonicalSource source) { String bytes = bundle.getWorldPublishedStartLocationEvidenceJson(); - if (!"v2".equals(bundle.getAttestationSchemaVersion())) { + if (!PublishedReleaseBundleDto.isSelectedAttestationSchema( + bundle.getAttestationSchemaVersion())) { if (bytes != null) { throw new IllegalArgumentException( "Selector evidence is forbidden on historical release schemas"); @@ -371,14 +375,17 @@ private static void verifySelectorSource(PublishedReleaseBundle bundle, Canonica return; } if (bytes == null) { - throw new IllegalArgumentException("World selector evidence is mandatory for release v2"); + throw new IllegalArgumentException( + "World selector evidence is mandatory for selected release v2/v4"); } var request = WorldPublishedStartLocationEvidence.fromStored(bytes.getBytes(StandardCharsets.UTF_8)) .request(); if (!request.canonicalTenantId().equals(source.canonicalTenantId()) || !request.canonicalVersionId().equals(source.canonicalVersionId()) - || !request.publishWorkflowId().equals(bundle.getPublishWorkflowId())) { + || !request.publishWorkflowId().equals(bundle.getPublishWorkflowId()) + || request.digestSchemaVersion() + != ("v4".equals(bundle.getAttestationSchemaVersion()) ? 4 : 3)) { throw new IllegalArgumentException( "World selector differs from exact Version source/workflow"); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java index 20a9840c0f..57c46fd3eb 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java @@ -16,6 +16,7 @@ import net.firedevops.firemud.gamedesign.publication.AssetSourceRepository; import org.jooq.DSLContext; import org.jooq.Record; +import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; /** Owner-local persistence boundary for Draft asset mappings and durable export snapshots. */ @@ -51,11 +52,35 @@ public ExportSnapshot freezeOrReadSnapshot(String tenantId, int versionNumber) { if (versionNumber <= 0) { throw new IllegalArgumentException("Version number must be positive"); } + return dsl.connectionResult( + connection -> { + if (connection.getAutoCommit()) { + throw new IllegalStateException( + "Version asset snapshot requires an enclosing owner transaction"); + } + // Preserve caller configuration while keeping every query on the checked connection. + DSLContext ownerDsl = DSL.using(dsl.configuration().derive(connection)); + return new VersionAssetPublicationRepository(ownerDsl) + .freezeOrReadSnapshotInTransaction(tenantId, versionNumber); + }); + } + + private ExportSnapshot freezeOrReadSnapshotInTransaction(String tenantId, int versionNumber) { VersionRow version = - lockVersionByTenantAndVersionNumber(tenantId, versionNumber) + readVersionByTenantAndVersionNumber(tenantId, versionNumber) .orElseThrow(() -> new IllegalStateException("Exact tenant Version was not found")); qualifyVersion(version); + // Retained snapshots are immutable; reading one does not need a writable row lock. + if (hasSnapshot(tenantId, version.id())) { + return readSnapshot(version); + } + + version = + lockVersionByTenantAndVersionNumber(tenantId, versionNumber) + .orElseThrow(() -> new IllegalStateException("Exact tenant Version was not found")); + qualifyVersion(version); + // Another first freeze may have committed before this transaction obtained the lock. if (hasSnapshot(tenantId, version.id())) { return readSnapshot(version); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishGateService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishGateService.java index 60c070ccad..6f5f7b0911 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishGateService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishGateService.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamedesign.service; import java.util.List; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; @@ -8,8 +9,20 @@ public interface PublishGateService { List collectFullVersionParticipantDigests( VersionDto version, String publishRequestId, String publishWorkflowId); + /** Collects owner digests using the canonical binding read from the exact selected operation. */ + List collectSelectedFullVersionParticipantDigests( + VersionDto version, + PublicationDigestRequestBinding canonicalBinding, + String publishWorkflowId); + List collectScriptPatchParticipantDigests( VersionDto version, String publishRequestId, String publishWorkflowId); void assertGatePassed(VersionDto version, List participantDigests); + + /** + * Requires the selected full-publication digest schemas, including all six GD source families. + */ + void assertSelectedGatePassed( + VersionDto version, List participantDigests); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java index 7e7301172e..261d04ae77 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java @@ -157,6 +157,30 @@ public CompleteLaunchBindingDto getCompleteLaunchBinding( bundle.commandDefinitions(), bundle.generationConfigRevision(), bundle.worldPublishedStartLocationEvidence()); + } else if (PublishedReleaseBundleContract.SELECTED_FULL_ATTESTATION_SCHEMA_VERSION.equals( + bundle.attestationSchemaVersion())) { + releaseAttestation = + AuthoredWorldReleaseAttestationEvidence.createSelectedFull( + descriptor.targetNamespace(), + descriptor.resultDigest(), + source.canonicalTenantId(), + canonicalVersion.getCanonicalVersionId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + bundle.publishWorkflowId(), + commitId, + participants, + bundle.manifestHash(), + bundle.manifestSchemaVersion(), + bundle.requiredManifestAssetKeys(), + artifacts, + bundle.commandDefinitions(), + bundle.generationConfigRevision(), + bundle.worldPublishedStartLocationEvidence()); } else { releaseAttestation = AuthoredWorldReleaseAttestationEvidence.create( @@ -273,7 +297,8 @@ private void requireExactBundleBinding( || !Objects.equals(snapshotCanonicalVersionId, bundle.canonicalVersionId()) || !("v1".equals(bundle.attestationSchemaVersion()) && bundle.worldPublishedStartLocationEvidence() == null - || "v2".equals(bundle.attestationSchemaVersion()) + || PublishedReleaseBundleDto.isSelectedAttestationSchema( + bundle.attestationSchemaVersion()) && bundle.worldPublishedStartLocationEvidence() != null) || !Objects.equals(bundle.id(), descriptor.releaseBundleId()) || !Objects.equals(bundle.versionId(), descriptor.versionId()) @@ -351,6 +376,7 @@ private List requirePartici switch (bundle.attestationSchemaVersion()) { case "v1" -> AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION; case "v2" -> AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION; + case "v4" -> AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION; default -> throw deny( "RELEASE_ATTESTATION_SCHEMA_UNSUPPORTED", diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java index a70eb5a7f4..7971bc5934 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java @@ -1,10 +1,16 @@ package net.firedevops.firemud.gamedesign.service.impl; +import io.grpc.StatusRuntimeException; +import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.client.AutomationScriptingClient; import net.firedevops.firemud.gamedesign.client.EntityManagementClient; @@ -15,13 +21,21 @@ import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode; import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptRepository; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationDigestReadService; import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; import net.firedevops.firemud.gamedesign.service.PublishGateService; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; @Service -public class PublishGateServiceImpl implements PublishGateService { +public final class PublishGateServiceImpl implements PublishGateService { private static final Map SUPPORTED_DIGEST_SCHEMA_VERSIONS = Map.of( PublishParticipantKey.WORLD_MANAGEMENT.name(), 3, @@ -47,18 +61,69 @@ public class PublishGateServiceImpl implements PublishGateService { private final EntityManagementClient entityManagementClient; private final GameLogicClient gameLogicClient; private final AutomationScriptingClient automationScriptingClient; + private final SelectedDraftGameLogicReceiptRepository selectedGameLogicReceiptRepository; + private final SelectedDraftPublicationDigestReadService selectedPublicationDigestReader; + private final String workloadNamespace; + @Autowired public PublishGateServiceImpl( ControlPlaneDigestService controlPlaneDigestService, WorldManagementClient worldManagementClient, EntityManagementClient entityManagementClient, GameLogicClient gameLogicClient, - AutomationScriptingClient automationScriptingClient) { + AutomationScriptingClient automationScriptingClient, + DSLContext dsl, + PlatformTransactionManager transactions, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this( + controlPlaneDigestService, + worldManagementClient, + entityManagementClient, + gameLogicClient, + automationScriptingClient, + new SelectedDraftGameLogicReceiptRepository(dsl), + GrpcPeerIdentity.isValidNamespace(workloadNamespace) + ? new SelectedDraftPublicationDigestReadService(dsl, transactions, workloadNamespace) + : null, + workloadNamespace); + } + + PublishGateServiceImpl( + ControlPlaneDigestService controlPlaneDigestService, + WorldManagementClient worldManagementClient, + EntityManagementClient entityManagementClient, + GameLogicClient gameLogicClient, + AutomationScriptingClient automationScriptingClient, + SelectedDraftGameLogicReceiptRepository selectedGameLogicReceiptRepository) { + this( + controlPlaneDigestService, + worldManagementClient, + entityManagementClient, + gameLogicClient, + automationScriptingClient, + selectedGameLogicReceiptRepository, + null, + null); + } + + PublishGateServiceImpl( + ControlPlaneDigestService controlPlaneDigestService, + WorldManagementClient worldManagementClient, + EntityManagementClient entityManagementClient, + GameLogicClient gameLogicClient, + AutomationScriptingClient automationScriptingClient, + SelectedDraftGameLogicReceiptRepository selectedGameLogicReceiptRepository, + SelectedDraftPublicationDigestReadService selectedPublicationDigestReader, + String workloadNamespace) { this.controlPlaneDigestService = controlPlaneDigestService; this.worldManagementClient = worldManagementClient; this.entityManagementClient = entityManagementClient; this.gameLogicClient = gameLogicClient; this.automationScriptingClient = automationScriptingClient; + this.selectedGameLogicReceiptRepository = + Objects.requireNonNull(selectedGameLogicReceiptRepository); + this.selectedPublicationDigestReader = selectedPublicationDigestReader; + this.workloadNamespace = workloadNamespace; } @Override @@ -69,8 +134,92 @@ public List collectFullVersionParticipantDigests( PublicationDigestRequestBinding.full( version.tenantId(), String.valueOf(version.id()), publishRequestId); requireWorkflowIdentity(binding, publishWorkflowId); + return collectFullVersionParticipantDigests(version, binding, false); + } + + @Override + public List collectSelectedFullVersionParticipantDigests( + VersionDto version, + PublicationDigestRequestBinding canonicalBinding, + String publishWorkflowId) { + Objects.requireNonNull(version, "version must not be null"); + Objects.requireNonNull(canonicalBinding, "canonicalBinding must not be null"); + if (version.scriptOnly() + || version.id() == null + || canonicalBinding.scopeKind() != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION + || !String.valueOf(version.id()).equals(canonicalBinding.versionId())) { + throw new IllegalArgumentException( + "selected publication requires the exact full-version Game Design row binding"); + } + UUID canonicalTenant; + try { + canonicalTenant = UUID.fromString(canonicalBinding.tenantId()); + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "selected publication tenant must be its canonical UUID", malformed); + } + if (!canonicalTenant.toString().equals(canonicalBinding.tenantId())) { + throw new IllegalArgumentException("selected publication tenant must be its canonical UUID"); + } + requireWorkflowIdentity(canonicalBinding, publishWorkflowId); + SelectedDraftPublicationDigestReadService.ReadResult selected = null; + String failureCode = "PARTICIPANT_UNAVAILABLE"; + try { + if (selectedPublicationDigestReader == null + || !GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalStateException("Selected publication digest reader unavailable"); + } + selected = selectedPublicationDigestReader.read(workloadNamespace, canonicalBinding); + if (selected == null + || !Arrays.equals( + canonicalBinding.canonicalPreimage(), selected.requestBinding().canonicalPreimage()) + || !canonicalBinding.requestDigest().equals(selected.requestDigest()) + || !canonicalBinding + .derivedWorkflowIdentity() + .equals(selected.requestBinding().derivedWorkflowIdentity())) { + throw new IllegalStateException("Selected publication digest request echo differs"); + } + } catch (RuntimeException unavailable) { + selected = null; + failureCode = + unavailable instanceof StatusRuntimeException grpcFailure + ? grpcFailure.getStatus().getCode().name() + : "FAILED_PRECONDITION"; + if (selectedPublicationDigestReader == null + || !GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + failureCode = "PARTICIPANT_UNAVAILABLE"; + } + } + var snapshot = selected; + String snapshotFailureCode = failureCode; return FULL_VERSION_PARTICIPANTS.stream() - .map(participant -> observeFullVersionParticipant(version, binding, participant)) + .map( + participant -> { + if (participant == PublishParticipantKey.WORLD_MANAGEMENT + || participant == PublishParticipantKey.GAME_DESIGN_CONTROL_PLANE) { + if (snapshot == null) { + return failedObservation( + participant, + canonicalBinding.versionId(), + null, + snapshotFailureCode, + "Exact selected publication source evidence unavailable"); + } + return participant == PublishParticipantKey.WORLD_MANAGEMENT + ? snapshot.worldManagementDigest() + : toParticipantDigest(participant, version, snapshot.gameDesignDigest()); + } + return observeFullVersionParticipant(version, canonicalBinding, participant, true); + }) + .toList(); + } + + private List collectFullVersionParticipantDigests( + VersionDto version, PublicationDigestRequestBinding binding, boolean selectedPublication) { + return FULL_VERSION_PARTICIPANTS.stream() + .map( + participant -> + observeFullVersionParticipant(version, binding, participant, selectedPublication)) .toList(); } @@ -96,6 +245,49 @@ public List collectScriptPatchParticipantDigests( @Override public void assertGatePassed( VersionDto version, List participantDigests) { + assertGatePassed(version, participantDigests, null); + } + + @Override + public void assertSelectedGatePassed( + VersionDto version, List participantDigests) { + if (version.scriptOnly()) { + throw new IllegalArgumentException("Selected publication requires a full version"); + } + assertParticipantSetAndSucceeded(version, participantDigests); + List worldDigests = + participantDigests == null + ? List.of() + : participantDigests.stream() + .filter(digest -> "WORLD_MANAGEMENT".equals(digest.participantKey())) + .toList(); + if (worldDigests.size() != 1 || worldDigests.getFirst().digestSchemaVersion() == null) { + throw new PublishGateFailureException( + PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA, + "publish gate failed: exact selected World digest schema is required"); + } + int selectedAttestationSchema = + switch (worldDigests.getFirst().digestSchemaVersion()) { + case 3 -> AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION; + case 4 -> AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION; + default -> + throw new PublishGateFailureException( + PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA, + "publish gate failed: unsupported selected World digest schema"); + }; + assertParticipantEvidence(version, participantDigests, selectedAttestationSchema); + } + + private void assertGatePassed( + VersionDto version, + List participantDigests, + Integer selectedAttestationSchema) { + assertParticipantSetAndSucceeded(version, participantDigests); + assertParticipantEvidence(version, participantDigests, selectedAttestationSchema); + } + + private void assertParticipantSetAndSucceeded( + VersionDto version, List participantDigests) { List expectedParticipants = version.scriptOnly() ? SCRIPT_PATCH_PARTICIPANTS : FULL_VERSION_PARTICIPANTS; List expectedParticipantKeyList = @@ -132,6 +324,12 @@ public void assertGatePassed( + (failed.errorMessage() == null ? failed.errorCode() : failed.errorMessage()), failed.errorCode()); } + } + + private void assertParticipantEvidence( + VersionDto version, + List participantDigests, + Integer selectedAttestationSchema) { String expectedScope = version.scriptOnly() ? version.scriptPatchVersion() : String.valueOf(version.id()); Long expectedBaseVersionId = version.scriptOnly() ? version.baseVersionId() : null; @@ -144,8 +342,17 @@ public void assertGatePassed( "publish gate failed: wrong scope from " + digest.participantKey()); } String participantKey = digest.participantKey(); - Integer supportedSchemaVersion = - participantKey == null ? null : SUPPORTED_DIGEST_SCHEMA_VERSIONS.get(participantKey); + Integer supportedSchemaVersion; + if (selectedAttestationSchema != null) { + supportedSchemaVersion = + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participantKey, selectedAttestationSchema); + } else { + supportedSchemaVersion = + participantKey == null + ? null + : SUPPORTED_DIGEST_SCHEMA_VERSIONS.get(participantKey); + } if (digest.digestSchemaVersion() == null || !digest.digestSchemaVersion().equals(supportedSchemaVersion)) { throw new PublishGateFailureException( @@ -178,11 +385,15 @@ public void assertGatePassed( private PublishParticipantDigestDto observeFullVersionParticipant( VersionDto version, PublicationDigestRequestBinding binding, - PublishParticipantKey participantKey) { + PublishParticipantKey participantKey, + boolean selectedPublication) { return switch (participantKey) { case WORLD_MANAGEMENT -> worldManagementClient.getDraftDesignDigestForVersion(binding); case ENTITY_MANAGEMENT -> entityManagementClient.getDraftDesignDigestForVersion(binding); - case GAME_LOGIC -> gameLogicClient.getDraftDesignDigestForVersion(binding); + case GAME_LOGIC -> + selectedPublication + ? observeSelectedGameLogicParticipant(binding) + : gameLogicClient.getDraftDesignDigestForVersion(binding); case AUTOMATION_SCRIPTING -> automationScriptingClient.getDraftDesignDigestForVersion(binding); case GAME_DESIGN_CONTROL_PLANE -> @@ -191,6 +402,74 @@ private PublishParticipantDigestDto observeFullVersionParticipant( }; } + private PublishParticipantDigestDto observeSelectedGameLogicParticipant( + PublicationDigestRequestBinding binding) { + Optional receipt; + try { + receipt = selectedGameLogicReceiptRepository.readForPublication(binding); + } catch (org.jooq.exception.DataAccessException | DataAccessException unavailable) { + return failedObservation( + PublishParticipantKey.GAME_LOGIC, + binding.versionId(), + null, + "UNAVAILABLE", + "immutable selected Game Logic receipt readback is temporarily unavailable"); + } + if (receipt == null) { + return failedObservation( + PublishParticipantKey.GAME_LOGIC, + binding.versionId(), + null, + "UNAVAILABLE", + "immutable selected Game Logic receipt readback returned no result"); + } + if (receipt.isEmpty()) { + return failedObservation( + PublishParticipantKey.GAME_LOGIC, + binding.versionId(), + null, + "PARTICIPANT_UNAVAILABLE", + "immutable selected Game Logic receipt is not available yet"); + } + if (selectedPublicationDigestReader == null + || !GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + return failedObservation( + PublishParticipantKey.GAME_LOGIC, + binding.versionId(), + null, + "PARTICIPANT_UNAVAILABLE", + "selected publication source reader is unavailable"); + } + final SelectedDraftPublicationDigestReadService.ReadResult sourceRead; + try { + sourceRead = + selectedPublicationDigestReader.read(workloadNamespace, binding, receipt.orElseThrow()); + if (sourceRead == null + || !Arrays.equals( + binding.canonicalPreimage(), sourceRead.requestBinding().canonicalPreimage()) + || !binding.requestDigest().equals(sourceRead.requestDigest()) + || !binding + .derivedWorkflowIdentity() + .equals(sourceRead.requestBinding().derivedWorkflowIdentity())) { + throw io.grpc.Status.FAILED_PRECONDITION + .withDescription("Selected Game Logic source read request echo differs") + .asRuntimeException(); + } + } catch (RuntimeException unavailable) { + String failureCode = + unavailable instanceof StatusRuntimeException grpcFailure + ? grpcFailure.getStatus().getCode().name() + : "FAILED_PRECONDITION"; + return failedObservation( + PublishParticipantKey.GAME_LOGIC, + binding.versionId(), + null, + failureCode, + "exact selected Game Logic source evidence unavailable"); + } + return gameLogicClient.getDraftDesignDigestForVersion(binding, receipt.orElseThrow()); + } + private void requireWorkflowIdentity( PublicationDigestRequestBinding binding, String suppliedWorkflowIdentity) { if (!binding.derivedWorkflowIdentity().equals(suppliedWorkflowIdentity)) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java index f40b92aa71..7f864578c2 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java @@ -13,6 +13,7 @@ final class PublishedReleaseBundleContract { static final String SUPPORTED_ATTESTATION_SCHEMA_VERSION = "v1"; static final String SELECTOR_ATTESTATION_SCHEMA_VERSION = "v2"; + static final String SELECTED_FULL_ATTESTATION_SCHEMA_VERSION = "v4"; static final int SUPPORTED_MANIFEST_SCHEMA_VERSION = 1; static final int SUPPORTED_ARTIFACT_SCHEMA_VERSION = 1; static final String SCHEMA_VERSION_UNSUPPORTED = "SCHEMA_VERSION_UNSUPPORTED"; @@ -22,10 +23,30 @@ final class PublishedReleaseBundleContract { private PublishedReleaseBundleContract() {} static void requireSelectorBinding(PublishedReleaseBundleDto bundle) { + requireSelectedBinding( + bundle, + SELECTOR_ATTESTATION_SCHEMA_VERSION, + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION, + "World selector"); + } + + static void requireSelectedFullBinding(PublishedReleaseBundleDto bundle) { + requireSelectedBinding( + bundle, + SELECTED_FULL_ATTESTATION_SCHEMA_VERSION, + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION, + "Selected-full release"); + } + + private static void requireSelectedBinding( + PublishedReleaseBundleDto bundle, + String expectedBundleSchema, + int evidenceSchema, + String description) { var evidence = Objects.requireNonNull(bundle.worldPublishedStartLocationEvidence(), "World evidence"); var request = evidence.request(); - if (!SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion()) + if (!expectedBundleSchema.equals(bundle.attestationSchemaVersion()) || bundle.scriptOnly() || bundle.scriptPatchVersion() != null || !request.canonicalTenantId().equals(bundle.canonicalTenantId()) @@ -37,7 +58,7 @@ static void requireSelectorBinding(PublishedReleaseBundleDto bundle) { || request.appliedCommitId() == null || request.appliedCommitId().isBlank()) { throw new IllegalArgumentException( - "World selector differs from complete immutable release binding"); + description + " differs from complete immutable release binding"); } new ExportedAssetManifest( bundle.manifestHash(), @@ -51,7 +72,7 @@ static void requireSelectorBinding(PublishedReleaseBundleDto bundle) { } var required = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder(); if (bundle.participantDigests().size() != required.size()) { - throw new IllegalArgumentException("World selector release lacks required participants"); + throw new IllegalArgumentException(description + " release lacks required participants"); } for (int index = 0; index < required.size(); index++) { var participant = bundle.participantDigests().get(index); @@ -67,27 +88,65 @@ static void requireSelectorBinding(PublishedReleaseBundleDto bundle) { || !Objects.equals( participant.digestSchemaVersion(), AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - participant.participantKey(), - AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION))) { + participant.participantKey(), evidenceSchema))) { throw new IllegalArgumentException( - "World selector requires all exact successful ordered release participants"); + description + " requires all exact successful ordered release participants"); } if ("WORLD_MANAGEMENT".equals(participant.participantKey()) && (!request.contentDigest().equals(participant.contentDigest()) || request.digestSchemaVersion() != participant.digestSchemaVersion())) { throw new IllegalArgumentException( - "World selector differs from World participant digest/schema"); + description + " differs from World participant digest/schema"); } if ("GAME_LOGIC".equals(participant.participantKey()) && (participant.abilitySchemaDigest() == null || !participant.abilitySchemaDigest().matches("sha256:[0-9a-f]{64}"))) { throw new IllegalArgumentException( - "World selector release lacks Game Logic ability schema proof"); + description + " release lacks Game Logic ability schema proof"); } if (!"GAME_LOGIC".equals(participant.participantKey()) && participant.abilitySchemaDigest() != null) { throw new IllegalArgumentException( - "World selector ability schema proof must be owned by Game Logic"); + description + " ability schema proof must be owned by Game Logic"); + } + } + } + + static void requireFreshSelectedFullParticipantVector( + long versionId, String appliedCommitId, List participants) { + if (versionId <= 0 || appliedCommitId == null || appliedCommitId.isBlank()) { + throw new IllegalArgumentException("Selected-full participant scope is invalid"); + } + var required = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder(); + if (participants == null || participants.size() != required.size()) { + throw new IllegalArgumentException( + "Selected-full release requires all five exact participants"); + } + String expectedScope = Long.toString(versionId); + for (int index = 0; index < required.size(); index++) { + var participant = participants.get(index); + String participantKey = required.get(index); + boolean gameLogic = "GAME_LOGIC".equals(participantKey); + if (participant == null + || !participantKey.equals(participant.participantKey()) + || !expectedScope.equals(participant.scopeValue()) + || participant.baseVersionId() != null + || !appliedCommitId.equals(participant.appliedCommitId()) + || !participant.succeeded() + || (participant.errorMessage() != null && !participant.errorMessage().isBlank()) + || participant.contentDigest() == null + || !participant.contentDigest().matches("[0-9a-f]{64}") + || participant.digestSchemaVersion() == null + || participant.digestSchemaVersion() + != AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participantKey, + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION) + || (gameLogic + ? participant.abilitySchemaDigest() == null + || !participant.abilitySchemaDigest().matches("sha256:[0-9a-f]{64}") + : participant.abilitySchemaDigest() != null)) { + throw new IllegalArgumentException( + "Selected-full release requires the exact 4/3/1/6/2 successful participant vector"); } } } @@ -100,11 +159,14 @@ static void requireExactSelectorRetry( String generationRevision, List participants, WorldPublishedStartLocationEvidence evidence) { - if (!SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(stored.attestationSchemaVersion())) { + if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(stored.attestationSchemaVersion())) { + requireSelectorBinding(stored); + } else if (SELECTED_FULL_ATTESTATION_SCHEMA_VERSION.equals(stored.attestationSchemaVersion())) { + requireSelectedFullBinding(stored); + } else { throw new IllegalStateException( "IDEMPOTENCY_CONFLICT: historical release is selector-ineligible"); } - requireSelectorBinding(stored); if (stored.versionNumber() != version.versionNumber() || version.scriptOnly() || version.scriptPatchVersion() != null @@ -124,6 +186,14 @@ static void requireExactSelectorRetry( } static void requireSupportedSchemaForRead(PublishedReleaseBundleDto bundle) { + if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { + requireSelectorBinding(bundle); + return; + } + if (SELECTED_FULL_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { + requireSelectedFullBinding(bundle); + return; + } if (!SUPPORTED_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { throw new IllegalStateException( SCHEMA_VERSION_UNSUPPORTED @@ -140,10 +210,22 @@ static void requireSupportedSchemaForPublicationRead(PublishedReleaseBundleDto b requireSelectorBinding(bundle); return; } + if (SELECTED_FULL_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { + requireSelectedFullBinding(bundle); + return; + } requireSupportedSchemaForRead(bundle); } static void requireSupportedSchemaForLaunch(PublishedReleaseBundleDto bundle) { + if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { + requireSelectorBinding(bundle); + return; + } + if (SELECTED_FULL_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { + requireSelectedFullBinding(bundle); + return; + } if (!SUPPORTED_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { throw new IllegalArgumentException( SCHEMA_VERSION_UNSUPPORTED @@ -156,17 +238,13 @@ static void requireSupportedSchemaForLaunch(PublishedReleaseBundleDto bundle) { * Descriptor resolution only; descriptor/v1 remains separate from the complete release carrier. */ static void requireSupportedSchemaForLaunchDescriptor(PublishedReleaseBundleDto bundle) { - if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { - requireSelectorBinding(bundle); - return; - } requireSupportedSchemaForLaunch(bundle); } static void requireExactRepairMatch( PublishedReleaseBundleDto bundle, ExportedAssetManifest exportedManifest) { - if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { - requireSelectorBinding(bundle); + if (PublishedReleaseBundleDto.isSelectedAttestationSchema(bundle.attestationSchemaVersion())) { + requireSupportedSchemaForPublicationRead(bundle); } else { requireSupportedSchemaForRead(bundle); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java index f0551d3cc8..cf00f2ea3e 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java @@ -111,6 +111,8 @@ private PublishedReleaseBundleDto createBundle( } return stored; } + PublishedReleaseBundleContract.requireFreshSelectedFullParticipantVector( + version.id(), worldEvidence.request().appliedCommitId(), participantDigests); var identitySource = versionRepository .findByTenantIdAndId(version.tenantId(), version.id()) @@ -133,7 +135,7 @@ private PublishedReleaseBundleDto createBundle( entity.setCanonicalVersionId(canonicalVersionId); entity.setVersionNumber(version.versionNumber()); entity.setAttestationSchemaVersion( - PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION); + PublishedReleaseBundleContract.SELECTED_FULL_ATTESTATION_SCHEMA_VERSION); entity.setWorldPublishedStartLocationEvidenceJson( new String(worldEvidence.canonicalBytes(), StandardCharsets.UTF_8)); entity.setPublishWorkflowId(publishWorkflowId); @@ -201,6 +203,9 @@ private PublishedReleaseBundleDto toDto(PublishedReleaseBundle entity) { if (PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION.equals( dto.attestationSchemaVersion())) { PublishedReleaseBundleContract.requireSelectorBinding(dto); + } else if (PublishedReleaseBundleContract.SELECTED_FULL_ATTESTATION_SCHEMA_VERSION.equals( + dto.attestationSchemaVersion())) { + PublishedReleaseBundleContract.requireSelectedFullBinding(dto); } return dto; } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java index dd9ce8b7cb..fe5dfbb52d 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java @@ -267,8 +267,13 @@ private PublishWorkflowSnapshot reconcileSelectedPublicationMechanicsLocal( try { dto = versionMapper.toDto(version); participantDigests = - publishGateService.collectFullVersionParticipantDigests( - dto, request.publishRequestId(), request.publishWorkflowId()); + publishGateService.collectSelectedFullVersionParticipantDigests( + dto, + PublicationDigestRequestBinding.full( + requireSelectedIntent(request).intent().canonicalTenantId().toString(), + String.valueOf(version.getId()), + request.publishRequestId()), + request.publishWorkflowId()); } catch (RuntimeException ex) { if (PublicationFailureClassifier.isRetryableParticipantDependencyFailure(ex)) { throw pendingReconciliation( @@ -278,8 +283,12 @@ private PublishWorkflowSnapshot reconcileSelectedPublicationMechanicsLocal( return failDefinitively(request, attempt, version, null, ex); } try { + publishGateService.assertSelectedGatePassed(dto, participantDigests); assertSelectedCommit(request, participantDigests); - publishGateService.assertGatePassed(dto, participantDigests); + PublishedReleaseBundleContract.requireFreshSelectedFullParticipantVector( + dto.id(), + requireSelectedIntent(request).selectedCommit().commitId().toString(), + participantDigests); } catch (RuntimeException ex) { if (PublicationFailureClassifier.isRetryableParticipantDependencyFailure(ex)) { throw pendingReconciliation( @@ -501,8 +510,12 @@ private PublishWorkflowSnapshot finalizeFullVersion( VersionDto dto = versionMapper.toDto(version); requireSelectedDraftEpoch(request, version); + publishGateService.assertSelectedGatePassed(dto, participantDigests); assertSelectedCommit(request, participantDigests); - publishGateService.assertGatePassed(dto, participantDigests); + PublishedReleaseBundleContract.requireFreshSelectedFullParticipantVector( + dto.id(), + requireSelectedIntent(request).selectedCommit().commitId().toString(), + participantDigests); publishAttemptService.recordFullVersionParticipantDigests( request.publishWorkflowId(), participantDigests); VersionAssetArtifactStateDto exportedState = @@ -646,7 +659,13 @@ private void assertCommittedBundleEvidence( VersionDto versionDto = versionMapper.toDto(readback.version()); PublishedReleaseBundleContract.requireSupportedSchemaForPublicationRead(readback.bundle()); assertSelectedCommit(request, readback.bundle().participantDigests()); - publishGateService.assertGatePassed(versionDto, readback.bundle().participantDigests()); + if (PublishedReleaseBundleDto.isSelectedAttestationSchema( + readback.bundle().attestationSchemaVersion())) { + publishGateService.assertSelectedGatePassed( + versionDto, readback.bundle().participantDigests()); + } else { + publishGateService.assertGatePassed(versionDto, readback.bundle().participantDigests()); + } recordedParticipantDigestService.assertMatchesRecordedDigests( request.tenantId(), PublishType.FULL_VERSION, readback.bundle().participantDigests()); } @@ -933,8 +952,7 @@ private void requireExactBundleEvidence( if (!Objects.equals(version.getTenantId(), bundle.tenantId()) || version.getVersionNumber() != bundle.versionNumber() || version.isScriptOnly() - || (PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION.equals( - bundle.attestationSchemaVersion()) + || (PublishedReleaseBundleDto.isSelectedAttestationSchema(bundle.attestationSchemaVersion()) && (!Objects.equals(version.getCanonicalTenantId(), bundle.canonicalTenantId()) || !Objects.equals( version.getCanonicalVersionId(), bundle.canonicalVersionId())))) { @@ -952,8 +970,7 @@ private void requireExactCommittedBundleIdentity( || bundle.scriptPatchVersion() != null) { throw new IllegalStateException("PUBLISH_ATTEMPT_BUNDLE_SCOPE_MISMATCH"); } - if (PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION.equals( - bundle.attestationSchemaVersion())) { + if (PublishedReleaseBundleDto.isSelectedAttestationSchema(bundle.attestationSchemaVersion())) { PublishedReleaseBundleContract.requireSupportedSchemaForPublicationRead(bundle); requireExactSelectedWorldEvidence(request, bundle); } diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java index b135d2b0bd..f564110d45 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java @@ -137,6 +137,24 @@ public static GameDesignPublicationOperation retainFrozenSourceBacked( return operation; } + /** + * Isolated GDS transaction fixture with a fresh stipulated selected-full World schema-4 input. + * The World evidence remains stipulated and is not native producer or freeze proof. + */ + public static GameDesignPublicationOperation retainFrozenSourceBackedSelectedFull( + DSLContext dsl, + DraftCommitBinding.TargetProof target, + long draftEpoch, + String notes, + List ordinaryAssets) + throws Exception { + String authoredPolicyCommit = retainPublicProductionPolicy(dsl, target, ordinaryAssets); + GameDesignPublicationOperation operation = + retain(dsl, target, draftEpoch, notes, true, authoredPolicyCommit, false, true); + new GameDesignPublicationOperationRepository(dsl).reserveSourceBacked(operation); + return operation; + } + /** Fixture input from an actual same-tenant game_assets row, not publication authority. */ public record OrdinaryAsset(long assetRowId, String usageKey) { public OrdinaryAsset { @@ -176,6 +194,20 @@ private static GameDesignPublicationOperation retain( String sourceBaseReference, boolean historicalV1) throws Exception { + return retain( + dsl, target, draftEpoch, notes, captureSources, sourceBaseReference, historicalV1, false); + } + + private static GameDesignPublicationOperation retain( + DSLContext dsl, + DraftCommitBinding.TargetProof target, + long draftEpoch, + String notes, + boolean captureSources, + String sourceBaseReference, + boolean historicalV1, + boolean selectedFullWorld) + throws Exception { var sources = new GameDesignSourceRepository(dsl); var reviewed = new GameDesignReviewedBaseRepository(dsl); var evidence = @@ -189,10 +221,14 @@ private static GameDesignPublicationOperation retain( : sourceBaseReference)) : null; var seed = - captureSources - ? IsolatedPublicationOperationFixtures.fresh( + selectedFullWorld + ? IsolatedPublicationOperationFixtures.freshSelectedFull( target, evidence.reference().canonicalValue()) - : IsolatedPublicationOperationFixtures.fresh(target); + : captureSources + ? IsolatedPublicationOperationFixtures.fresh( + target, evidence.reference().canonicalValue()) + : IsolatedPublicationOperationFixtures.fresh(target); + var seedWorld = seed.world(); var draft = seed.account().input().selection().selectedCommit(); var coordinator = new DraftCommitCoordinatorRepository(dsl); // The original Draft Account/World result is stipulated upstream fixture evidence, not a new @@ -222,7 +258,7 @@ private static GameDesignPublicationOperation retain( draft.commitId(), draft.digest(), "ISOLATED-world-applied", - seed.world().appliedResultBytes(), + seedWorld.appliedResultBytes(), epochs); coordinator.markOwnerInProgress(draft, DraftCommitBinding.Owner.WORLD_MANAGEMENT); coordinator.recordOwnerOutcome(draft, outcome); @@ -253,8 +289,11 @@ private static GameDesignPublicationOperation retain( var operation = historicalV1 ? IsolatedPublicationOperationFixtures.historicalV1ForSelection( - selectedBinding, seed.world()) - : IsolatedPublicationOperationFixtures.forSelection(selectedBinding, seed.world()); + selectedBinding, seedWorld) + : selectedFullWorld + ? IsolatedPublicationOperationFixtures.forSelectedFullSelection( + selectedBinding, seedWorld) + : IsolatedPublicationOperationFixtures.forSelection(selectedBinding, seedWorld); var attempt = new PublishAttempt(); attempt.setTenantId(target.gameDesignVersionTenantKey()); attempt.setPublishWorkflowId(operation.workflowId()); diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java index 0554126103..98a856ff30 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java @@ -10,6 +10,7 @@ import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; @@ -39,9 +40,26 @@ public static GameDesignPublicationOperation fresh( return fresh(target, PublishedWorldSelectorFixtures.evidence(target, baseReference)); } + /** Fresh stipulated selected-full fixture; schema 4 is constructed before operation retention. */ + public static GameDesignPublicationOperation freshSelectedFull( + DraftCommitBinding.TargetProof target, String baseReference) throws Exception { + return fresh( + target, + PublishedWorldSelectorFixtures.selectedFullSeed(target, baseReference), + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); + } + private static GameDesignPublicationOperation fresh( DraftCommitBinding.TargetProof target, WorldPublishedStartLocationEvidence seed) throws Exception { + return fresh(target, seed, 3); + } + + private static GameDesignPublicationOperation fresh( + DraftCommitBinding.TargetProof target, + WorldPublishedStartLocationEvidence seed, + int worldDigestSchemaVersion) + throws Exception { var originalDraftAccount = DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); var draft = @@ -110,12 +128,22 @@ private static GameDesignPublicationOperation fresh( draft.digest(), vector, OffsetDateTime.parse("2026-10-07T00:00:00Z"))); - return forSelection(selected, seed); + return selection(selected, seed, false, worldDigestSchemaVersion); } public static GameDesignPublicationOperation forSelection( AuthoredDraftPublishSelectionBinding selected, WorldPublishedStartLocationEvidence seed) { - return selection(selected, seed, false); + return selection(selected, seed, false, 3); + } + + /** Builds a fresh selected-full operation without reinterpreting retained schema-3 history. */ + public static GameDesignPublicationOperation forSelectedFullSelection( + AuthoredDraftPublishSelectionBinding selected, WorldPublishedStartLocationEvidence seed) { + return selection( + selected, + seed, + false, + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); } /** @@ -124,13 +152,14 @@ public static GameDesignPublicationOperation forSelection( */ public static GameDesignPublicationOperation historicalV1ForSelection( AuthoredDraftPublishSelectionBinding selected, WorldPublishedStartLocationEvidence seed) { - return selection(selected, seed, true); + return selection(selected, seed, true, 3); } private static GameDesignPublicationOperation selection( AuthoredDraftPublishSelectionBinding selected, WorldPublishedStartLocationEvidence seed, - boolean historicalV1) { + boolean historicalV1, + int worldDigestSchemaVersion) { var originalDraftAccount = DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); var target = selected.target(); @@ -181,7 +210,7 @@ private static GameDesignPublicationOperation selection( intent.publishRequestId()), draft.commitId().toString(), seed.request().contentDigest(), - 3, + worldDigestSchemaVersion, seed.request().worldAffectedTuples()), seed.selectorReceiptBytes(), seed.originalAccountBindingBytes(), diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java index 277640b137..e6326497ff 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java @@ -39,10 +39,49 @@ private PublishedWorldSelectorFixtures(TargetProof target, String baseReference) this.VERSION_ID = target.canonicalVersionId(); } + /** Rebuilds only the schema field of stipulated test evidence for contract boundary checks. */ + public static WorldPublishedStartLocationEvidence withDigestSchemaVersion( + WorldPublishedStartLocationEvidence base, int digestSchemaVersion) { + var original = base.request(); + var request = + new WorldPublishedStartLocationEvidence.Request( + original.targetNamespace(), + original.canonicalTenantId(), + original.canonicalVersionId(), + original.intakeRequestId(), + original.publicationFence(), + original.publicationRequestId(), + original.requestDigest(), + original.versionStateEpoch(), + original.publishWorkflowId(), + original.appliedCommitId(), + original.contentDigest(), + digestSchemaVersion, + original.worldAffectedTuples()); + return new WorldPublishedStartLocationEvidence( + request, + base.selectorReceiptBytes(), + base.originalAccountBindingBytes(), + base.appliedResultBytes()); + } + public static WorldPublishedStartLocationEvidence evidence(TargetProof target) throws Exception { return new PublishedWorldSelectorFixtures(target).build(); } + /** + * Stipulated fresh selected-full World input; schema 4 is present from its first construction. + * This fixture does not claim that a live World producer computed or authorized the evidence. + */ + public static WorldPublishedStartLocationEvidence selectedFullSeed( + TargetProof target, String baseReference) throws Exception { + net.firedevops.firemud.common.authoring.DraftBaseReference.parse(baseReference); + var fixture = new PublishedWorldSelectorFixtures(target, baseReference); + return fixture.build( + fixture.freshGraphBinding(), + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); + } + public static WorldPublishedStartLocationEvidence evidence( TargetProof target, String baseReference) throws Exception { net.firedevops.firemud.common.authoring.DraftBaseReference.parse(baseReference); @@ -117,6 +156,11 @@ private WorldPublishedStartLocationEvidence build() throws Exception { } private WorldPublishedStartLocationEvidence build(DraftCommitBinding draft) throws Exception { + return build(draft, 3); + } + + private WorldPublishedStartLocationEvidence build( + DraftCommitBinding draft, int attestationSchemaVersion) throws Exception { var terminal = WorldDraftTerminalReadEvidence.Request.create("test", accountBinding(draft)); var result = committedReadback(terminal, true); var applied = JSON.readTree(result.result()); @@ -152,7 +196,7 @@ private WorldPublishedStartLocationEvidence build(DraftCommitBinding draft) thro "publish-workflow", draft.commitId().toString(), "b".repeat(64), - 3, + attestationSchemaVersion, tuples); return new WorldPublishedStartLocationEvidence( request, 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 new file mode 100644 index 0000000000..d8689ca770 --- /dev/null +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java @@ -0,0 +1,1550 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; +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.when; + +import com.google.protobuf.util.JsonFormat; +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 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.SecureRandom; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Date; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedEmptyPublicationDigestGrpcReceiver; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedEmptyPublicationDigestService; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftBaseReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.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.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +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.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeRepository; +import net.firedevops.firemud.entitymanagement.sourceintake.EntitySelectedEmptyPublicationDigestGrpcReceiver; +import net.firedevops.firemud.entitymanagement.sourceintake.EntitySelectedEmptyPublicationDigestService; +import net.firedevops.firemud.gamedesign.client.AutomationScriptingClient; +import net.firedevops.firemud.gamedesign.client.EntityManagementClient; +import net.firedevops.firemud.gamedesign.client.GameLogicClient; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.draft.GameDesignReviewedBaseRepository; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.dto.VersionDto; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptRepository; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationOwner; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociation; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; +import net.firedevops.firemud.gamedesign.service.impl.PublishGateServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.PublishedReleaseBundleServiceImpl; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.gamelogic.service.impl.GameLogicDraftDesignDigestServiceImpl; +import net.firedevops.firemud.gamelogic.service.impl.GameLogicGrpcService; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeRepository; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicPublicationSourceReadService; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.worldmanagement.tenant.WorldSelectedFullPublicationEvidenceFixture; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphDeclaration; +import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphFamilyCount; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceClosureDeclaration; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamily; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamilyCount; +import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; +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.openssl.jcajce.JcaPEMWriter; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.flywaydb.core.Flyway; +import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +/** + * Actual current-default GDS bundle, Entity, Automation, Game Logic, and World owner storage and + * readbacks. Account participation/source inputs, original creator authority, World source + * provenance, Game Logic settlement input, asset manifest, and ephemeral PKI are explicitly + * controlled. This is a component composition proof; it does not establish genuine Account or + * creator authority, registered ingress, or runtime activation/admission/delivery. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class SelectedFullOwnerPublicationPostgresIntegrationTest { + private static final String NAMESPACE = "firemud"; + + @Container + static final PostgreSQLContainer GDS_POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final PostgreSQLContainer WORLD_POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final PostgreSQLContainer ENTITY_POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final PostgreSQLContainer AUTOMATION_POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final PostgreSQLContainer GAME_LOGIC_POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @TempDir Path temporary; + + @Test + void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchemaFourBundle() + throws Exception { + Store gds = store("game-design", "selected_full_gds", GDS_POSTGRES, false); + Store world = store("world-management", "selected_full_world", WORLD_POSTGRES, false); + Store entity = store("entity-management", "selected_full_entity", ENTITY_POSTGRES, true); + Store automation = + store("automation-scripting", "selected_full_automation", AUTOMATION_POSTGRES, true); + Store gameLogic = store("game-logic", "selected_full_gl", GAME_LOGIC_POSTGRES, false); + + Draft draft = createDraft(gds); + var worldSource = registerControlledWorldSource(gds, draft.target()); + DraftCommitBinding commit = selectedCommit(gds, draft.target()); + applyGameDesignCommit(gds, commit); + var worldGraph = + WorldSelectedFullPublicationEvidenceFixture.applyGraph( + world.dsl(), world.transactions(), NAMESPACE, commit, worldSource); + completeGameDesignCommit(gds, commit, worldGraph.applied()); + + String publishRequestId = "selected-full-" + UUID.randomUUID(); + var intent = + new AuthoredDraftPublishSelection.PublishIntent( + draft.target().canonicalTenantId(), + draft.target().canonicalVersionId(), + publishRequestId, + "1", + "controlled selected-full owner composition", + commit.requestId(), + commit.commitId(), + commit.digest()); + var selection = + gds.write() + .execute( + ignored -> + new AuthoredDraftPublishSelectionRepository( + gds.dsl(), new DraftCommitCoordinatorRepository(gds.dsl())) + .reserve(intent) + .selection()); + var worldOwners = + WorldSelectedFullPublicationEvidenceFixture.applyFreezeAndCapture( + world.dsl(), + world.transactions(), + NAMESPACE, + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()), + worldGraph, + SelectedFullOwnerPublicationPostgresIntegrationTest::controlledAccountBinding); + assertThat(worldOwners.selectedWorldDigest().digestSchemaVersion()).isEqualTo(4); + assertThat(worldOwners.appliedResultBytes()).isNotEmpty(); + assertThat(worldOwners.graphBytes()).isNotEmpty(); + assertThat(worldOwners.inventoryEvidence().freezeEvidence()) + .isEqualTo(worldOwners.freezeEvidence()); + + var sourceScopeActor = UUID.randomUUID(); + var entityAuthorization = + selectedOwnerAuthorization(gds, selection, Owner.ENTITY_MANAGEMENT, sourceScopeActor); + var entityWorldRead = + SelectedOwnerWorldInventoryReadEvidence.create( + NAMESPACE, entityAuthorization, worldOwners.freezeEvidence()); + var entityInputs = + new SelectedOwnerEmptySourceInputs( + entityAuthorization, + new SelectedOwnerWorldInventoryReadEvidence( + entityWorldRead, worldOwners.inventoryEvidence())); + var entityRepository = new EntityEmptySelectedSourceIntakeRepository(entity.dsl()); + var entityReceipt = + entityRepository.retainFresh( + entityInputs, + EntityEmptySelectedSourceIntakeReceipt.requestDigest( + NAMESPACE, entityAuthorization, worldOwners.freezeEvidence())); + assertThat( + entityRepository + .read(entityReceipt.targetNamespace(), entityReceipt.intakeRequestId()) + .orElseThrow() + .canonicalBytes()) + .containsExactly(entityReceipt.canonicalBytes()); + assertThat( + entityRepository + .retainFresh( + entityInputs, + EntityEmptySelectedSourceIntakeReceipt.requestDigest( + NAMESPACE, entityAuthorization, worldOwners.freezeEvidence())) + .canonicalBytes()) + .containsExactly(entityReceipt.canonicalBytes()); + + var automationAuthorization = + selectedOwnerAuthorization(gds, selection, Owner.AUTOMATION_SCRIPTING, sourceScopeActor); + var automationWorldRead = + SelectedOwnerWorldInventoryReadEvidence.create( + NAMESPACE, automationAuthorization, worldOwners.freezeEvidence()); + var automationInputs = + new SelectedOwnerEmptySourceInputs( + automationAuthorization, + new SelectedOwnerWorldInventoryReadEvidence( + automationWorldRead, worldOwners.inventoryEvidence())); + var automationRepository = new AutomationEmptySelectedSourceIntakeRepository(automation.dsl()); + var automationReceipt = + automationRepository.retainFresh( + automationInputs, + net.firedevops.firemud.common.automation.sourceintake + .AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + NAMESPACE, automationAuthorization, worldOwners.freezeEvidence())); + assertThat( + automationRepository + .read(automationReceipt.targetNamespace(), automationReceipt.intakeRequestId()) + .orElseThrow() + .canonicalBytes()) + .containsExactly(automationReceipt.canonicalBytes()); + assertThat( + automationRepository + .retainFresh( + automationInputs, + net.firedevops.firemud.common.automation.sourceintake + .AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + NAMESPACE, automationAuthorization, worldOwners.freezeEvidence())) + .canonicalBytes()) + .containsExactly(automationReceipt.canonicalBytes()); + + var synchronizedSources = + new GameDesignSourceRepository(gds.dsl()) + .readSynchronized(draft.target(), commit.commitId()) + .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"); + var gameplaySource = new GameplayRuleSelectedSource(gameplaySnapshot.canonicalJson()); + var glAuthorization = + new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + sourceScopeActor, + gameplaySource, + controlledAccountSources(sourceScopeActor, draft.target().canonicalTenantId())); + var glOperation = new GameLogicGameplayRuleIntakeOperation(NAMESPACE, glAuthorization); + var glTerminal = + GameLogicGameplayRuleIntakeTerminal.retained( + glOperation, + gameplaySource.canonicalBytes(), + gameplaySource.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + var glOwner = new GameLogicGameplayRuleIntakeRepository(gameLogic.dsl()); + gameLogic + .write() + .execute( + ignored -> { + glOwner.lockOperation(glAuthorization.operationId()); + glOwner.insertTerminal(glTerminal); + return null; + }); + var committedGlTerminal = glOwner.findTerminal(glAuthorization.operationId()).orElseThrow(); + assertThat(committedGlTerminal.canonicalBytes()).containsExactly(glTerminal.canonicalBytes()); + + var selectedReceiptRepository = new SelectedDraftGameLogicReceiptRepository(gds.dsl()); + var glReceiptCandidate = + new SelectedDraftGameLogicReceipt( + selection, + glAuthorization, + new AccountGameLogicIntakeSettlementEvidence(committedGlTerminal)); + var glReceipt = + gds.write().execute(ignored -> selectedReceiptRepository.retain(glReceiptCandidate)); + assertThat( + selectedReceiptRepository + .readForPublication( + PublicationDigestRequestBinding.full( + draft.target().canonicalTenantId().toString(), + Long.toString(draft.version().getId()), + publishRequestId)) + .orElseThrow() + .receipt() + .canonicalBytes()) + .containsExactly(glReceipt.receipt().canonicalBytes()); + + var selectionBinding = + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()); + var accountBinding = worldOwners.accountBinding(); + var templateSourceRead = + new SelectedDraftTemplateWorldSourceAssociation.SourceRead( + worldOwners.sourceReadRequest(), worldOwners.sourceReadReceipt()); + var selectedOwnerReservation = + gds.write() + .execute( + ignored -> + new SelectedDraftPublicationOwner(gds.dsl()) + .reserve( + intent, + accountBinding, + worldOwners.startLocationEvidence(), + worldOwners.inventoryEvidence(), + templateSourceRead)); + assertThat(selectedOwnerReservation.selection().canonicalBytes()) + .containsExactly(selectionBinding.canonicalBytes()); + + Long gdsBundleBefore = + gds.dsl() + .fetchSingle( + "SELECT count(*) FROM published_release_bundle WHERE tenant_id = ? AND version_id = ?", + draft.version().getTenantId(), + draft.version().getId()) + .get(0, Long.class); + assertThat(gdsBundleBefore).isZero(); + + ProofPki pki = new ProofPki(temporary.resolve("selected-full-pki")); + Server entityServer = null; + Server automationServer = null; + Server gameLogicServer = null; + Throwable bodyFailure = null; + try { + entityServer = + ownerServer( + pki, + "entity-management-service", + new EntitySelectedEmptyPublicationDigestGrpcReceiver( + new EntitySelectedEmptyPublicationDigestService(NAMESPACE, entityRepository), + NAMESPACE, + new io.micrometer.core.instrument.simple.SimpleMeterRegistry())); + automationServer = + ownerServer( + pki, + "automation-scripting-service", + new AutomationSelectedEmptyPublicationDigestGrpcReceiver( + new AutomationSelectedEmptyPublicationDigestService( + NAMESPACE, automationRepository), + NAMESPACE, + new io.micrometer.core.instrument.simple.SimpleMeterRegistry())); + gameLogicServer = + ownerServer( + pki, + "game-logic-service", + new GameLogicGrpcService( + null, + null, + null, + null, + null, + null, + new GameLogicDraftDesignDigestServiceImpl( + new GameLogicPublicationSourceReadService(glOwner, NAMESPACE)), + null, + new io.micrometer.core.instrument.simple.SimpleMeterRegistry(), + new net.firedevops.firemud.common.security.PublicationReadGuard(NAMESPACE))); + + var endpoints = new ServiceEndpointsProperties(); + endpoints.setEntityManagementService(loopback(entityServer)); + endpoints.setAutomationScriptingService(loopback(automationServer)); + endpoints.setGameLogicService(loopback(gameLogicServer)); + var channelFactory = new GrpcChannelFactory(); + try (var entityClient = + new ReadyEntityManagementClient( + endpoints, pki.client("game-design-service"), channelFactory); + var automationClient = + new ReadyAutomationScriptingClient( + endpoints, pki.client("game-design-service"), channelFactory); + var gameLogicClient = + new ReadyGameLogicClient( + endpoints, pki.client("game-design-service"), channelFactory)) { + ReflectionTestUtils.setField(gameLogicClient, "workloadNamespace", NAMESPACE); + entityClient.connect(); + automationClient.connect(); + gameLogicClient.connect(); + var gate = + new PublishGateServiceImpl( + null, + null, + entityClient, + gameLogicClient, + automationClient, + gds.dsl(), + gds.transactions(), + NAMESPACE); + VersionDto versionDto = versionDto(draft.version()); + var publicationRequest = + PublicationDigestRequestBinding.full( + draft.target().canonicalTenantId().toString(), + Long.toString(draft.version().getId()), + publishRequestId); + var participantDigests = + gate.collectSelectedFullVersionParticipantDigests( + versionDto, publicationRequest, publicationRequest.derivedWorkflowIdentity()); + assertThat(participantDigests) + .extracting(PublishParticipantDigestDto::participantKey) + .containsExactly( + "WORLD_MANAGEMENT", + "ENTITY_MANAGEMENT", + "GAME_LOGIC", + "AUTOMATION_SCRIPTING", + "GAME_DESIGN_CONTROL_PLANE"); + assertThat(participantDigests) + .extracting(PublishParticipantDigestDto::digestSchemaVersion) + .containsExactly(4, 3, 1, 6, 2); + assertThat(participantDigests) + .filteredOn(digest -> "WORLD_MANAGEMENT".equals(digest.participantKey())) + .singleElement() + .satisfies( + digest -> + assertThat(digest.contentDigest()) + .isEqualTo(worldOwners.selectedWorldDigest().contentDigest())); + assertThat(participantDigests) + .filteredOn(digest -> "GAME_LOGIC".equals(digest.participantKey())) + .singleElement() + .satisfies(digest -> assertThat(digest.abilitySchemaDigest()).startsWith("sha256:")); + gate.assertSelectedGatePassed(versionDto, participantDigests); + + var altered = new ArrayList<>(participantDigests); + int automationIndex = 3; + var validAutomation = altered.get(automationIndex); + altered.set( + automationIndex, + new PublishParticipantDigestDto( + validAutomation.participantKey(), + validAutomation.scopeValue(), + validAutomation.baseVersionId(), + validAutomation.appliedCommitId(), + validAutomation.contentDigest(), + 5, + validAutomation.abilitySchemaDigest(), + validAutomation.errorCode(), + validAutomation.errorMessage())); + assertThatThrownBy(() -> gate.assertSelectedGatePassed(versionDto, altered)) + .isInstanceOf(PublishGateFailureException.class) + .satisfies( + failure -> + assertThat(((PublishGateFailureException) failure).failureCode()) + .isEqualTo(PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA)); + + var releaseService = + new PublishedReleaseBundleServiceImpl( + new PublishedReleaseBundleRepository(gds.dsl()), + new VersionRepository(gds.dsl()), + new ObjectMapper()); + var controlledEmptyManifest = controlledEmptyManifest(); + var artifactRepository = + new net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository( + gds.dsl()); + var versions = new VersionRepository(gds.dsl()); + var artifactService = + new net.firedevops.firemud.gamedesign.service.impl.VersionAssetArtifactServiceImpl( + artifactRepository, + null, + versions, + null, + null, + null, + null, + null, + new ObjectMapper()); + var assetPublication = + new net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository( + gds.dsl()); + var exportSnapshot = + gds.write() + .execute( + ignored -> + assetPublication.freezeOrReadSnapshot( + versionDto.tenantId(), versionDto.versionNumber())); + assertThat(exportSnapshot.items()).isEmpty(); + gds.write() + .execute( + ignored -> + artifactService.stageExport( + versionDto.tenantId(), + versionDto.id(), + versionDto.versionNumber(), + publicationRequest.derivedWorkflowIdentity())); + var candidateService = + new net.firedevops.firemud.gamedesign.service.impl + .VersionAssetExportCandidateServiceImpl( + versions, + new GameRepository(gds.dsl()), + new net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository( + gds.dsl()), + artifactRepository, + assetPublication, + gds.transactions(), + new ObjectMapper()); + // Controlled delivery origin and manifest metadata; no object-store or public delivery + // proof. + var candidate = + new net.firedevops.firemud.gamedesign.service.FrozenAssetExportCandidate( + controlledEmptyManifest, "https://controlled.invalid/assets"); + assertThat( + candidateService.recordExportCandidate( + versionDto.tenantId(), versionDto.versionNumber(), candidate)) + .isEqualTo(candidate); + assertThat( + candidateService.readExportCandidate( + versionDto.tenantId(), versionDto.versionNumber())) + .isEqualTo(candidate); + assertThatThrownBy( + () -> + gds.write() + .execute( + ignored -> + releaseService.createFullVersionBundle( + versionDto, + publicationRequest.derivedWorkflowIdentity(), + controlledEmptyManifest, + "controlled-generation-input", + altered, + worldOwners.startLocationEvidence()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Selected-full release requires the exact 4/3/1/6/2"); + assertThat( + gds.dsl() + .fetchSingle( + "SELECT count(*) FROM published_release_bundle WHERE tenant_id = ? AND version_id = ?", + draft.version().getTenantId(), + draft.version().getId()) + .get(0, Long.class)) + .isZero(); + + PublishedReleaseBundleService releaseOwner = releaseService; + var written = + gds.write() + .execute( + ignored -> { + String workflow = publicationRequest.derivedWorkflowIdentity(); + var exported = + artifactService.markExportedUnattested( + versionDto.tenantId(), + versionDto.id(), + versionDto.versionNumber(), + workflow, + controlledEmptyManifest); + var result = + releaseOwner.createFullVersionBundle( + versionDto, + workflow, + controlledEmptyManifest, + "controlled-generation-input", + participantDigests, + worldOwners.startLocationEvidence()); + var version = + versions + .findByTenantIdAndIdForUpdate(versionDto.tenantId(), versionDto.id()) + .orElseThrow(); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch( + Math.addExact(version.getVersionStateEpoch(), 1L)); + versions.save(version); + artifactService.markPublished( + versionDto.tenantId(), + versionDto.id(), + exported.stateEpoch(), + workflow, + controlledEmptyManifest.manifestHash()); + var attempts = + new net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository( + gds.dsl()); + var attempt = + attempts.findByPublishWorkflowIdForUpdate(workflow).orElseThrow(); + attempt.setStatus( + net.firedevops.firemud.gamedesign.model.PublishAttemptStatus.SUCCEEDED); + attempts.save(attempt); + var operation = selectedOwnerReservation.operation(); + new net.firedevops.firemud.gamedesign.publication + .GameDesignPublicationOperationRepository(gds.dsl()) + .seal( + operation.tenantKey(), + workflow, + operation.versionId(), + operation.selectionDigest(), + true); + return result; + }); + assertThat(written.attestationSchemaVersion()).isEqualTo("v4"); + assertThat(written.participantDigests()).containsExactlyElementsOf(participantDigests); + assertThat(written.worldPublishedStartLocationEvidence().canonicalBytes()) + .containsExactly(worldOwners.startLocationEvidence().canonicalBytes()); + String committedBundleRow = bundleOwnerRow(gds, draft.version()); + var independentRead = + new PublishedReleaseBundleServiceImpl( + new PublishedReleaseBundleRepository(gds.dsl()), + new VersionRepository(gds.dsl()), + new ObjectMapper()) + .findPublishedReleaseBundle(draft.version().getTenantId(), draft.version().getId()) + .orElseThrow(); + assertThat(independentRead).isEqualTo(written); + assertThat(independentRead.attestationSchemaVersion()).isEqualTo("v4"); + assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow); + + var replay = + gds.write() + .execute( + ignored -> + releaseOwner.createFullVersionBundle( + versionDto, + publicationRequest.derivedWorkflowIdentity(), + controlledEmptyManifest, + "controlled-generation-input", + participantDigests, + worldOwners.startLocationEvidence())); + assertThat(replay).isEqualTo(written); + assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow); + } + } catch (Exception failure) { + bodyFailure = failure; + throw failure; + } catch (Error failure) { + bodyFailure = failure; + throw failure; + } finally { + stopServers(bodyFailure, entityServer, automationServer, gameLogicServer); + } + } + + @Test + void ownerServerCleanupAttemptsEveryServerAndSuppressesFailuresOnBodyFailure() + throws InterruptedException { + Server entityServer = mock(Server.class); + Server automationServer = mock(Server.class); + Server gameLogicServer = mock(Server.class); + RuntimeException bodyFailure = new IllegalStateException("publication body failed"); + RuntimeException shutdownFailure = new IllegalStateException("entity shutdown failed"); + RuntimeException waitFailure = new IllegalStateException("automation wait failed"); + doThrow(shutdownFailure).when(entityServer).shutdownNow(); + when(entityServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true); + when(automationServer.awaitTermination(5, TimeUnit.SECONDS)).thenThrow(waitFailure); + when(gameLogicServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(false); + + Throwable thrown = + catchThrowable( + () -> { + Throwable primaryFailure = null; + try { + throw bodyFailure; + } catch (RuntimeException failure) { + primaryFailure = failure; + throw failure; + } finally { + stopServers(primaryFailure, entityServer, automationServer, gameLogicServer); + } + }); + + assertThat(thrown).isSameAs(bodyFailure); + assertThat(bodyFailure.getSuppressed()).hasSize(3); + assertThat(bodyFailure.getSuppressed()[0].getCause()).isSameAs(shutdownFailure); + assertThat(bodyFailure.getSuppressed()[1].getCause()).isSameAs(waitFailure); + assertThat(bodyFailure.getSuppressed()[2].getMessage()) + .contains("game logic owner server did not terminate"); + var order = inOrder(entityServer, automationServer, gameLogicServer); + order.verify(entityServer).shutdownNow(); + order.verify(automationServer).shutdownNow(); + order.verify(gameLogicServer).shutdownNow(); + order.verify(entityServer).awaitTermination(5, TimeUnit.SECONDS); + order.verify(automationServer).awaitTermination(5, TimeUnit.SECONDS); + order.verify(gameLogicServer).awaitTermination(5, TimeUnit.SECONDS); + } + + @Test + void ownerServerCleanupFailureFailsWhenPublicationBodySucceeded() throws InterruptedException { + Server entityServer = mock(Server.class); + Server automationServer = mock(Server.class); + Server gameLogicServer = mock(Server.class); + RuntimeException waitFailure = new IllegalStateException("entity wait failed"); + when(entityServer.awaitTermination(5, TimeUnit.SECONDS)).thenThrow(waitFailure); + when(automationServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true); + when(gameLogicServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true); + + assertThatThrownBy(() -> stopServers(null, entityServer, automationServer, gameLogicServer)) + .isInstanceOf(AssertionError.class) + .satisfies( + failure -> { + assertThat(failure.getSuppressed()).hasSize(1); + assertThat(failure.getSuppressed()[0].getCause()).isSameAs(waitFailure); + }); + + verify(entityServer).shutdownNow(); + verify(automationServer).shutdownNow(); + verify(gameLogicServer).shutdownNow(); + verify(entityServer).awaitTermination(5, TimeUnit.SECONDS); + verify(automationServer).awaitTermination(5, TimeUnit.SECONDS); + verify(gameLogicServer).awaitTermination(5, TimeUnit.SECONDS); + } + + @Test + void ownerServerCleanupRestoresInterruptAfterAttemptingAllTerminationWaits() + throws InterruptedException { + Server entityServer = mock(Server.class); + Server automationServer = mock(Server.class); + Server gameLogicServer = mock(Server.class); + InterruptedException interruption = new InterruptedException("entity wait interrupted"); + when(entityServer.awaitTermination(5, TimeUnit.SECONDS)).thenThrow(interruption); + when(automationServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true); + when(gameLogicServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true); + + try { + assertThatThrownBy(() -> stopServers(null, entityServer, automationServer, gameLogicServer)) + .isInstanceOf(AssertionError.class) + .satisfies( + failure -> { + assertThat(failure.getSuppressed()).hasSize(1); + assertThat(failure.getSuppressed()[0].getCause()).isSameAs(interruption); + }); + assertThat(Thread.currentThread().isInterrupted()).isTrue(); + verify(entityServer).awaitTermination(5, TimeUnit.SECONDS); + verify(automationServer).awaitTermination(5, TimeUnit.SECONDS); + verify(gameLogicServer).awaitTermination(5, TimeUnit.SECONDS); + } finally { + Thread.interrupted(); + } + } + + private static Draft createDraft(Store gds) { + Version savedVersion = + gds.write() + .execute( + ignored -> { + Game game = new Game(); + game.setTenantId(UUID.randomUUID().toString()); + game.setName("Controlled selected full owner proof"); + Game savedGame = new GameRepository(gds.dsl()).save(game); + Version version = new Version(); + version.setTenantId(savedGame.getTenantId()); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + return new VersionRepository(gds.dsl()).save(version); + }); + var target = + new TargetProof( + savedVersion.getCanonicalTenantId(), + savedVersion.getCanonicalVersionId(), + savedVersion.getId(), + savedVersion.getTenantId(), + savedVersion.getIdentitySourceGameRowId(), + savedVersion.getIdentitySourceGameTenantKey(), + savedVersion.getIdentitySourceProvenanceKind()); + return new Draft(savedVersion, target); + } + + private static AuthoredWorldSourceEvidence registerControlledWorldSource( + Store gds, TargetProof target) { + var repository = new GameAuthoredWorldSourceRepository(gds.dsl()); + return gds.write() + .execute( + ignored -> + repository.register( + NAMESPACE, + UUID.randomUUID(), + target.canonicalTenantId(), + "controlled-selected-tenant", + "controlled-selected-world", + "Controlled selected World source")); + } + + private static DraftCommitBinding selectedCommit(Store gds, TargetProof target) + 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(); + UUID roomId = UUID.randomUUID(); + var counts = new ArrayList(); + for (var family : + List.of( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING)) { + counts.add( + WorldFreshGraphFamilyCount.newBuilder() + .setFamily(family) + .setCount( + family == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION + || family == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE + || family == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM + ? 1 + : 0) + .build()); + } + var inbound = WorldInboundSourceClosureDeclaration.newBuilder().setSchemaVersion(1); + for (WorldInboundSourceFamily family : + List.of( + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT, + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT, + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION, + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING, + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK, + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE, + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING)) { + inbound.addFamilyCounts( + WorldInboundSourceFamilyCount.newBuilder().setFamily(family).setCount(0)); + } + var declaration = + WorldFreshGraphDeclaration.newBuilder() + .setTenantId(target.canonicalTenantId().toString()) + .setVersionId(target.canonicalVersionId().toString()) + .addAllFamilyCounts(counts) + .setInboundSourceClosure(inbound.build()) + .setStartLocation( + net.firedevops.firemud.worldmanagement.v1.RoomTemplateRef.newBuilder() + .setTenantId(target.canonicalTenantId().toString()) + .setVersionId(target.canonicalVersionId().toString()) + .setRoomTemplateId(roomId.toString())) + .build(); + var mutations = + List.of( + mutation( + commitId, + roomId, + regionId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .setRoom( + RoomDesignMutation.newBuilder() + .setName("Controlled starting room") + .setZoneId(zoneId.toString()) + .setDescription("Controlled World owner input")) + .build(), + mutation( + commitId, + zoneId, + regionId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE) + .setZone( + ZoneDesignMutation.newBuilder() + .setName("Controlled zone") + .setRegionId(regionId.toString())) + .build(), + mutation( + commitId, + regionId, + regionId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setRegion( + RegionDesignMutation.newBuilder() + .setName("Controlled region") + .setWeather("clear") + .setShardId(1)) + .setFreshGraphDeclaration(declaration) + .build()); + + 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\"," + + "\"realmSlug\":\"main\",\"realmDisplayName\":\"Main\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}}"; + revisions.add( + new RevisionPayload( + Integer.toString(revisions.size()), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + policyPayload)); + units.add( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + net.firedevops.firemud.gamedesign.publication.RealmPolicySource.SCOPE, + target.canonicalVersionId().toString(), + net.firedevops.firemud.gamedesign.publication.RealmPolicySource.SCOPE, + "effective", + "0")); + // Authored declarations are content only; each real owner independently proves emptiness. + revisions.add( + new RevisionPayload( + Integer.toString(revisions.size()), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + net.firedevops.firemud.gamedesign.publication.TemplateConfigSource + .ownerInventoryPayload( + Owner.ENTITY_MANAGEMENT, + net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration + .parse(entityInventory())))); + revisions.add( + new RevisionPayload( + Integer.toString(revisions.size()), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + net.firedevops.firemud.gamedesign.publication.TemplateConfigSource + .ownerInventoryPayload( + Owner.AUTOMATION_SCRIPTING, + net.firedevops.firemud.common.automation + .AutomationAuthoredSourceInventoryDeclaration.parse( + automationInventory())))); + units.add( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + net.firedevops.firemud.gamedesign.publication.TemplateConfigSource.SCOPE, + target.canonicalVersionId().toString(), + net.firedevops.firemud.gamedesign.publication.TemplateConfigSource.SCOPE, + net.firedevops.firemud.gamedesign.publication.TemplateConfigSource.SCOPE_ID, + "0")); + for (var mutation : mutations) { + revisions.add( + new RevisionPayload( + Integer.toString(revisions.size()), + UUID.fromString(mutation.getLogicalRevisionId()), + Owner.WORLD_MANAGEMENT, + JsonFormat.printer().omittingInsignificantWhitespace().print(mutation))); + String family = + mutation.getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + family, + mutation.getAggregateId(), + "AGGREGATE", + mutation.getAggregateId(), + "0")); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + family, + mutation.getAggregateId(), + "REGION_SUBTREE", + mutation.getScopeId(), + "0")); + } + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + commitId, + "genesis:" + genesis.policy().receiptId(), + revisions, + units); + } + + private static WorldDesignMutationRevision.Builder mutation( + UUID commitId, UUID aggregateId, UUID regionId, WorldDesignAggregateType aggregateType) { + return WorldDesignMutationRevision.newBuilder() + .setCommitId(commitId.toString()) + .setLogicalRevisionId(UUID.randomUUID().toString()) + .setAggregateId(aggregateId.toString()) + .setAggregateType(aggregateType) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(regionId.toString()); + } + + private static void applyGameDesignCommit(Store gds, DraftCommitBinding binding) { + var coordinator = new DraftCommitCoordinatorRepository(gds.dsl()); + var sources = new GameDesignSourceRepository(gds.dsl()); + gds.write() + .execute( + ignored -> { + var reviewed = + new GameDesignReviewedBaseRepository(gds.dsl()) + .resolve(binding.target(), DraftBaseReference.parse(binding.baseCommitId())); + sources.claimReviewed(binding, reviewed); + coordinator.claimApplicationSlot(binding); + for (Owner owner : binding.requiredOwners()) + coordinator.markOwnerInProgress(binding, owner); + return null; + }); + } + + private static void completeGameDesignCommit( + Store gds, + DraftCommitBinding binding, + net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphAppliedResult worldApplied) { + var coordinator = new DraftCommitCoordinatorRepository(gds.dsl()); + var sources = new GameDesignSourceRepository(gds.dsl()); + var gameDesignApplied = gds.write().execute(ignored -> sources.apply(binding)); + var worldOutcome = + new DraftCommitCoordinatorRepository.OwnerOutcome( + Owner.WORLD_MANAGEMENT, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + worldApplied.resultIdentity(), + worldApplied.canonicalBytes(), + worldApplied.appliedEpochs().stream() + .map( + epoch -> + new DraftCommitCoordinatorRepository.AppliedEpoch( + epoch.aggregateType(), + epoch.aggregateId(), + epoch.scopeType(), + epoch.scopeId(), + epoch.expectedEpoch(), + epoch.resultingEpoch())) + .toList()); + gds.write() + .execute( + ignored -> { + coordinator.recordOwnerOutcome(binding, gameDesignApplied.ownerOutcome()); + coordinator.recordOwnerOutcome(binding, worldOutcome); + List outcomes = + binding.requiredOwners().stream() + .map( + owner -> + owner == Owner.WORLD_MANAGEMENT + ? worldOutcome + : gameDesignApplied.ownerOutcome()) + .toList(); + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .advanceIsolatedSourceVisibility(gds.dsl(), binding, outcomes); + coordinator.releaseApplicationSlot(binding); + return null; + }); + } + + private static AccountPublicationAuthorizationBinding controlledAccountBinding( + AuthoredDraftPublishSelectionBinding selection) { + UUID actor = UUID.randomUUID(); + var input = new AccountPublicationAuthorizationBinding.PreallocationInput(actor, selection); + return new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + input, + controlledAccountSources(actor, selection.intent().canonicalTenantId())); + } + + private static SelectedOwnerIntakeAuthorizationBinding selectedOwnerAuthorization( + Store gds, AuthoredDraftPublishSelection selection, Owner recipient, UUID actor) { + var scope = + new SelectedOwnerIntakeSourceReadScope( + recipient, + NAMESPACE, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + selection.selectedCommit()); + var export = new GameDesignSourceRepository(gds.dsl()).requireSelectedOwnerIntakeSource(scope); + var content = + net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent.fromStored( + export.canonicalBytes(), scope, export.digest()); + return new SelectedOwnerIntakeAuthorizationBinding( + content, controlledAccountSources(actor, selection.target().canonicalTenantId())); + } + + private static List controlledAccountSources( + UUID actor, UUID tenant) { + byte[] evidence = + "TEST_ONLY controlled upstream Account source input".getBytes(StandardCharsets.UTF_8); + return List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + evidence), + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.TENANT, + tenant.toString(), + "1", + "1", + null, + null, + evidence), + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.MEMBERSHIP, + actor + "/" + tenant, + "1", + "1", + null, + null, + evidence), + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.GLOBAL_ROLES, + actor.toString(), + "1", + "1", + null, + null, + evidence)); + } + + private static VersionDto versionDto(Version version) { + return new VersionDto( + version.getId(), + version.getTenantId(), + version.getVersionNumber(), + version.getVersionState(), + version.getVersionStateEpoch(), + version.getScriptPatchVersion(), + version.getBaseVersionId(), + version.isScriptOnly(), + version.getNotes(), + version.getCreatedAt(), + version.getUpdatedAt()); + } + + private static ExportedAssetManifest controlledEmptyManifest() throws Exception { + String hash = + HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-256") + .digest( + "{\"assets\":{},\"schemaVersion\":1}".getBytes(StandardCharsets.UTF_8))); + return new ExportedAssetManifest("sha256:" + hash, 1, List.of(), List.of()); + } + + private static String bundleOwnerRow(Store gds, Version version) { + return gds.dsl() + .fetchSingle( + "SELECT row_to_json(t)::TEXT || ':' || t.xmin::TEXT FROM published_release_bundle t WHERE tenant_id = ? AND version_id = ?", + version.getTenantId(), + version.getId()) + .get(0, String.class); + } + + private static String loopback(Server server) { + return "127.0.0.1:" + server.getPort(); + } + + private static Server ownerServer(ProofPki pki, String service, io.grpc.BindableService handler) + throws Exception { + var identity = pki.server(service); + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()) + .trustManager(pki.ca().toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(handler, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private static void stopServers( + Throwable bodyFailure, Server entityServer, Server automationServer, Server gameLogicServer) { + Server[] servers = {entityServer, automationServer, gameLogicServer}; + String[] serverNames = {"entity", "automation", "game logic"}; + List cleanupFailures = new ArrayList<>(); + boolean interrupted = bodyFailure instanceof InterruptedException; + + for (int index = 0; index < servers.length; index++) { + Server server = servers[index]; + if (server == null) continue; + try { + server.shutdownNow(); + } catch (RuntimeException | Error failure) { + cleanupFailures.add( + new IllegalStateException( + "Failed to request shutdown for " + serverNames[index] + " owner server", failure)); + } + } + + for (int index = 0; index < servers.length; index++) { + Server server = servers[index]; + if (server == null) continue; + try { + if (!server.awaitTermination(5, TimeUnit.SECONDS)) { + cleanupFailures.add( + new IllegalStateException( + serverNames[index] + " owner server did not terminate within 5 seconds")); + } + } catch (InterruptedException failure) { + interrupted = true; + cleanupFailures.add( + new IllegalStateException( + "Interrupted while awaiting " + serverNames[index] + " owner server termination", + failure)); + } catch (RuntimeException | Error failure) { + cleanupFailures.add( + new IllegalStateException( + "Failed while awaiting " + serverNames[index] + " owner server termination", + failure)); + } + } + + if (interrupted) Thread.currentThread().interrupt(); + if (bodyFailure != null) { + cleanupFailures.forEach(bodyFailure::addSuppressed); + } else if (!cleanupFailures.isEmpty()) { + AssertionError aggregate = new AssertionError("Selected-full owner server cleanup failed"); + cleanupFailures.forEach(aggregate::addSuppressed); + throw aggregate; + } + } + + private static Store store( + String service, String schemaPrefix, PostgreSQLContainer postgres, boolean saga) { + String schema = schemaPrefix + "_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + dataSource.setSchema(schema); + String history = "flyway_schema_history_" + service.replace('-', '_'); + var flyway = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(history) + .placeholders(Map.of("serviceSchema", schema)) + .locations(migrationLocation(service)); + if (saga) { + flyway.locations(migrationLocation(service), sagaMigrationLocation()); + } + if ("entity-management".equals(service)) { + flyway + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + } + flyway.load().migrate(); + var manager = new DataSourceTransactionManager(dataSource); + var configuration = new org.jooq.impl.DefaultConfiguration(); + configuration.set(SQLDialect.POSTGRES); + configuration.set( + new org.jooq.impl.DataSourceConnectionProvider( + new TransactionAwareDataSourceProxy(dataSource))); + configuration.set( + new org.springframework.boot.jooq.autoconfigure.SpringTransactionProvider(manager)); + DSLContext dsl = DSL.using(configuration); + return new Store(schema, dsl, manager); + } + + private static String migrationLocation(String service) { + return "filesystem:" + + repositoryRoot() + .resolve("services") + .resolve(service + "-service") + .resolve("src/main/resources/db/migration") + .toAbsolutePath() + .normalize(); + } + + private static String sagaMigrationLocation() { + return "filesystem:" + + repositoryRoot() + .resolve("services/common-saga/src/main/resources/db/migration/saga") + .toAbsolutePath() + .normalize(); + } + + private static Path repositoryRoot() { + Path current = Path.of("").toAbsolutePath(); + while (current != null) { + if (Files.isDirectory(current.resolve("services/game-design-service"))) return current; + current = current.getParent(); + } + throw new IllegalStateException( + "Repository root is unavailable for current-default migrations"); + } + + private record Draft(Version version, TargetProof target) {} + + private record Store(String schema, DSLContext dsl, DataSourceTransactionManager transactions) { + TransactionTemplate write() { + var transaction = new TransactionTemplate(transactions); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return transaction; + } + } + + private static final class ReadyEntityManagementClient extends EntityManagementClient { + ReadyEntityManagementClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels) { + super(endpoints, tls, channels, BlockingGrpcStubCustomizer.noop()); + } + + void connect() throws javax.net.ssl.SSLException, IOException { + initReloadingClient(); + } + } + + private static final class ReadyAutomationScriptingClient extends AutomationScriptingClient { + ReadyAutomationScriptingClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels) { + super(endpoints, tls, channels, BlockingGrpcStubCustomizer.noop()); + } + + void connect() throws javax.net.ssl.SSLException, IOException { + initReloadingClient(); + } + } + + private static final class ReadyGameLogicClient extends GameLogicClient { + ReadyGameLogicClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels) { + super(endpoints, tls, channels, BlockingGrpcStubCustomizer.noop()); + } + + void connect() throws javax.net.ssl.SSLException, IOException { + initReloadingClient(); + } + } + + private static final class ProofPki { + private final Path ca; + private final Map servers = new java.util.HashMap<>(); + private final Map clients = new java.util.HashMap<>(); + + ProofPki(Path root) throws Exception { + Files.createDirectories(root); + KeyPair caKeys = keys(); + var now = java.time.Instant.now(); + var caName = new X500Name("CN=Controlled selected full owner proof CA"); + var caBuilder = + new JcaX509v3CertificateBuilder( + caName, + BigInteger.ONE, + Date.from(now.minusSeconds(60)), + Date.from(now.plusSeconds(3600)), + caName, + caKeys.getPublic()); + caBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); + caBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign)); + X509Certificate certificate = + new JcaX509CertificateConverter() + .getCertificate( + caBuilder.build( + new JcaContentSignerBuilder("SHA256withRSA").build(caKeys.getPrivate()))); + ca = pem(root.resolve("ca.pem"), certificate); + for (String service : + List.of( + "game-design-service", + "entity-management-service", + "automation-scripting-service", + "game-logic-service")) { + servers.put(service, issue(root, service, true, caKeys, certificate)); + clients.put(service, issue(root, service, false, caKeys, certificate)); + } + } + + Path ca() { + return ca; + } + + Identity server(String service) { + return java.util.Objects.requireNonNull(servers.get(service)); + } + + CommonGrpcClientProperties client(String service) { + Identity identity = java.util.Objects.requireNonNull(clients.get(service)); + var properties = new CommonGrpcClientProperties(); + properties.setPlaintext(false); + properties.setCertChain(identity.certificate().toString()); + properties.setPrivateKey(identity.key().toString()); + properties.setCaCert(ca.toString()); + return properties; + } + + private static Identity issue( + Path root, String service, boolean server, KeyPair caKeys, X509Certificate caCertificate) + throws Exception { + KeyPair pair = keys(); + var now = java.time.Instant.now(); + var builder = + new JcaX509v3CertificateBuilder( + caCertificate, + new BigInteger(120, new SecureRandom()), + Date.from(now.minusSeconds(60)), + Date.from(now.plusSeconds(3600)), + new X500Name("CN=" + service), + pair.getPublic()); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false)); + builder.addExtension( + Extension.keyUsage, + false, + new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + server ? KeyPurposeId.id_kp_serverAuth : KeyPurposeId.id_kp_clientAuth)); + builder.addExtension( + Extension.subjectAlternativeName, + false, + new GeneralNames( + new GeneralName[] { + new GeneralName( + GeneralName.uniformResourceIdentifier, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/" + service), + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + })); + X509Certificate cert = + new JcaX509CertificateConverter() + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA").build(caKeys.getPrivate()))); + String prefix = service + (server ? "-server" : "-client"); + return new Identity( + pem(root.resolve(prefix + ".crt"), cert), + pem(root.resolve(prefix + ".key"), pair.getPrivate())); + } + + private static KeyPair keys() throws Exception { + var generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private static Path pem(Path path, Object value) throws Exception { + try (var writer = new JcaPEMWriter(Files.newBufferedWriter(path))) { + writer.writeObject(value); + } + return path; + } + + record Identity(Path certificate, Path key) {} + } + + private static String automationInventory() { + return "{\"schema\":\"automation-authored-source-inventory/v1\"," + + "\"families\":{\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[]," + + "\"SCRIPT_PATCH_SOURCES\":[]}}"; + } + + private static String entityInventory() { + return "{\"schema\":\"entity-authored-source-inventory/v1\"," + + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + "\"ACTOR_BODY_LAYOUT_ASSIGNMENTS\":[],\"ARCHETYPE_ASSIGNMENTS\":[]," + + "\"ARCHETYPE_CONSTRAINTS\":[],\"ARCHETYPE_ROOTS\":[]," + + "\"BALANCE_CURVE_ATTACHMENTS\":[],\"BALANCE_CURVE_ROOTS\":[]," + + "\"BODY_LAYOUT_MEMBERSHIPS\":[],\"BODY_LAYOUT_ROOTS\":[]," + + "\"CRAFTING_INGREDIENT_BINDINGS\":[],\"CRAFTING_RECIPE_RESULT_BINDINGS\":[]," + + "\"CRAFTING_RECIPE_ROOTS\":[],\"EQUIPMENT_ATTACHMENT_RULES\":[]," + + "\"EQUIPMENT_CAPABILITIES\":[],\"EQUIPMENT_COMPATIBILITY_RULES\":[]," + + "\"EQUIPMENT_OCCUPANCY_RULES\":[],\"EQUIPMENT_SLOT_GROUPS\":[]," + + "\"EQUIPMENT_SLOT_ROOTS\":[],\"INBOUND_LOOT_BINDINGS\":[]," + + "\"ITEM_TEMPLATE_ROOTS\":[],\"LOOT_ITEM_MAPPINGS\":[]," + + "\"LOOT_TABLE_ROOTS\":[],\"NPC_TEMPLATE_ROOTS\":[]," + + "\"OTHER_ACTOR_TEMPLATE_ROOTS\":[]}}"; + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepositoryPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepositoryPostgresIntegrationTest.java index b34a1b71cc..ca1ca3488d 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepositoryPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepositoryPostgresIntegrationTest.java @@ -10,6 +10,8 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; @@ -17,10 +19,12 @@ import net.firedevops.firemud.gamedesign.draft.GameDesignReviewedBaseRepository; import net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup; import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.GameAsset; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import net.firedevops.firemud.gamedesign.publication.GameplayRuleSnapshot; import net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.test.TestContainerImages; @@ -29,6 +33,8 @@ import org.jooq.SQLDialect; import org.jooq.impl.DSL; 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; @@ -139,6 +145,263 @@ void rolledBackGameplayWriteLeavesFreshGenesisAndNoStagedOrVisibleHistory() { assertThat(fixture.sql().fetchCount(DSL.table("game_design_gameplay_rule_revision"))).isZero(); } + @Test + void nonemptyReferencedGameplayCatalogSharesAssetOutcomeAndRetainsInheritedSources() { + var fixture = fixture(); + var asset = + fixture + .write() + .execute( + ignored -> { + var value = new GameAsset(); + value.setTenantId(fixture.target().gameDesignVersionTenantKey()); + value.setFileName("catalog-resource.png"); + value.setContentType("image/png"); + value.setData( + "actual catalog asset bytes" + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + return new GameAssetRepository(fixture.sql()).save(value); + }); + var payloads = new java.util.ArrayList<>(gameplayPayloads()); + payloads.add( + AssetSource.upsertPayload( + asset.getId().toString(), asset.getFileName(), AssetSource.Requiredness.REQUIRED)); + var binding = fixture.binding("0", fixture.genesisBase(), payloads.toArray(String[]::new)); + fixture.stage(binding); + fixture.synchronize(binding); + var owner = new GameplayRuleSourceRepository(fixture.sql()); + var snapshot = owner.requireCompleteForGameLogic(fixture.target(), binding.commitId()); + assertThat(snapshot.manifest().families()).hasSize(Family.values().length); + assertThat(snapshot.manifest().families().get(Family.ACTIONS)).hasSize(1); + assertThat(snapshot.manifest().families().get(Family.ABILITIES)).hasSize(1); + assertThat(snapshot.entries()) + .allSatisfy(entry -> assertThat(entry.sourceBinding()).isEqualTo(binding)); + var outcome = fixture.write().execute(ignored -> fixture.sources().apply(binding)); + assertThat(outcome.asset()).isPresent(); + assertThat(outcome.gameplay().orElseThrow().snapshot().canonicalBytes()) + .containsExactly(snapshot.canonicalBytes()); + var independentlyRead = + new GameplayRuleSourceRepository(fixture.sql()) + .requireCompleteForGameLogic(fixture.target(), binding.commitId()); + assertThat(independentlyRead.canonicalBytes()).containsExactly(snapshot.canonicalBytes()); + var disjoint = + fixture.binding( + "1", binding.commitId().toString(), AssetSource.deletePayload(asset.getFileName())); + fixture.stage(disjoint); + fixture.synchronize(disjoint); + var inherited = owner.requireCompleteForGameLogic(fixture.target(), disjoint.commitId()); + assertThat(inherited.sourceEpoch()).isEqualTo("1"); + assertThat(inherited.inheritedCommitId()).isEqualTo(binding.commitId()); + assertThat(inherited.entries()) + .allSatisfy(entry -> assertThat(entry.sourceBinding()).isEqualTo(binding)); + assertThat(inherited.manifest().canonicalBytes()) + .containsExactly(snapshot.manifest().canonicalBytes()); + var deletion = + fixture.binding( + "1", + disjoint.commitId().toString(), + GameplayRuleSource.deletePayload(Family.ABILITIES, "focusAbility"), + GameplayRuleSource.deletePayload(Family.ACTIONS, "focusAction")); + fixture.stage(deletion); + fixture.synchronize(deletion); + var deleted = owner.requireCompleteForGameLogic(fixture.target(), deletion.commitId()); + assertThat(deleted.sourceEpoch()).isEqualTo("2"); + assertThat(deleted.manifest().families().get(Family.ACTIONS)).isEmpty(); + assertThat(deleted.manifest().families().get(Family.ABILITIES)).isEmpty(); + assertThat( + owner.readSnapshot(fixture.target(), binding.commitId()).orElseThrow().canonicalBytes()) + .containsExactly(snapshot.canonicalBytes()); + } + + @Test + void gameplayHandoffDeniesUnqualifiedLegacyEffectiveCommands() { + var fixture = fixture(); + var command = + "{\"schemaVersion\":1,\"commandId\":\"legacy\",\"semanticOwner\":\"GAME_LOGIC\"," + + "\"executionDiscipline\":\"DURABLE_GAMEPLAY\",\"stageRequirement\":\"GAMEPLAY\"," + + "\"promptPolicy\":\"WHEN_GAMEPLAY\",\"actionCategory\":\"GAMEPLAY\",\"historyRecordable\":true," + + "\"aliases\":[],\"actionTags\":[],\"effects\":[]}"; + var binding = fixture.binding("0", fixture.genesisBase(), CommandSource.upsertPayload(command)); + fixture.stage(binding); + fixture.synchronize(binding); + assertThat( + new GameplayRuleSourceRepository(fixture.sql()) + .readSnapshot(binding.target(), binding.commitId())) + .isPresent(); + assertThatThrownBy( + () -> + new GameplayRuleSourceRepository(fixture.sql()) + .requireCompleteForGameLogic(binding.target(), binding.commitId())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("GAMEPLAY_RULE_LEGACY_COMMAND_SOURCE_NOT_CONVERGED"); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void gameplayHandoffDeniesGenericRuleEvenWhenTypedRevisionMatches(boolean legacyBeforeSnapshot) { + var fixture = fixture(); + var binding = + fixture.binding("0", fixture.genesisBase(), gameplayPayloads().toArray(String[]::new)); + var revision = binding.revisions().getFirst(); + if (!legacyBeforeSnapshot) { + fixture.stage(binding); + fixture.synchronize(binding); + } + fixture + .sql() + .execute( + "INSERT INTO revision (tenant_id, version_id, author_account_id, revision_kind, logical_revision_id, data) " + + "VALUES (?, ?, 1, 'GAMEPLAY_RULE', ?, CAST(? AS JSONB))", + fixture.target().gameDesignVersionTenantKey(), + fixture.target().gameDesignVersionRowId(), + revision.revisionId().toString(), + revision.payload()); + var retainedRows = fixture.sql().fetch("SELECT * FROM revision ORDER BY id"); + if (legacyBeforeSnapshot) { + fixture.stage(binding); + fixture.synchronize(binding); + } + var repository = new GameplayRuleSourceRepository(fixture.sql()); + var snapshot = repository.readSnapshot(binding.target(), binding.commitId()).orElseThrow(); + assertThat(snapshot.entries()).isNotEmpty(); + + assertThatThrownBy( + () -> repository.requireCompleteForGameLogic(binding.target(), binding.commitId())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("GAMEPLAY_RULE_GENERIC_SOURCE_NOT_CONVERGED"); + assertThatThrownBy( + () -> + new GameplayRuleSourceRepository(fixture.sql()) + .requireCompleteForGameLogic(binding.target(), binding.commitId())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("GAMEPLAY_RULE_GENERIC_SOURCE_NOT_CONVERGED"); + assertThat(repository.readSnapshot(binding.target(), binding.commitId()).orElseThrow()) + .isEqualTo(snapshot); + assertThat(fixture.sql().fetch("SELECT * FROM revision ORDER BY id")).isEqualTo(retainedRows); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void gameplayHandoffGenericRuleGuardUsesExactPrivateTenantAndVersion(boolean differentTenant) { + var fixture = fixture(); + Version otherVersion = + fixture + .write() + .execute( + ignored -> { + var value = new Version(); + value.setTenantId(fixture.target().gameDesignVersionTenantKey()); + value.setVersionNumber(2); + return new VersionRepository(fixture.sql()).save(value); + }); + String foreignTenant = + fixture + .write() + .execute( + ignored -> { + var value = new Game(); + value.setTenantId("foreign-" + UUID.randomUUID().toString().substring(0, 8)); + value.setName("Controlled foreign legacy history scope"); + return new GameRepository(fixture.sql()).save(value).getTenantId(); + }); + var binding = + fixture.binding("0", fixture.genesisBase(), gameplayPayloads().toArray(String[]::new)); + fixture.stage(binding); + fixture.synchronize(binding); + var repository = new GameplayRuleSourceRepository(fixture.sql()); + var snapshot = repository.requireCompleteForGameLogic(binding.target(), binding.commitId()); + // Generic history has no composite owner FK; scope both private keys even for retained rows. + fixture + .sql() + .execute( + "INSERT INTO revision (tenant_id, version_id, author_account_id, revision_kind, data) " + + "VALUES (?, ?, 1, 'GAMEPLAY_RULE', '{}'::JSONB)", + differentTenant ? foreignTenant : fixture.target().gameDesignVersionTenantKey(), + differentTenant + ? Long.valueOf(fixture.target().gameDesignVersionRowId()) + : otherVersion.getId()); + var retainedRows = fixture.sql().fetch("SELECT * FROM revision ORDER BY id"); + + assertThat(repository.requireCompleteForGameLogic(binding.target(), binding.commitId())) + .isEqualTo(snapshot); + assertThat(fixture.sql().fetch("SELECT * FROM revision ORDER BY id")).isEqualTo(retainedRows); + } + + @Test + void gameplayHandoffCannotClaimEmptyWhileGenericRuleHistoryExists() { + var fixture = fixture(); + var first = fixture.binding("0", fixture.genesisBase(), upsert("10")); + fixture.stage(first); + fixture.synchronize(first); + var binding = + fixture.binding( + "1", + first.commitId().toString(), + GameplayRuleSource.deletePayload(Family.STATS, "strength")); + fixture.stage(binding); + fixture.synchronize(binding); + var repository = new GameplayRuleSourceRepository(fixture.sql()); + assertThat( + repository.requireCompleteForGameLogic(binding.target(), binding.commitId()).entries()) + .isEmpty(); + fixture + .sql() + .execute( + "INSERT INTO revision (tenant_id, version_id, author_account_id, revision_kind, data) " + + "VALUES (?, ?, 1, 'GAMEPLAY_RULE', '{}'::JSONB)", + fixture.target().gameDesignVersionTenantKey(), + fixture.target().gameDesignVersionRowId()); + var retainedRows = fixture.sql().fetch("SELECT * FROM revision ORDER BY id"); + + assertThatThrownBy( + () -> repository.requireCompleteForGameLogic(binding.target(), binding.commitId())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("GAMEPLAY_RULE_GENERIC_SOURCE_NOT_CONVERGED"); + assertThat(fixture.sql().fetch("SELECT * FROM revision ORDER BY id")).isEqualTo(retainedRows); + } + + private List gameplayPayloads() { + var action = + new GameplayRuleManifest.Action( + "focusAction", + "Focus", + List.of("canFocus"), + List.of(), + List.of( + new GameplayRuleManifest.Cost( + "energy", + java.math.BigDecimal.ONE, + GameplayRuleManifest.CommitPolicy.ON_EXECUTION)), + List.of( + new GameplayRuleManifest.Cooldown( + "focusCooldown", 3L, GameplayRuleManifest.CommitPolicy.ON_EFFECT_SUCCESS)), + List.of(new GameplayRuleManifest.EffectBinding("restore", "SOURCE")), + List.of()); + List definitions = + List.of( + new GameplayRuleManifest.AdmissionTag("canFocus"), + new GameplayRuleManifest.Resource( + "energy", + java.math.BigDecimal.TEN, + java.math.BigDecimal.ZERO, + java.math.BigDecimal.TEN, + java.math.BigDecimal.valueOf(100), + GameplayRuleManifest.Visibility.PUBLIC, + List.of()), + new GameplayRuleManifest.Effect( + "restore", + GameplayRuleManifest.Lifecycle.INSTANT, + GameplayRuleManifest.EffectOperation.ADJUST_RESOURCE, + "energy", + null, + java.math.BigDecimal.ONE, + null, + null), + action, + new GameplayRuleManifest.Ability("focusAbility", "Focus ability", "focusAction")); + return definitions.stream().map(GameplayRuleSource::upsertPayload).toList(); + } + private static String upsert(String value) { return upsert("strength", value); } @@ -167,7 +430,11 @@ private static Fixture fixture() { .schemas(schema) .defaultSchema(schema) .placeholders(java.util.Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()) .load() .migrate(); var write = new TransactionTemplate(new DataSourceTransactionManager(data)); @@ -211,23 +478,48 @@ String genesisBase() { return "genesis:" + sources.readGenesis(target).orElseThrow().policy().receiptId(); } - DraftCommitBinding binding(String epoch, String base, String payload) { + DraftCommitBinding binding(String epoch, String base, String... payloads) { + var revisions = new java.util.ArrayList(); + for (int index = 0; index < payloads.length; index++) { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(index), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + payloads[index])); + } + var units = new java.util.ArrayList(); + for (String scope : + List.of(GameplayRuleSource.SCOPE, CommandSource.SCOPE, AssetSource.SCOPE)) { + String kind = + scope.equals(GameplayRuleSource.SCOPE) + ? "GAMEPLAY_RULE" + : scope.equals(CommandSource.SCOPE) ? "COMMAND_DEFINITION" : "ASSET_REFERENCE"; + if (java.util.Arrays.stream(payloads).noneMatch(payload -> payload.contains(kind))) + continue; + String sourceEpoch = epoch; + if (!scope.equals(GameplayRuleSource.SCOPE)) { + String table = + scope.equals(CommandSource.SCOPE) + ? "game_design_command_source_head" + : "game_design_asset_source_head"; + sourceEpoch = + sql.fetchSingle( + "SELECT source_epoch FROM " + table + " WHERE canonical_version_id = ?", + target.canonicalVersionId()) + .get(0, String.class); + } + units.add( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + scope, + target.canonicalVersionId().toString(), + scope, + "effective", + sourceEpoch)); + } return DraftCommitBinding.create( - target, - UUID.randomUUID(), - UUID.randomUUID(), - base, - List.of( - new DraftCommitBinding.RevisionPayload( - "0", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, payload)), - List.of( - new DraftCommitBinding.AffectedUnit( - Owner.GAME_DESIGN_CONTROL_PLANE, - GameplayRuleSource.SCOPE, - target.canonicalVersionId().toString(), - GameplayRuleSource.SCOPE, - GameplayRuleSource.SCOPE_ID, - epoch))); + target, UUID.randomUUID(), UUID.randomUUID(), base, revisions, units); } void stage(DraftCommitBinding binding) { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java index 5028082e1a..ddd732ca20 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java @@ -323,6 +323,25 @@ private static void assertCurrentCaptureReceiptJoin(boolean changeReceiptSource) SelectedGameplayRuleSourceJoin.matches( operationReadback.operation(), gameplayCapture, selectedSnapshot, readback)) .isEqualTo(!changeReceiptSource); + + var digestReader = + new SelectedDraftPublicationDigestReadService( + fixture.dsl(), fixture.transactionManager(), "test"); + if (changeReceiptSource) { + assertThatThrownBy(() -> digestReader.read("test", publicationBinding(readback), readback)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); + } else { + assertThat( + digestReader + .read("test", publicationBinding(readback), readback) + .gameDesignDigest() + .appliedCommitId()) + .isEqualTo(selectedCommit.commitId().toString()); + } } private static SelectedDraftGameLogicReceipt retainCurrentFixtureReceipt( @@ -383,7 +402,8 @@ private static CurrentCaptureFixture currentCaptureFixture() throws Exception { .load() .migrate(); var dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); - var tx = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + var transactionManager = new DataSourceTransactionManager(dataSource); + var tx = new TransactionTemplate(transactionManager); tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); DraftCommitBinding.TargetProof target = @@ -424,7 +444,7 @@ private static CurrentCaptureFixture currentCaptureFixture() throws Exception { "Unable to retain controlled source capture", failure); } }); - return new CurrentCaptureFixture(dsl, tx, target, sources, operation); + return new CurrentCaptureFixture(dsl, tx, transactionManager, target, sources, operation); } private static Fixture fixture(SelectedDraftGameLogicReceipt value) { @@ -620,6 +640,7 @@ private record Fixture(DSLContext dsl, TransactionTemplate tx) {} private record CurrentCaptureFixture( DSLContext dsl, TransactionTemplate tx, + DataSourceTransactionManager transactionManager, DraftCommitBinding.TargetProof target, GameDesignSourceRepository sources, GameDesignPublicationOperation operation) {} 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 437019f04c..b69946852a 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 @@ -2,25 +2,45 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.junit.jupiter.api.Assertions.assertAll; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.security.MessageDigest; +import java.sql.Connection; +import java.util.ArrayList; import java.util.HexFormat; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.authoring.DraftBaseReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.draft.GameDesignReviewedBaseRepository; import net.firedevops.firemud.gamedesign.draft.IsolatedAssetSourceOwnerSetup; +import net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.publication.AssetSourceRepository; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; 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.VersionRepository; +import net.firedevops.firemud.gamedesign.service.impl.VersionAssetPublicationServiceImpl; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; +import org.jooq.ConnectionProvider; import org.jooq.DSLContext; +import org.jooq.ExecuteListener; import org.jooq.SQLDialect; +import org.jooq.conf.Settings; import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; import org.junit.jupiter.api.AfterAll; @@ -30,6 +50,7 @@ import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; class VersionAssetExportSnapshotIntegrationTest { @@ -95,6 +116,264 @@ void freezesOnlyTheSynchronizedAssetProjectionAndDeniesDirectAssociation() { .containsExactly(SOURCE_BYTES); } + @Test + void firstFreezeWithoutEnclosingTransactionRejectsNonemptySelection() throws Exception { + assertUnwrappedFirstFreezeDenied(fixture()); + } + + @Test + void firstFreezeWithoutEnclosingTransactionRejectsFoundedEmptySelection() throws Exception { + assertUnwrappedFirstFreezeDenied(foundedEmptyFixture()); + } + + @Test + void springOwnerCommitsNonemptySnapshotBeforeIndependentReadback() { + Fixture fixture = fixture(); + var service = + new VersionAssetPublicationServiceImpl( + new DataSourceTransactionManager(fixture.dataSource), + new VersionAssetPublicationRepository(fixture.dsl)); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + + var snapshot = service.freezeOrReadSnapshot(fixture.tenantId, 1); + + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(snapshot.items()).hasSize(1); + assertThat(snapshot.items().getFirst().contentDigest()).isEqualTo(sha256(SOURCE_BYTES)); + assertThat(independentSnapshot(fixture)).isEqualTo(snapshot); + assertThat(service.readFrozenAssetBytes(fixture.tenantId, 1, snapshot.items().getFirst())) + .containsExactly(SOURCE_BYTES); + } + + @Test + void springOwnerCommitsFoundedEmptySnapshotBeforeIndependentReadback() { + Fixture fixture = foundedEmptyFixture(); + var service = + new VersionAssetPublicationServiceImpl( + new DataSourceTransactionManager(fixture.dataSource), + new VersionAssetPublicationRepository(fixture.dsl)); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + + var snapshot = service.freezeOrReadSnapshot(fixture.tenantId, 1); + + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(snapshot.items()).isEmpty(); + assertThat(independentSnapshot(fixture)).isEqualTo(snapshot); + } + + @Test + void jooqOwnerCommitsFoundedEmptySnapshotBeforeIndependentReadback() { + Fixture fixture = foundedEmptyFixture(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + + var snapshot = + fixture.dsl.transactionResult( + configuration -> + new VersionAssetPublicationRepository(DSL.using(configuration)) + .freezeOrReadSnapshot(fixture.tenantId, 1)); + + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(snapshot.items()).isEmpty(); + assertThat(independentSnapshot(fixture)).isEqualTo(snapshot); + } + + @Test + void retainsCallerSerializableTransactionAndJooqConfigurationAcrossCompleteFreeze() + throws Exception { + Fixture fixture = fixture(); + var acquired = new AtomicInteger(); + var released = new AtomicInteger(); + var queryConnections = new ArrayList(); + try (var connection = fixture.dataSource.getConnection()) { + connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); + connection.setAutoCommit(false); + var provider = + new ConnectionProvider() { + @Override + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "The isolated provider intentionally lends the caller-owned connection") + public Connection acquire() { + assertThat(acquired.incrementAndGet()).as("one owner connection lease").isEqualTo(1); + return connection; + } + + @Override + public void release(Connection returned) { + assertThat(returned).isSameAs(connection); + released.incrementAndGet(); + } + }; + var listener = + ExecuteListener.onExecuteStart( + context -> { + queryConnections.add(context.connection()); + assertThat(context.configuration().dialect()).isEqualTo(SQLDialect.POSTGRES); + assertThat(context.configuration().settings().isRenderFormatted()).isTrue(); + assertThat(context.configuration().data("asset-freeze-proof")) + .isEqualTo("caller-configuration"); + }); + var configuration = + fixture + .dsl + .configuration() + .derive(provider) + .derive(new Settings().withRenderFormatted(true)) + .derive(listener); + configuration.data("asset-freeze-proof", "caller-configuration"); + + var snapshot = + new VersionAssetPublicationRepository(DSL.using(configuration)) + .freezeOrReadSnapshot(fixture.tenantId, 1); + + assertThat(snapshot.items()).hasSize(1); + assertThat(snapshot.items().getFirst().contentDigest()).isEqualTo(sha256(SOURCE_BYTES)); + assertThat(queryConnections).isNotEmpty(); + for (Connection queryConnection : queryConnections) { + assertThat(queryConnection.unwrap(Connection.class)).isSameAs(connection); + } + assertThat(acquired).hasValue(1); + assertThat(released).hasValue(1); + assertThat(connection.isClosed()).isFalse(); + assertThat(connection.getAutoCommit()).isFalse(); + assertThat(connection.getTransactionIsolation()) + .isEqualTo(Connection.TRANSACTION_SERIALIZABLE); + assertThatThrownBy(() -> independentSnapshot(fixture)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("No durable frozen Version asset snapshot exists"); + connection.rollback(); + } + DSLContext independent = DSL.using(fixture.dataSource, SQLDialect.POSTGRES); + assertThat(independent.fetchCount(DSL.table("version_asset_export_snapshot"))).isZero(); + assertThat(independent.fetchCount(DSL.table("version_asset_export_item"))).isZero(); + } + + @Test + void readsExistingSnapshotInCallerReadOnlyTransaction() throws Exception { + Fixture fixture = fixture(); + var frozen = + fixture.dsl.transactionResult( + configuration -> + new VersionAssetPublicationRepository(DSL.using(configuration)) + .freezeOrReadSnapshot(fixture.tenantId, 1)); + + try (var connection = fixture.dataSource.getConnection()) { + connection.setReadOnly(true); + connection.setAutoCommit(false); + var readback = + new VersionAssetPublicationRepository( + DSL.using(fixture.dsl.configuration().derive(connection))) + .freezeOrReadSnapshot(fixture.tenantId, 1); + + assertThat(readback).isEqualTo(frozen); + assertThat(connection.isReadOnly()).isTrue(); + assertThat(connection.getAutoCommit()).isFalse(); + connection.rollback(); + } + assertThat(independentSnapshot(fixture)).isEqualTo(frozen); + } + + private static void assertUnwrappedFirstFreezeDenied(Fixture fixture) throws Exception { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + try (var connection = fixture.dataSource.getConnection()) { + assertThat(connection.getAutoCommit()).isTrue(); + } + DSLContext independent = DSL.using(fixture.dataSource, SQLDialect.POSTGRES); + assertThat(independent.fetchCount(DSL.table("version_asset_export_snapshot"))).isZero(); + assertThat(independent.fetchCount(DSL.table("version_asset_export_item"))).isZero(); + var queries = new AtomicInteger(); + var observed = + DSL.using( + fixture + .dsl + .configuration() + .derive(ExecuteListener.onExecuteStart(context -> queries.incrementAndGet()))); + + Throwable failure = + catchThrowable( + () -> + new VersionAssetPublicationRepository(observed) + .freezeOrReadSnapshot(fixture.tenantId, 1)); + + assertAll( + "An unwrapped first freeze must fail without committing snapshot rows", + () -> + assertThat(failure) + .as("unwrapped first-freeze failure") + .isInstanceOf(IllegalStateException.class) + .hasMessage("Version asset snapshot requires an enclosing owner transaction"), + () -> assertThat(queries).as("SQL before transaction entry refusal").hasValue(0), + () -> + assertThat(independent.fetchCount(DSL.table("version_asset_export_snapshot"))) + .as("independently committed snapshot headers") + .isZero(), + () -> + assertThat(independent.fetchCount(DSL.table("version_asset_export_item"))) + .as("independently committed snapshot items") + .isZero()); + } + + private static VersionAssetPublicationRepository.ExportSnapshot independentSnapshot( + Fixture fixture) { + return new VersionAssetPublicationRepository(DSL.using(fixture.dataSource, SQLDialect.POSTGRES)) + .readFrozenSnapshot(fixture.tenantId, 1); + } + + private Fixture foundedEmptyFixture() { + Fixture fixture = fixture(); + var write = new TransactionTemplate(new DataSourceTransactionManager(fixture.dataSource)); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + write.executeWithoutResult( + status -> { + var selection = + new AssetSourceRepository(fixture.dsl) + .requireExportSelection(fixture.tenantId, fixture.versionId); + var target = selection.binding().target(); + var deletion = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + selection.binding().commitId().toString(), + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.deletePayload(USAGE_KEY))), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.SCOPE, + target.canonicalVersionId().toString(), + AssetSource.SCOPE, + AssetSource.SCOPE_ID, + selection.sourceEpoch()))); + var sources = new GameDesignSourceRepository(fixture.dsl); + sources.claimReviewed( + deletion, + new GameDesignReviewedBaseRepository(fixture.dsl) + .resolve(target, DraftBaseReference.parse(deletion.baseCommitId()))); + var coordinator = new DraftCommitCoordinatorRepository(fixture.dsl); + coordinator.claimApplicationSlot(deletion); + coordinator.markOwnerInProgress(deletion, Owner.GAME_DESIGN_CONTROL_PLANE); + var result = sources.apply(deletion); + IsolatedPublicationOwnerSetup.advanceIsolatedSourceVisibility( + fixture.dsl, deletion, List.of(result.ownerOutcome())); + sources.captureSynchronized(deletion); + coordinator.releaseApplicationSlot(deletion); + }); + // This is a real reviewed source deletion and synchronized projection, not missing history. + assertThat( + new AssetSourceRepository(fixture.dsl) + .requireExportSelection(fixture.tenantId, fixture.versionId) + .items()) + .isEmpty(); + assertThat(fixture.dsl.fetchCount(DSL.table("version_asset"))).isZero(); + return fixture; + } + @Test void rejectsRenamingSynchronizedSourceBeforePersistingSnapshot() { Fixture fixture = fixture(); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionCanonicalIdentityIntegrationTest.java new file mode 100644 index 0000000000..2000df083d --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionCanonicalIdentityIntegrationTest.java @@ -0,0 +1,515 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +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 net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +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.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.SQLDialect; +import org.jooq.Table; +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.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class VersionCanonicalIdentityIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final MigrationVersion V35 = MigrationVersion.fromVersion("35"); + private static final Table VERSION = DSL.table(DSL.name("version")); + private static final Field ID = DSL.field(DSL.name("id"), Long.class); + private static final Field TENANT_ID = DSL.field(DSL.name("tenant_id"), String.class); + private static final Field VERSION_NUMBER = + DSL.field(DSL.name("version_number"), Integer.class); + private static final Field VERSION_STATE = + DSL.field(DSL.name("version_state"), String.class); + private static final Field VERSION_STATE_EPOCH = + DSL.field(DSL.name("version_state_epoch"), Long.class); + private static final Field SCRIPT_PATCH_VERSION = + DSL.field(DSL.name("script_patch_version"), String.class); + private static final Field BASE_VERSION_ID = + DSL.field(DSL.name("base_version_id"), Long.class); + private static final Field IS_SCRIPT_ONLY = + DSL.field(DSL.name("is_script_only"), Boolean.class); + private static final Field NOTES = DSL.field(DSL.name("notes"), String.class); + private static final Field CREATED_AT = + DSL.field(DSL.name("created_at"), java.sql.Timestamp.class); + private static final Field UPDATED_AT = + DSL.field(DSL.name("updated_at"), java.sql.Timestamp.class); + private static final Field CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field IDENTITY_SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("identity_source_game_row_id"), Long.class); + private static final Field IDENTITY_SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("identity_source_game_tenant_key"), String.class); + private static final Field IDENTITY_SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("identity_source_provenance_kind"), String.class); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void v35_1PreservesRetainedVersionHistoryAndLeavesIdentityUnmapped() { + Fixture fixture = fixture(V35); + Game game = saveGame(fixture, "retained-version-source"); + Long retainedVersionId = insertRetainedVersion(fixture.dsl(), game.getTenantId()); + Map retainedFieldsBefore = retainedFields(fixture.dsl(), retainedVersionId); + String retainedXminBefore = versionXmin(fixture.dsl(), retainedVersionId); + + migrate(fixture.dataSource(), fixture.schema(), null); + + assertThat(retainedFields(fixture.dsl(), retainedVersionId)).isEqualTo(retainedFieldsBefore); + assertThat(versionXmin(fixture.dsl(), retainedVersionId)).isEqualTo(retainedXminBefore); + assertThat( + fixture + .dsl() + .select(CANONICAL_VERSION_ID) + .from(VERSION) + .where(ID.eq(retainedVersionId)) + .fetchOne(CANONICAL_VERSION_ID)) + .isNull(); + assertThat( + fixture + .dsl() + .select(CANONICAL_TENANT_ID) + .from(VERSION) + .where(ID.eq(retainedVersionId)) + .fetchOne(CANONICAL_TENANT_ID)) + .isNull(); + assertThat( + fixture + .dsl() + .select(IDENTITY_SOURCE_GAME_ROW_ID) + .from(VERSION) + .where(ID.eq(retainedVersionId)) + .fetchOne(IDENTITY_SOURCE_GAME_ROW_ID)) + .isNull(); + assertThat( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + game.getCanonicalTenantId(), UUID.randomUUID())) + .isEmpty(); + + assertThatThrownBy( + () -> + fixture + .dsl() + .update(VERSION) + .set(CANONICAL_VERSION_ID, UUID.randomUUID()) + .set(CANONICAL_TENANT_ID, game.getCanonicalTenantId()) + .set(IDENTITY_SOURCE_GAME_ROW_ID, game.getId()) + .set(IDENTITY_SOURCE_GAME_TENANT_KEY, game.getTenantId()) + .set(IDENTITY_SOURCE_PROVENANCE_KIND, "NEW_GAME_ROW") + .where(ID.eq(retainedVersionId)) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("retained Version rows cannot be assigned a canonical identity"); + } + + @Test + void savePersistsAndReadsBackFreshCanonicalIdentityAcrossUpdate() { + Fixture fixture = fixture(null); + Game game = saveGame(fixture, "fresh-version-source"); + + Version inserted = + fixture + .transactionTemplate() + .execute(status -> fixture.versionRepository().save(version(game))); + assertThat(inserted).isNotNull(); + assertThat(inserted.getCanonicalVersionId()).isNotNull().isNotEqualTo(NIL_UUID); + assertThat(inserted.getCanonicalTenantId()).isEqualTo(game.getCanonicalTenantId()); + assertThat(inserted.getIdentitySourceGameRowId()).isEqualTo(game.getId()); + assertThat(inserted.getIdentitySourceGameTenantKey()).isEqualTo(game.getTenantId()); + assertThat(inserted.getIdentitySourceProvenanceKind()).isEqualTo("NEW_GAME_ROW"); + + Version exactRead = + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + game.getCanonicalTenantId(), inserted.getCanonicalVersionId()) + .orElseThrow(); + assertIdentityMatches(exactRead, game, inserted.getCanonicalVersionId()); + assertIdentityMatches( + fixture.versionRepository().findById(inserted.getId()).orElseThrow(), + game, + inserted.getCanonicalVersionId()); + + inserted.setNotes("updated without replacing owner identity"); + Version updated = + fixture.transactionTemplate().execute(status -> fixture.versionRepository().save(inserted)); + assertThat(updated).isNotNull(); + assertThat(updated.getNotes()).isEqualTo("updated without replacing owner identity"); + assertIdentityMatches(updated, game, inserted.getCanonicalVersionId()); + assertIdentityMatches( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + game.getCanonicalTenantId(), inserted.getCanonicalVersionId()) + .orElseThrow(), + game, + inserted.getCanonicalVersionId()); + } + + @Test + void newVersionIdentityUsesExactRetainedGameSourceProvenance() { + Fixture fixture = fixtureWithRetainedGame(); + Game retainedGame = fixture.gameRepository().findByTenantId("retained-version-game-source"); + assertThat(retainedGame).isNotNull(); + + Version saved = + fixture + .transactionTemplate() + .execute(status -> fixture.versionRepository().save(version(retainedGame))); + + assertThat(saved).isNotNull(); + assertThat(saved.getCanonicalVersionId()).isNotNull().isNotEqualTo(NIL_UUID); + assertThat(saved.getIdentitySourceProvenanceKind()).isEqualTo("RETAINED_GAME_V29"); + assertIdentityMatches( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + retainedGame.getCanonicalTenantId(), saved.getCanonicalVersionId()) + .orElseThrow(), + retainedGame, + saved.getCanonicalVersionId(), + "RETAINED_GAME_V29"); + } + + @Test + void canonicalLookupRejectsWrongTenantMissingAndNilIdsWithoutMutation() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "lookup-version-owner"); + Game other = saveGame(fixture, "lookup-version-other"); + Version saved = + fixture + .transactionTemplate() + .execute(status -> fixture.versionRepository().save(version(owner))); + assertThat(saved).isNotNull(); + String versionXminBefore = versionXmin(fixture.dsl(), saved.getId()); + String ownerXminBefore = gameXmin(fixture.dsl(), owner.getId()); + String otherXminBefore = gameXmin(fixture.dsl(), other.getId()); + + assertThat( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + other.getCanonicalTenantId(), saved.getCanonicalVersionId())) + .isEmpty(); + assertThat( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + owner.getCanonicalTenantId(), UUID.randomUUID())) + .isEmpty(); + assertThat( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId(owner.getCanonicalTenantId(), null)) + .isEmpty(); + assertThat( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId(null, saved.getCanonicalVersionId())) + .isEmpty(); + assertThat( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + NIL_UUID, saved.getCanonicalVersionId())) + .isEmpty(); + assertThat( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + owner.getCanonicalTenantId(), NIL_UUID)) + .isEmpty(); + assertIdentityMatches( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + owner.getCanonicalTenantId(), saved.getCanonicalVersionId()) + .orElseThrow(), + owner, + saved.getCanonicalVersionId()); + + assertThat(versionXmin(fixture.dsl(), saved.getId())).isEqualTo(versionXminBefore); + assertThat(gameXmin(fixture.dsl(), owner.getId())).isEqualTo(ownerXminBefore); + assertThat(gameXmin(fixture.dsl(), other.getId())).isEqualTo(otherXminBefore); + } + + @Test + void databaseRejectsIdentityMutationNilIdentityAndMismatchedSource() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "mutation-version-owner"); + Game other = saveGame(fixture, "mutation-version-other"); + Version saved = + fixture + .transactionTemplate() + .execute(status -> fixture.versionRepository().save(version(owner))); + assertThat(saved).isNotNull(); + + assertThatThrownBy( + () -> + fixture + .dsl() + .update(VERSION) + .set(CANONICAL_VERSION_ID, UUID.randomUUID()) + .where(ID.eq(saved.getId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("canonical Version identity and its tenant source are immutable"); + assertThatThrownBy( + () -> fixture.dsl().deleteFrom(VERSION).where(ID.eq(saved.getId())).execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("canonical Version identity is immutable"); + + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "INSERT INTO version (tenant_id, version_number, version_state, " + + "version_state_epoch, canonical_version_id, canonical_tenant_id, " + + "identity_source_game_row_id, identity_source_game_tenant_key, " + + "identity_source_provenance_kind) " + + "VALUES (?, 2, 'DRAFT', 1, ?, ?, ?, ?, ?)", + owner.getTenantId(), + NIL_UUID, + owner.getCanonicalTenantId(), + owner.getId(), + owner.getTenantId(), + "NEW_GAME_ROW")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("chk_version_canonical_identity_shape"); + + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "INSERT INTO version (tenant_id, version_number, version_state, " + + "version_state_epoch, canonical_version_id, canonical_tenant_id, " + + "identity_source_game_row_id, identity_source_game_tenant_key, " + + "identity_source_provenance_kind) " + + "VALUES (?, 3, 'DRAFT', 1, ?, ?, ?, ?, ?)", + owner.getTenantId(), + UUID.randomUUID(), + owner.getCanonicalTenantId(), + other.getId(), + other.getTenantId(), + "NEW_GAME_ROW")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining( + "canonical Version identity source does not match its exact game row"); + + Version wrongTenantAlias = version(owner); + wrongTenantAlias.setTenantId(owner.getCanonicalTenantId().toString()); + assertThatThrownBy( + () -> + fixture + .transactionTemplate() + .execute(status -> fixture.versionRepository().save(wrongTenantAlias))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no exact Game Design source row"); + } + + @Test + void canonicalIdentityRejectsTruncateWhileUnmappedRetainedVersionRemainsDeletable() { + Fixture mappedFixture = fixture(null); + Game mappedGame = saveGame(mappedFixture, "truncate-version-owner"); + Version mapped = + mappedFixture + .transactionTemplate() + .execute(status -> mappedFixture.versionRepository().save(version(mappedGame))); + assertThat(mapped).isNotNull(); + + assertThatThrownBy(() -> mappedFixture.dsl().execute("TRUNCATE TABLE version CASCADE")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("canonical Version identities cannot be truncated"); + + Fixture retainedFixture = fixture(V35); + Game retainedGame = saveGame(retainedFixture, "delete-retained-version-owner"); + Long retainedVersionId = + insertRetainedVersion(retainedFixture.dsl(), retainedGame.getTenantId()); + migrate(retainedFixture.dataSource(), retainedFixture.schema(), null); + assertThat(retainedFixture.dsl().deleteFrom(VERSION).where(ID.eq(retainedVersionId)).execute()) + .isEqualTo(1); + } + + private Fixture fixture(MigrationVersion target) { + String schema = "game_design_version_identity_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, target); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + transactionTemplate.setIsolationLevel( + org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); + GameRepository gameRepository = new GameRepository(dsl); + VersionRepository versionRepository = new VersionRepository(dsl); + return new Fixture( + schema, dataSource, dsl, gameRepository, versionRepository, transactionTemplate); + } + + private Fixture fixtureWithRetainedGame() { + String schema = "gd_retained_version_identity_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("28")); + DSLContext legacyDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + legacyDsl.execute( + "INSERT INTO game (tenant_id, name, description) VALUES (?, ?, ?)", + "retained-version-game-source", + "Retained Version Source", + "Source row predating canonical tenant identity"); + migrate(dataSource, schema, null); + return fixtureFromMigratedSchema(schema, dataSource); + } + + private Fixture fixtureFromMigratedSchema(String schema, DriverManagerDataSource dataSource) { + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + transactionTemplate.setIsolationLevel( + org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); + GameRepository gameRepository = new GameRepository(dsl); + VersionRepository versionRepository = new VersionRepository(dsl); + return new Fixture( + schema, dataSource, dsl, gameRepository, versionRepository, transactionTemplate); + } + + 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, MigrationVersion target) { + var configuration = + 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()); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private Game saveGame(Fixture fixture, String tenantKey) { + Game game = new Game(); + game.setTenantId(tenantKey); + game.setName("Version Identity Owner"); + game.setDescription("Source row for canonical Version identity"); + return fixture.transactionTemplate().execute(status -> fixture.gameRepository().save(game)); + } + + private Long insertRetainedVersion(DSLContext dsl, String tenantId) { + return dsl.resultQuery( + "INSERT INTO version (tenant_id, version_number, version_state, version_state_epoch, " + + "script_patch_version, base_version_id, is_script_only, notes) " + + "VALUES (?, 4, 'FAILED', 3, NULL, NULL, FALSE, 'retained history') RETURNING id", + tenantId) + .fetchOne(0, Long.class); + } + + private Map retainedFields(DSLContext dsl, Long versionId) { + return dsl.select( + ID, + TENANT_ID, + VERSION_NUMBER, + VERSION_STATE, + VERSION_STATE_EPOCH, + SCRIPT_PATCH_VERSION, + BASE_VERSION_ID, + IS_SCRIPT_ONLY, + NOTES, + CREATED_AT, + UPDATED_AT) + .from(VERSION) + .where(ID.eq(versionId)) + .fetchSingle() + .intoMap(); + } + + private String versionXmin(DSLContext dsl, Long versionId) { + var row = + Objects.requireNonNull( + dsl.fetchOne("SELECT xmin::text AS xmin FROM version WHERE id = ?", versionId), + "Version xmin query returned no row"); + return Objects.requireNonNull( + row.get("xmin", String.class), "Version xmin readback returned null"); + } + + private String gameXmin(DSLContext dsl, Long gameId) { + var row = + Objects.requireNonNull( + dsl.fetchOne("SELECT xmin::text AS xmin FROM game WHERE id = ?", gameId), + "Game xmin query returned no row"); + return Objects.requireNonNull( + row.get("xmin", String.class), "Game xmin readback returned null"); + } + + private Version version(Game game) { + Version version = new Version(); + version.setTenantId(game.getTenantId()); + version.setVersionNumber(1); + version.setNotes("fresh version"); + return version; + } + + private void assertIdentityMatches(Version version, Game game, UUID canonicalVersionId) { + assertIdentityMatches(version, game, canonicalVersionId, "NEW_GAME_ROW"); + } + + private void assertIdentityMatches( + Version version, Game game, UUID canonicalVersionId, String provenanceKind) { + assertThat(version.getTenantId()).isEqualTo(game.getTenantId()); + assertThat(version.getCanonicalVersionId()).isEqualTo(canonicalVersionId); + assertThat(version.getCanonicalTenantId()).isEqualTo(game.getCanonicalTenantId()); + assertThat(version.getIdentitySourceGameRowId()).isEqualTo(game.getId()); + assertThat(version.getIdentitySourceGameTenantKey()).isEqualTo(game.getTenantId()); + assertThat(version.getIdentitySourceProvenanceKind()).isEqualTo(provenanceKind); + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + GameRepository gameRepository, + VersionRepository versionRepository, + TransactionTemplate transactionTemplate) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index b6e370c341..e31f1ea2a5 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -133,6 +133,119 @@ static void configure(DynamicPropertyRegistry registry) { @MockitoSpyBean private RecordedParticipantDigestService recordedParticipantDigestService; @MockitoSpyBean private VersionAssetArtifactService versionAssetArtifactService; + @Test + void publishAttemptSaveUsesRevisionCasAndRejectsStaleAndTerminalUpdates() { + String tenantId = isolatedTenantId(); + Game game = new Game(); + game.setTenantId(tenantId); + game.setName("publish-attempt-revision-proof-game"); + gameRepository.save(game); + + Version version = new Version(); + version.setTenantId(tenantId); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + Version savedVersion = versionRepository.save(version); + + PublishAttempt attempt = new PublishAttempt(); + attempt.setTenantId(tenantId); + attempt.setPublishWorkflowId("publish-attempt-revision-cas-integration-test"); + attempt.setPublishType(PublishType.FULL_VERSION); + attempt.setVersionId(savedVersion.getId()); + attempt.setVersionNumber(savedVersion.getVersionNumber()); + PublishAttempt inserted = publishAttemptRepository.save(attempt); + assertThat(inserted).isNotNull(); + assertThat(inserted.getId()).isNotNull(); + assertThat(inserted.getRevision()).isEqualTo(1L); + assertThat(inserted.getTenantId()).isEqualTo(tenantId); + assertThat(inserted.getPublishWorkflowId()).isEqualTo(attempt.getPublishWorkflowId()); + assertThat(inserted.getVersionId()).isEqualTo(savedVersion.getId()); + assertThat(inserted.getStatus()).isEqualTo(PublishAttemptStatus.PENDING); + PublishAttempt insertedReadback = + publishAttemptRepository + .findByPublishWorkflowId(attempt.getPublishWorkflowId()) + .orElseThrow(); + assertThat(insertedReadback.getId()).isEqualTo(inserted.getId()); + assertThat(insertedReadback.getRevision()).isEqualTo(1L); + assertThat(insertedReadback.getTenantId()).isEqualTo(tenantId); + assertThat(insertedReadback.getVersionId()).isEqualTo(savedVersion.getId()); + assertThat(insertedReadback.getStatus()).isEqualTo(PublishAttemptStatus.PENDING); + + PublishAttempt firstWriter = + publishAttemptRepository + .findByPublishWorkflowId(attempt.getPublishWorkflowId()) + .orElseThrow(); + PublishAttempt staleWriter = + publishAttemptRepository + .findByPublishWorkflowId(attempt.getPublishWorkflowId()) + .orElseThrow(); + firstWriter.setFailureMessage("first revision writer"); + firstWriter = publishAttemptRepository.save(firstWriter); + assertThat(firstWriter.getId()).isEqualTo(inserted.getId()); + assertThat(firstWriter.getRevision()).isEqualTo(2L); + assertThat(firstWriter.getStatus()).isEqualTo(PublishAttemptStatus.PENDING); + assertThat(firstWriter.getFailureMessage()).isEqualTo("first revision writer"); + + var beforeStaleWrite = + dsl.fetchSingle( + "SELECT *, xmin::text AS xmin FROM publish_attempt WHERE id = ?", inserted.getId()) + .intoMap(); + staleWriter.setFailureMessage("stale revision writer"); + assertThatThrownBy(() -> publishAttemptRepository.save(staleWriter)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("PUBLISH_ATTEMPT_CAS_CONFLICT"); + assertThat( + dsl.fetchSingle( + "SELECT *, xmin::text AS xmin FROM publish_attempt WHERE id = ?", + inserted.getId()) + .intoMap()) + .isEqualTo(beforeStaleWrite); + PublishAttempt afterStaleWrite = + publishAttemptRepository + .findByPublishWorkflowId(attempt.getPublishWorkflowId()) + .orElseThrow(); + assertThat(afterStaleWrite.getId()).isEqualTo(inserted.getId()); + assertThat(afterStaleWrite.getRevision()).isEqualTo(2L); + assertThat(afterStaleWrite.getStatus()).isEqualTo(PublishAttemptStatus.PENDING); + assertThat(afterStaleWrite.getFailureMessage()).isEqualTo("first revision writer"); + assertThat(afterStaleWrite.getFailureCode()).isNull(); + assertThat(afterStaleWrite.getCompletedAt()).isNull(); + + afterStaleWrite.setStatus(PublishAttemptStatus.FAILED); + afterStaleWrite.setFailureCode("terminal-revision-proof"); + afterStaleWrite.setCompletedAt(LocalDateTime.now()); + PublishAttempt terminal = publishAttemptRepository.save(afterStaleWrite); + assertThat(terminal.getId()).isEqualTo(inserted.getId()); + assertThat(terminal.getRevision()).isEqualTo(3L); + assertThat(terminal.getStatus()).isEqualTo(PublishAttemptStatus.FAILED); + assertThat(terminal.getFailureMessage()).isEqualTo("first revision writer"); + assertThat(terminal.getFailureCode()).isEqualTo("terminal-revision-proof"); + var beforeTerminalWrite = + dsl.fetchSingle( + "SELECT *, xmin::text AS xmin FROM publish_attempt WHERE id = ?", terminal.getId()) + .intoMap(); + terminal.setFailureMessage("terminal rows cannot be rewritten"); + assertThatThrownBy(() -> publishAttemptRepository.save(terminal)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("PUBLISH_ATTEMPT_CAS_CONFLICT"); + assertThat( + dsl.fetchSingle( + "SELECT *, xmin::text AS xmin FROM publish_attempt WHERE id = ?", + terminal.getId()) + .intoMap()) + .isEqualTo(beforeTerminalWrite); + PublishAttempt afterTerminalWrite = + publishAttemptRepository + .findByPublishWorkflowId(attempt.getPublishWorkflowId()) + .orElseThrow(); + assertThat(afterTerminalWrite.getId()).isEqualTo(inserted.getId()); + assertThat(afterTerminalWrite.getRevision()).isEqualTo(3L); + assertThat(afterTerminalWrite.getStatus()).isEqualTo(PublishAttemptStatus.FAILED); + assertThat(afterTerminalWrite.getFailureMessage()).isEqualTo("first revision writer"); + assertThat(afterTerminalWrite.getFailureCode()).isEqualTo("terminal-revision-proof"); + } + @Test void fullVersionSealTransactionUsesExplicitReadCommittedIsolation() { AtomicReference isolation = new AtomicReference<>(); @@ -549,18 +662,39 @@ void scriptPatchFinalizationFailureRollsBackToRetainedDraftAndMarksAttemptFailed void selectedMechanicsRetainsCandidatePendingCompletePublicationReadback() { String tenantId = isolatedTenantId(); SelectedPublicationFixture fixture = - selectedPublicationFixture(tenantId, "pending-readback-proof-game", false); + selectedFullPublicationFixture(tenantId, "pending-readback-proof-game", false); String publishRequestId = fixture.operation().account().input().selection().intent().publishRequestId(); String publishWorkflowId = fixture.operation().workflowId(); + PublicationDigestRequestBinding expectedBinding = + PublicationDigestRequestBinding.full( + fixture + .operation() + .account() + .input() + .selection() + .intent() + .canonicalTenantId() + .toString(), + String.valueOf(fixture.version().getId()), + publishRequestId); ExportedAssetManifest candidate = recordFixtureCandidate(fixture); AtomicReference recordedDigestFailure = new AtomicReference<>(); AtomicInteger artifactReadbackCount = new AtomicInteger(); Mockito.when( - publishGateService.collectFullVersionParticipantDigests( + publishGateService.collectSelectedFullVersionParticipantDigests( Mockito.any(VersionDto.class), - Mockito.eq(publishRequestId), + Mockito.argThat( + binding -> + binding != null + && binding + .canonicalPreimageHex() + .equals(expectedBinding.canonicalPreimageHex()) + && binding.requestDigest().equals(expectedBinding.requestDigest()) + && binding + .derivedWorkflowIdentity() + .equals(expectedBinding.derivedWorkflowIdentity())), Mockito.eq(publishWorkflowId))) .thenAnswer( invocation -> { @@ -568,7 +702,7 @@ void selectedMechanicsRetainsCandidatePendingCompletePublicationReadback() { return PublishedWorldSelectorFixtures.participants( selectedVersion.id(), fixture.operation().world(), - AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); }); Mockito.doAnswer( invocation -> { @@ -663,10 +797,22 @@ void selectedMechanicsRetainsCandidatePendingCompletePublicationReadback() { void fullVersionMechanicsLeavesPostExportFinalizationFailurePendingWithCandidateAndRemap() { String tenantId = isolatedTenantId(); SelectedPublicationFixture fixture = - selectedPublicationFixture(tenantId, "failed-remap-proof-game", true); + selectedFullPublicationFixture(tenantId, "failed-remap-proof-game", true); String publishRequestId = fixture.operation().account().input().selection().intent().publishRequestId(); String publishWorkflowId = fixture.operation().workflowId(); + PublicationDigestRequestBinding expectedBinding = + PublicationDigestRequestBinding.full( + fixture + .operation() + .account() + .input() + .selection() + .intent() + .canonicalTenantId() + .toString(), + String.valueOf(fixture.version().getId()), + publishRequestId); Version sourceVersion = versionRepository.findByTenantIdAndVersionNumber(tenantId, 1).orElseThrow(); long sourceVersionId = sourceVersion.getId(); @@ -682,9 +828,18 @@ void fullVersionMechanicsLeavesPostExportFinalizationFailurePendingWithCandidate AtomicBoolean finalizationFailureInjected = new AtomicBoolean(); Mockito.when( - publishGateService.collectFullVersionParticipantDigests( + publishGateService.collectSelectedFullVersionParticipantDigests( Mockito.any(VersionDto.class), - Mockito.eq(publishRequestId), + Mockito.argThat( + binding -> + binding != null + && binding + .canonicalPreimageHex() + .equals(expectedBinding.canonicalPreimageHex()) + && binding.requestDigest().equals(expectedBinding.requestDigest()) + && binding + .derivedWorkflowIdentity() + .equals(expectedBinding.derivedWorkflowIdentity())), Mockito.eq(publishWorkflowId))) .thenAnswer( invocation -> { @@ -694,7 +849,7 @@ void fullVersionMechanicsLeavesPostExportFinalizationFailurePendingWithCandidate return PublishedWorldSelectorFixtures.participants( candidate.id(), fixture.operation().world(), - AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); }); Mockito.doAnswer( invocation -> { @@ -844,16 +999,37 @@ void fullVersionMechanicsLeavesPostExportFinalizationFailurePendingWithCandidate void privateMechanicsCommitsGdsOwnerButRemainsPendingWithoutWorldProducer() { String tenantId = "9002"; SelectedPublicationFixture fixture = - selectedPublicationFixture(tenantId, "successful-transaction-proof-game", false); + selectedFullPublicationFixture(tenantId, "successful-transaction-proof-game", false); String publishRequestId = fixture.operation().account().input().selection().intent().publishRequestId(); String publishWorkflowId = fixture.operation().workflowId(); + PublicationDigestRequestBinding expectedBinding = + PublicationDigestRequestBinding.full( + fixture + .operation() + .account() + .input() + .selection() + .intent() + .canonicalTenantId() + .toString(), + String.valueOf(fixture.version().getId()), + publishRequestId); AtomicReference controlPlaneDigestFailure = captureControlPlaneDigestFailure(); Mockito.when( - publishGateService.collectFullVersionParticipantDigests( + publishGateService.collectSelectedFullVersionParticipantDigests( Mockito.any(VersionDto.class), - Mockito.eq(publishRequestId), + Mockito.argThat( + binding -> + binding != null + && binding + .canonicalPreimageHex() + .equals(expectedBinding.canonicalPreimageHex()) + && binding.requestDigest().equals(expectedBinding.requestDigest()) + && binding + .derivedWorkflowIdentity() + .equals(expectedBinding.derivedWorkflowIdentity())), Mockito.eq(publishWorkflowId))) .thenAnswer( invocation -> { @@ -861,7 +1037,7 @@ void privateMechanicsCommitsGdsOwnerButRemainsPendingWithoutWorldProducer() { return PublishedWorldSelectorFixtures.participants( version.id(), fixture.operation().world(), - AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); }); Mockito.when(assetExportService.exportAssets(tenantId, fixture.version().getVersionNumber())) .thenAnswer(invocation -> recordFixtureCandidate(fixture)); @@ -974,7 +1150,7 @@ void publicFreshAndPendingFullVersionPublicationAreDeniedBeforeMutation() { } /** Fixture-only Account/World inputs; this exercises GD's actual selected owner transaction. */ - private SelectedPublicationFixture selectedPublicationFixture( + private SelectedPublicationFixture selectedFullPublicationFixture( String tenantId, String gameName, boolean includePublishedSource) { TransactionTemplate sourceTransaction = new TransactionTemplate(transactionManager); sourceTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); @@ -1019,7 +1195,7 @@ private SelectedPublicationFixture selectedPublicationFixture( GameAsset persistedAsset = gameAssetRepository.save(asset); try { GameDesignPublicationOperation operation = - IsolatedPublicationOwnerSetup.retainFrozenSourceBacked( + IsolatedPublicationOwnerSetup.retainFrozenSourceBackedSelectedFull( dsl, target, persisted.getVersionStateEpoch(), diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/WorldManagementClientTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/WorldManagementClientTest.java index 751407ebb9..6353cb3e24 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/WorldManagementClientTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/WorldManagementClientTest.java @@ -122,7 +122,15 @@ private static List participants(PublishParticipant } private static PublishGateServiceImpl gate() { - return new PublishGateServiceImpl(null, null, null, null, null); + return new PublishGateServiceImpl( + null, + null, + null, + null, + null, + mock(org.jooq.DSLContext.class), + mock(org.springframework.transaction.PlatformTransactionManager.class), + ""); } private static VersionDto version() { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcServiceTest.java new file mode 100644 index 0000000000..c2703bb723 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcServiceTest.java @@ -0,0 +1,339 @@ +package net.firedevops.firemud.gamedesign.draft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +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.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadEvidence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadGrpcCodec; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationRequest; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationResponse; +import net.firedevops.firemud.gamedesign.v1.SelectedDraftPublicationStatus; +import org.junit.jupiter.api.Test; + +/** Receiver unit proof uses stipulated verified peer context and mocked selection storage. */ +class GameDesignSelectedDraftPublicationReadGrpcServiceTest { + private static final String NAMESPACE = "test"; + + @Test + void rejectsMissingWrongServiceAndWrongNamespacePeersBeforeDecodingAndStorage() { + var repository = mock(AuthoredDraftPublishSelectionRepository.class); + var service = new GameDesignSelectedDraftPublicationReadGrpcService(repository, NAMESPACE); + var malformed = ReadSelectedDraftPublicationRequest.getDefaultInstance(); + var absent = new Collector(); + service.readSelectedDraftPublication(malformed, absent); + assertFailure(absent, Status.Code.UNAUTHENTICATED); + for (var peer : + List.of( + peer("game-design-service", NAMESPACE), + peer("account-service", "other"), + peer("world-management-service", "other"))) { + var denied = invokeAs(service, malformed, peer); + assertFailure(denied, Status.Code.PERMISSION_DENIED); + } + verifyNoInteractions(repository); + } + + @Test + void rejectsMalformedUnknownAndCrossNamespaceRequestsBeforeStorage() { + var repository = mock(AuthoredDraftPublishSelectionRepository.class); + var service = new GameDesignSelectedDraftPublicationReadGrpcService(repository, NAMESPACE); + var request = wireRequest(); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + for (var invalid : + List.of( + ReadSelectedDraftPublicationRequest.getDefaultInstance(), + request.toBuilder().setUnknownFields(unknown).build(), + request.toBuilder().setSelectionDigest("sha256:" + "0".repeat(64)).build())) { + assertFailure( + invokeAs(service, invalid, peer("account-service", NAMESPACE)), + Status.Code.INVALID_ARGUMENT); + } + assertFailure( + invokeAs( + service, + request.toBuilder().setTargetNamespace("other").build(), + peer("account-service", NAMESPACE)), + Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void bothAllowedWorkloadPeersRejectAuthenticatedCallerContextBeforeDecodeOrStorage() { + var repository = mock(AuthoredDraftPublishSelectionRepository.class); + var service = new GameDesignSelectedDraftPublicationReadGrpcService(repository, NAMESPACE); + try { + for (String caller : List.of("account-service", "world-management-service")) { + for (var roles : List.of(List.of(), List.of("ROLE_ADMIN"))) { + SessionContext.setContext("controlled-authenticated-user", roles, java.util.Map.of()); + assertFailure( + invokeAs(service, wireRequest(), peer(caller, NAMESPACE)), + Status.Code.PERMISSION_DENIED); + // Malformed bytes cannot reach decoding through an otherwise admitted workload peer. + assertFailure( + invokeAs( + service, + ReadSelectedDraftPublicationRequest.getDefaultInstance(), + peer(caller, NAMESPACE)), + Status.Code.PERMISSION_DENIED); + } + } + verifyNoInteractions(repository); + } finally { + SessionContext.clear(); + } + } + + @Test + void readsExactCanonicalIdentityAndReturnsOnlyExactRetainedSelectionForBothCallers() { + for (String caller : List.of("account-service", "world-management-service")) { + var repository = mock(AuthoredDraftPublishSelectionRepository.class); + var binding = binding(); + when(repository.read(any(), any(), any())).thenReturn(Optional.of(snapshot(binding))); + var service = new GameDesignSelectedDraftPublicationReadGrpcService(repository, NAMESPACE); + var request = wireRequest(); + var response = invokeAs(service, request, peer(caller, NAMESPACE)); + var intent = binding.intent(); + verify(repository) + .read(intent.canonicalTenantId(), intent.canonicalVersionId(), intent.publishRequestId()); + assertThat(response.errorCode).isNull(); + assertThat(response.completed).isTrue(); + assertThat(response.value) + .isEqualTo( + AuthoredDraftPublishSelectionReadGrpcCodec.toSelectedResponse( + AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest(request))); + assertThat(response.value.getStatus()) + .isEqualTo(SelectedDraftPublicationStatus.SELECTED_DRAFT_PUBLICATION_STATUS_SELECTED); + } + } + + @Test + void missingSelectionDoesNotInventSuccessfulOrTerminalEvidence() { + var repository = mock(AuthoredDraftPublishSelectionRepository.class); + when(repository.read(any(), any(), any())).thenReturn(Optional.empty()); + var service = new GameDesignSelectedDraftPublicationReadGrpcService(repository, NAMESPACE); + assertFailure( + invokeAs(service, wireRequest(), peer("account-service", NAMESPACE)), + Status.Code.NOT_FOUND); + } + + @Test + void changedStoredSelectionFailsWithoutPartialBytes() { + var repository = mock(AuthoredDraftPublishSelectionRepository.class); + var original = binding(); + var intent = original.intent(); + var changed = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + intent.expectedVersionStateEpoch(), + "changed notes", + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()), + original.target(), + original.selectedCommit(), + new VisibilityFence( + original.target(), + original.fenceRequestId(), + original.fenceCommitId(), + original.fenceInputDigest(), + original.fenceResultVectorJson(), + OffsetDateTime.parse(original.fenceCreatedAt()))); + when(repository.read(any(), any(), any())).thenReturn(Optional.of(snapshot(changed))); + var service = new GameDesignSelectedDraftPublicationReadGrpcService(repository, NAMESPACE); + assertFailure( + invokeAs(service, wireRequest(), peer("world-management-service", NAMESPACE)), + Status.Code.FAILED_PRECONDITION); + } + + @Test + void corruptRetainedSelectionIsDeniedAsNonRetryableWithoutLeakingEvidence() { + for (RuntimeException failure : + List.of( + new IllegalStateException("corrupt retained selection"), + new IllegalArgumentException("invalid retained selection"))) { + var repository = mock(AuthoredDraftPublishSelectionRepository.class); + when(repository.read(any(), any(), any())).thenThrow(failure); + var service = new GameDesignSelectedDraftPublicationReadGrpcService(repository, NAMESPACE); + var result = invokeAs(service, wireRequest(), peer("account-service", NAMESPACE)); + assertFailure(result, Status.Code.FAILED_PRECONDITION); + assertSanitizedFailure(result, "Retained selected Draft publication evidence is invalid"); + } + } + + @Test + void typedStorageFailuresAreUnavailableWithoutReturningEvidence() { + for (RuntimeException failure : + List.of( + new org.jooq.exception.DataAccessException("storage unavailable"), + new org.springframework.dao.TransientDataAccessResourceException( + "temporary storage failure"), + new org.springframework.dao.DataAccessResourceFailureException( + "storage resource unavailable"))) { + var repository = mock(AuthoredDraftPublishSelectionRepository.class); + when(repository.read(any(), any(), any())).thenThrow(failure); + var service = new GameDesignSelectedDraftPublicationReadGrpcService(repository, NAMESPACE); + var result = invokeAs(service, wireRequest(), peer("account-service", NAMESPACE)); + assertFailure(result, Status.Code.UNAVAILABLE); + assertSanitizedFailure(result, "Game Design selection storage unavailable"); + } + } + + private static AuthoredDraftPublishSelectionRepository.SelectionSnapshot snapshot( + AuthoredDraftPublishSelectionBinding binding) { + return new AuthoredDraftPublishSelectionRepository.SelectionSnapshot( + AuthoredDraftPublishSelection.fromStored(binding.canonicalJson(), binding.digest()), + OffsetDateTime.parse("2026-10-01T00:00:00Z")); + } + + private static ReadSelectedDraftPublicationRequest wireRequest() { + return AuthoredDraftPublishSelectionReadGrpcCodec.toRequest( + AuthoredDraftPublishSelectionReadEvidence.Request.create(NAMESPACE, binding())); + } + + private static void assertFailure(Collector collector, Status.Code expected) { + assertThat(collector.errorCode).isEqualTo(expected); + assertThat(collector.value).isNull(); + assertThat(collector.completed).isFalse(); + } + + private static void assertSanitizedFailure(Collector collector, String description) { + assertThat(collector.failureIsStatusRuntimeException).isTrue(); + assertThat(collector.failureDescription).isEqualTo(description); + assertThat(collector.failureHasCause).isFalse(); + assertThat(collector.failureHasTrailers).isFalse(); + } + + private static Collector invokeAs( + GameDesignSelectedDraftPublicationReadGrpcService service, + ReadSelectedDraftPublicationRequest request, + GrpcPeerIdentity peer) { + var result = new Collector(); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + service.readSelectedDraftPublication(request, result); + return result; + } finally { + context.detach(previous); + } + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static AuthoredDraftPublishSelectionBinding binding() { + UUID tenant = uuid("22222222-2222-4222-8222-222222222222"); + UUID version = uuid("33333333-3333-4333-8333-333333333333"); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"); + var commit = + DraftCommitBinding.create( + target, + uuid("44444444-4444-4444-8444-444444444444"), + uuid("55555555-5555-4555-8555-555555555555"), + "base-1", + List.of( + new RevisionPayload( + "0", + uuid("66666666-6666-4666-8666-666666666666"), + Owner.WORLD_MANAGEMENT, + "{}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + var selected = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + tenant, + version, + "publication-request", + "5", + "test selection", + commit.requestId(), + commit.commitId(), + commit.digest()), + target, + commit, + new VisibilityFence( + target, + commit.requestId(), + commit.commitId(), + commit.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + return selected; + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class Collector + implements StreamObserver { + private ReadSelectedDraftPublicationResponse value; + private Status.Code errorCode; + private String failureDescription; + private boolean failureIsStatusRuntimeException; + private boolean failureHasCause; + private boolean failureHasTrailers; + private boolean completed; + + @Override + public void onNext(ReadSelectedDraftPublicationResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + var status = Status.fromThrowable(failure); + errorCode = status.getCode(); + failureDescription = status.getDescription(); + failureHasCause = failure.getCause() != null; + if (failure instanceof StatusRuntimeException statusFailure) { + failureIsStatusRuntimeException = true; + failureHasTrailers = statusFailure.getTrailers() != null; + } + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java new file mode 100644 index 0000000000..bc5dab2a20 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java @@ -0,0 +1,394 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ClientInterceptor; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadGrpcCodec; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.client.GameLogicClient; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamelogic.v1.GameLogicServiceGrpc; +import net.firedevops.firemud.gamelogic.v1.GetDraftDesignDigestRequest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameLogicClientTest { + private static final String WORKLOAD_NAMESPACE = "test"; + + @Test + void readsExactRetainedSelectionAndReturnsBothDigestProjections(@TempDir Path tlsDirectory) + throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var publication = publicationBinding(receipt); + var sourceRead = + new GameLogicPublicationSourceReadBinding(publication, receipt.authorization()); + var response = + GameLogicPublicationSourceReadGrpcCodec.toResponse( + sourceRead, receipt.receipt().terminal()); + var clientAndStub = client(tlsDirectory); + var client = clientAndStub.client(); + var stub = clientAndStub.stub(); + when(stub.getDraftDesignDigest(any(GetDraftDesignDigestRequest.class))).thenReturn(response); + + var result = client.getDraftDesignDigestForVersion(publication, receipt); + + assertThat(result.succeeded()).isTrue(); + assertThat(result.participantKey()).isEqualTo("GAME_LOGIC"); + assertThat(result.scopeValue()).isEqualTo(publication.versionId()); + assertThat(result.baseVersionId()).isNull(); + assertThat(result.appliedCommitId()) + .isEqualTo(receipt.authorization().source().binding().commitId().toString()); + assertThat(response.getContentDigest()).matches("sha256:[0-9a-f]{64}"); + assertThat(result.contentDigest()) + .isEqualTo(response.getContentDigest().substring("sha256:".length())) + .matches("[0-9a-f]{64}") + .isNotEqualTo(response.getContentDigest()); + assertThat(result.digestSchemaVersion()).isEqualTo(response.getDigestSchemaVersion()); + assertThat(result.abilitySchemaDigest()).isEqualTo(response.getAbilitySchemaDigest()); + assertThat(result.abilitySchemaDigest()).matches("sha256:[0-9a-f]{64}"); + + var request = org.mockito.ArgumentCaptor.forClass(GetDraftDesignDigestRequest.class); + verify(stub).getDraftDesignDigest(request.capture()); + assertThat(request.getValue().getTenantId()).isEqualTo(publication.tenantId()); + assertThat(request.getValue().getVersionId()).isEqualTo(publication.versionId()); + assertThat(request.getValue().getPublishRequestId()).isEqualTo(publication.publishRequestId()); + assertThat(request.getValue().getDerivedWorkflowIdentity()) + .isEqualTo(publication.derivedWorkflowIdentity()); + assertThat(request.getValue().getRequestDigest()).isEqualTo(publication.requestDigest()); + var decoded = GameLogicPublicationSourceReadGrpcCodec.fromRequest(request.getValue()); + assertThat(decoded.canonicalBytes()).containsExactly(sourceRead.canonicalBytes()); + assertThat(decoded.authorization().canonicalBytes()) + .containsExactly(receipt.authorization().canonicalBytes()); + verify(stub).withCallCredentials(any()); + verify(stub).withInterceptors(any(ClientInterceptor[].class)); + verify(stub).withMaxInboundMessageSize(GameLogicPublicationSourceReadGrpcCodec.MAX_WIRE_BYTES); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + @Test + void rejectsAValidButDifferentTerminalFromTheImmutableReceipt(@TempDir Path tlsDirectory) + throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var publication = publicationBinding(receipt); + var sourceRead = + new GameLogicPublicationSourceReadBinding(publication, receipt.authorization()); + var retained = receipt.receipt().terminal(); + var differentTerminal = + GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation("other", receipt.authorization()), + retained.selectedSourceBytes(), + retained.manifestBytes()); + assertThat(Arrays.equals(differentTerminal.canonicalBytes(), retained.canonicalBytes())) + .isFalse(); + var response = + GameLogicPublicationSourceReadGrpcCodec.toResponse(sourceRead, differentTerminal); + var clientAndStub = client(tlsDirectory); + ReflectionTestUtils.setField(clientAndStub.client(), "workloadNamespace", "other"); + when(clientAndStub.stub().getDraftDesignDigest(any(GetDraftDesignDigestRequest.class))) + .thenReturn(response); + + var result = clientAndStub.client().getDraftDesignDigestForVersion(publication, receipt); + + assertThat(result.succeeded()).isFalse(); + assertThat(result.errorCode()).isEqualTo("RESPONSE_TERMINAL_MISMATCH"); + assertThat(result.contentDigest()).isNull(); + assertThat(result.abilitySchemaDigest()).isNull(); + } + + @Test + void propagatesUnavailableTransportFailureForRetry(@TempDir Path tlsDirectory) + throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var publication = publicationBinding(receipt); + var clientAndStub = client(tlsDirectory); + when(clientAndStub.stub().getDraftDesignDigest(any(GetDraftDesignDigestRequest.class))) + .thenThrow(Status.UNAVAILABLE.withDescription("readback unavailable").asRuntimeException()); + + assertThatThrownBy( + () -> clientAndStub.client().getDraftDesignDigestForVersion(publication, receipt)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + verify(clientAndStub.stub()).getDraftDesignDigest(any(GetDraftDesignDigestRequest.class)); + } + + @Test + void rejectsMalformedManifestDigestFromPublicationResponse(@TempDir Path tlsDirectory) + throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var publication = publicationBinding(receipt); + var sourceRead = + new GameLogicPublicationSourceReadBinding(publication, receipt.authorization()); + var validResponse = + GameLogicPublicationSourceReadGrpcCodec.toResponse( + sourceRead, receipt.receipt().terminal()); + var response = + validResponse.toBuilder() + .setContentDigest(validResponse.getContentDigest().substring("sha256:".length())) + .build(); + var clientAndStub = client(tlsDirectory); + when(clientAndStub.stub().getDraftDesignDigest(any(GetDraftDesignDigestRequest.class))) + .thenReturn(response); + + var result = clientAndStub.client().getDraftDesignDigestForVersion(publication, receipt); + + assertThat(result.succeeded()).isFalse(); + assertThat(result.errorCode()).isEqualTo("RESPONSE_BINDING_MISMATCH"); + assertThat(result.contentDigest()).isNull(); + assertThat(result.abilitySchemaDigest()).isNull(); + } + + @Test + void rejectsSwappedManifestAndAbilityDigestsFromPublicationResponse(@TempDir Path tlsDirectory) + throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var publication = publicationBinding(receipt); + var sourceRead = + new GameLogicPublicationSourceReadBinding(publication, receipt.authorization()); + var validResponse = + GameLogicPublicationSourceReadGrpcCodec.toResponse( + sourceRead, receipt.receipt().terminal()); + assertThat(validResponse.getContentDigest()) + .isNotEqualTo(validResponse.getAbilitySchemaDigest()); + var response = + validResponse.toBuilder() + .setContentDigest(validResponse.getAbilitySchemaDigest()) + .setAbilitySchemaDigest(validResponse.getContentDigest()) + .build(); + var clientAndStub = client(tlsDirectory); + when(clientAndStub.stub().getDraftDesignDigest(any(GetDraftDesignDigestRequest.class))) + .thenReturn(response); + + var result = clientAndStub.client().getDraftDesignDigestForVersion(publication, receipt); + + assertThat(result.succeeded()).isFalse(); + assertThat(result.errorCode()).isEqualTo("RESPONSE_BINDING_MISMATCH"); + assertThat(result.contentDigest()).isNull(); + assertThat(result.abilitySchemaDigest()).isNull(); + } + + @Test + void missingReceiptLegacyPathFailsClosedWithoutCallingGameLogic(@TempDir Path tlsDirectory) + throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var clientAndStub = client(tlsDirectory); + + var result = clientAndStub.client().getDraftDesignDigestForVersion(publicationBinding(receipt)); + + assertThat(result.succeeded()).isFalse(); + assertThat(result.errorCode()).isEqualTo("SELECTED_GAME_LOGIC_RECEIPT_REQUIRED"); + verifyNoInteractions(clientAndStub.stub()); + } + + @Test + void rejectsPublicationRequestThatDoesNotMatchTheReceiptSelection(@TempDir Path tlsDirectory) + throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var publication = publicationBinding(receipt); + var changedPublication = + PublicationDigestRequestBinding.full( + publication.tenantId(), + publication.versionId(), + publication.publishRequestId() + "-different"); + var clientAndStub = client(tlsDirectory); + + assertThatThrownBy( + () -> + clientAndStub.client().getDraftDesignDigestForVersion(changedPublication, receipt)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("differs from immutable selected Game Logic receipt"); + verifyNoInteractions(clientAndStub.stub()); + } + + @Test + void missingWorkloadNamespaceReturnsUnavailableBeforeRpc(@TempDir Path tlsDirectory) + throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var clientAndStub = client(tlsDirectory); + ReflectionTestUtils.setField(clientAndStub.client(), "workloadNamespace", ""); + + var result = + clientAndStub.client().getDraftDesignDigestForVersion(publicationBinding(receipt), receipt); + + assertConfigurationUnavailable(result); + verifyNoInteractions(clientAndStub.stub()); + } + + @Test + void invalidWorkloadNamespaceReturnsUnavailableBeforeRpc(@TempDir Path tlsDirectory) + throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var clientAndStub = client(tlsDirectory); + ReflectionTestUtils.setField(clientAndStub.client(), "workloadNamespace", "Not_A_Namespace"); + + var result = + clientAndStub.client().getDraftDesignDigestForVersion(publicationBinding(receipt), receipt); + + assertConfigurationUnavailable(result); + verifyNoInteractions(clientAndStub.stub()); + } + + @Test + void plaintextTlsConfigurationReturnsUnavailableBeforeRpc(@TempDir Path tlsDirectory) + throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(true); + var clientAndStub = client(tlsDirectory, tls); + + var result = + clientAndStub.client().getDraftDesignDigestForVersion(publicationBinding(receipt), receipt); + + assertConfigurationUnavailable(result); + verifyNoInteractions(clientAndStub.stub()); + } + + @Test + void unreadableTlsMaterialReturnsUnavailableBeforeRpc(@TempDir Path tlsDirectory) + throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var tls = fileBackedTls(tlsDirectory); + tls.setCaCert(tlsDirectory.resolve("missing-ca.crt").toString()); + var clientAndStub = client(tlsDirectory, tls); + + var result = + clientAndStub.client().getDraftDesignDigestForVersion(publicationBinding(receipt), receipt); + + assertConfigurationUnavailable(result); + verifyNoInteractions(clientAndStub.stub()); + } + + @Test + void uninitializedClientReturnsUnavailableBeforeRpc(@TempDir Path tlsDirectory) + throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var clientAndStub = client(tlsDirectory); + ReflectionTestUtils.setField(clientAndStub.client(), "stub", null); + + var result = + clientAndStub.client().getDraftDesignDigestForVersion(publicationBinding(receipt), receipt); + + assertConfigurationUnavailable(result); + verifyNoInteractions(clientAndStub.stub()); + } + + @Test + void activeSqlTransactionDeniesBeforeRpc(@TempDir Path tlsDirectory) throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var clientAndStub = client(tlsDirectory); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy( + () -> + clientAndStub + .client() + .getDraftDesignDigestForVersion(publicationBinding(receipt), receipt)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL transaction"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + verifyNoInteractions(clientAndStub.stub()); + } + + @Test + void activeSqlSynchronizationDeniesBeforeRpc(@TempDir Path tlsDirectory) throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var clientAndStub = client(tlsDirectory); + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy( + () -> + clientAndStub + .client() + .getDraftDesignDigestForVersion(publicationBinding(receipt), receipt)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL transaction"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + verifyNoInteractions(clientAndStub.stub()); + } + + private static PublicationDigestRequestBinding publicationBinding( + SelectedDraftGameLogicReceipt receipt) { + return PublicationDigestRequestBinding.full( + receipt.selection().intent().canonicalTenantId().toString(), + Long.toString(receipt.selection().target().gameDesignVersionRowId()), + receipt.selection().intent().publishRequestId()); + } + + private static ClientAndStub client(Path tlsDirectory) throws IOException { + return client(tlsDirectory, fileBackedTls(tlsDirectory)); + } + + private static void assertConfigurationUnavailable(PublishParticipantDigestDto result) { + assertThat(result.succeeded()).isFalse(); + assertThat(result.errorCode()).isEqualTo("PARTICIPANT_UNAVAILABLE"); + assertThat(result.errorMessage()) + .isEqualTo("Game Logic publication source read is not configured"); + assertThat(result.contentDigest()).isNull(); + assertThat(result.abilitySchemaDigest()).isNull(); + } + + private static ClientAndStub client(Path tlsDirectory, CommonGrpcClientProperties tls) { + var client = + new GameLogicClient( + new ServiceEndpointsProperties(), + tls, + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop()); + ReflectionTestUtils.setField(client, "workloadNamespace", WORKLOAD_NAMESPACE); + + var stub = mock(GameLogicServiceGrpc.GameLogicServiceBlockingStub.class); + when(stub.withCallCredentials(any())).thenReturn(stub); + when(stub.withInterceptors(any(ClientInterceptor[].class))).thenReturn(stub); + when(stub.withMaxInboundMessageSize(GameLogicPublicationSourceReadGrpcCodec.MAX_WIRE_BYTES)) + .thenReturn(stub); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + clearInvocations(stub); + ReflectionTestUtils.setField(client, "stub", stub); + return new ClientAndStub(client, stub); + } + + private static CommonGrpcClientProperties fileBackedTls(Path tlsDirectory) throws IOException { + var tls = new CommonGrpcClientProperties(); + tls.setCertChain(write(tlsDirectory.resolve("client.crt"))); + tls.setPrivateKey(write(tlsDirectory.resolve("client.key"))); + tls.setCaCert(write(tlsDirectory.resolve("ca.crt"))); + return tls; + } + + private static String write(Path path) throws IOException { + Files.writeString(path, "test material"); + return path.toString(); + } + + private record ClientAndStub( + GameLogicClient client, GameLogicServiceGrpc.GameLogicServiceBlockingStub stub) {} +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java new file mode 100644 index 0000000000..b185f8e61f --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java @@ -0,0 +1,191 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.junit.jupiter.api.Test; + +/** Structural digest vectors only; synthetic source rows do not prove physical owner provenance. */ +class SelectedDraftControlPlaneDigestTest { + @Test + void exactSixFamilyPreimageIsDeterministic() throws Exception { + var selected = selectedBinding(); + var sources = sources(selected); + + var first = SelectedDraftControlPlaneDigest.compute(selected, sources); + var replay = SelectedDraftControlPlaneDigest.compute(selected, sources); + + assertThat(first).isEqualTo(replay); + assertThat(first.digestSchemaVersion()).isEqualTo(2); + assertThat(first.tenantId()).isEqualTo(selected.target().canonicalTenantId().toString()); + assertThat(first.scopeValue()) + .isEqualTo(Long.toString(selected.target().gameDesignVersionRowId())); + assertThat(first.appliedCommitId()).isEqualTo(selected.commitId().toString()); + assertThat(first.contentDigest()) + .isEqualTo("72f88d8fe8ad3d7f99a83e8cf0bb394fba649cae7e3e96da8567ad7de141cf01"); + } + + @Test + void changedSnapshotOrSelectedBindingChangesContentDigest() throws Exception { + var selected = selectedBinding(); + var originalSources = sources(selected); + var original = SelectedDraftControlPlaneDigest.compute(selected, originalSources); + + var changedAsset = + new AssetSnapshot( + selected, + "1", + null, + UUID.fromString("11111111-1111-4111-8111-111111111111"), + List.of()); + var changedSnapshot = + new GameDesignSourceRepository.SynchronizedSources( + originalSources.command(), + originalSources.policy(), + Optional.of(changedAsset), + originalSources.gameplayEvidence(), + originalSources.branding(), + originalSources.templateConfig()); + assertThat(SelectedDraftControlPlaneDigest.compute(selected, changedSnapshot).contentDigest()) + .isNotEqualTo(original.contentDigest()); + + var changedBinding = + DraftCommitBinding.create( + selected.target(), + selected.requestId(), + UUID.fromString("99999999-9999-4999-8999-999999999999"), + selected.baseCommitId(), + selected.revisions(), + selected.affectedUnits()); + var changedInput = + SelectedDraftControlPlaneDigest.compute(changedBinding, sources(changedBinding)); + assertThat(changedInput.contentDigest()).isNotEqualTo(original.contentDigest()); + } + + @Test + void missingBrandingOrTemplateFamilyCannotBeTreatedAsAnEmptySnapshot() throws Exception { + var selected = selectedBinding(); + var complete = sources(selected); + var missingBrand = + new GameDesignSourceRepository.SynchronizedSources( + complete.command(), + complete.policy(), + complete.assetEvidence(), + complete.gameplayEvidence(), + Optional.empty(), + complete.templateConfig()); + var missingTemplate = + new GameDesignSourceRepository.SynchronizedSources( + complete.command(), + complete.policy(), + complete.assetEvidence(), + complete.gameplayEvidence(), + complete.branding(), + Optional.empty()); + + assertThatThrownBy(() -> SelectedDraftControlPlaneDigest.compute(selected, missingBrand)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("branding"); + assertThatThrownBy(() -> SelectedDraftControlPlaneDigest.compute(selected, missingTemplate)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("template-config"); + } + + @Test + void sourceBindingMustExactlyEqualSelectedDraftBinding() throws Exception { + var selected = selectedBinding(); + var otherBinding = + DraftCommitBinding.create( + selected.target(), + selected.requestId(), + UUID.fromString("99999999-9999-4999-8999-999999999999"), + selected.baseCommitId(), + selected.revisions(), + selected.affectedUnits()); + + assertThatThrownBy( + () -> SelectedDraftControlPlaneDigest.compute(selected, sources(otherBinding))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact Draft commit"); + } + + private static GameDesignPublicationOperation operation() throws Exception { + return IsolatedPublicationOperationFixtures.fresh( + new TargetProof( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 19L, + "tenant-key", + 42L, + "tenant-key", + "NEW_GAME_ROW")); + } + + private static DraftCommitBinding selectedBinding() throws Exception { + var selected = operation().account().input().selection().selectedCommit(); + // Payload JSON is stored as text in the binding; normalize unordered fixture maps first. + var revisions = new java.util.ArrayList(); + for (var revision : selected.revisions()) { + revisions.add( + new DraftCommitBinding.RevisionPayload( + revision.revisionOrder(), + revision.revisionId(), + revision.owner(), + new String( + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + revision.payload()), + java.nio.charset.StandardCharsets.UTF_8))); + } + return DraftCommitBinding.create( + selected.target(), + selected.requestId(), + selected.commitId(), + selected.baseCommitId(), + revisions, + selected.affectedUnits()); + } + + private static GameDesignSourceRepository.SynchronizedSources sources( + DraftCommitBinding binding) { + var command = new CommandSnapshot(binding, "0", null, "sha256:" + "a".repeat(64), List.of()); + // Controlled inherited policy provenance; this World-only commit need not mutate policy. + var policy = + new RealmPolicySnapshot( + binding, + "1", + List.of( + new RealmPolicySource.Policy( + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + "inherited-policy", + net.firedevops.firemud.common.publication.RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\",\"visible\":true," + + "\"publicProduction\":false,\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}", + new tools.jackson.databind.ObjectMapper())))); + var asset = + new AssetSnapshot( + binding, "0", null, UUID.fromString("33333333-3333-4333-8333-333333333333"), List.of()); + var gameplay = + new GameplayRuleSnapshot( + binding, "0", null, UUID.fromString("44444444-4444-4444-8444-444444444444"), List.of()); + var branding = + new BrandingSourceSnapshot( + binding, "0", null, UUID.fromString("55555555-5555-4555-8555-555555555555"), List.of()); + var template = + new TemplateConfigSourceSnapshot( + binding, "0", null, UUID.fromString("66666666-6666-4666-8666-666666666666"), List.of()); + return new GameDesignSourceRepository.SynchronizedSources( + command, + policy, + Optional.of(asset), + Optional.of(gameplay), + Optional.of(branding), + Optional.of(template)); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java new file mode 100644 index 0000000000..c6a4df7194 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java @@ -0,0 +1,569 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.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 io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.CannotCreateTransactionException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.TransactionSystemException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Structural owner-read proof; mocks do not establish physical PostgreSQL source provenance. */ +class SelectedDraftPublicationDigestReadServiceTest { + private static final String NAMESPACE = "test"; + + private final SelectedDraftPublicationDigestReadService.OwnerRead owner = + mock(SelectedDraftPublicationDigestReadService.OwnerRead.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + private final TransactionStatus transactionStatus = mock(TransactionStatus.class); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void readsExactSelectionFrozenAndSynchronizedSourcesInOneReadOnlyRepeatableReadSnapshot() + throws Exception { + var fixture = fixture(); + var request = request(fixture.operation()); + when(transactions.getTransaction(any())).thenReturn(transactionStatus); + when(owner.read(request.derivedWorkflowIdentity())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + fixture.operation(), "PENDING", new byte[] {1}))); + when(owner.readSourceCapture(fixture.operation())).thenReturn(Optional.of(fixture.capture())); + when(owner.readSynchronized(fixture.binding().target(), fixture.binding().commitId())) + .thenReturn(Optional.of(fixture.sources())); + + var result = + new SelectedDraftPublicationDigestReadService(owner, transactions, NAMESPACE) + .read(NAMESPACE, request); + + assertThat(result.requestBinding()).isSameAs(request); + assertThat(result.requestDigest()).isEqualTo(request.requestDigest()); + assertThat(result.gameDesignDigest().tenantId()).isEqualTo(request.tenantId()); + assertThat(result.gameDesignDigest().scopeValue()).isEqualTo(request.versionId()); + assertThat(result.gameDesignDigest().appliedCommitId()) + .isEqualTo(fixture.binding().commitId().toString()); + assertThat(result.gameDesignDigest().digestSchemaVersion()).isEqualTo(2); + assertThat(result.worldManagementDigest().participantKey()).isEqualTo("WORLD_MANAGEMENT"); + assertThat(result.worldManagementDigest().contentDigest()) + .isEqualTo(fixture.operation().world().request().contentDigest()); + assertThat(result.worldManagementDigest().digestSchemaVersion()) + .isEqualTo(fixture.operation().world().request().digestSchemaVersion()); + + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + var order = inOrder(transactions, owner); + order.verify(transactions).getTransaction(definition.capture()); + order.verify(owner).read(request.derivedWorkflowIdentity()); + order.verify(owner).requireExactSelection(fixture.operation()); + order.verify(owner).readSourceCapture(fixture.operation()); + order.verify(owner).readSynchronized(fixture.binding().target(), fixture.binding().commitId()); + order.verify(transactions).commit(transactionStatus); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThat(definition.getValue().isReadOnly()).isTrue(); + } + + @Test + void receiptBoundReadRequiresExactCanonicalGameplaySourceBytes() throws Exception { + var fixture = fixture(); + var request = request(fixture.operation()); + when(transactions.getTransaction(any())).thenReturn(transactionStatus); + when(owner.read(request.derivedWorkflowIdentity())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + fixture.operation(), "PENDING", new byte[] {1}))); + when(owner.readSourceCapture(fixture.operation())).thenReturn(Optional.of(fixture.capture())); + when(owner.readSynchronized(fixture.binding().target(), fixture.binding().commitId())) + .thenReturn(Optional.of(fixture.sources())); + var service = new SelectedDraftPublicationDigestReadService(owner, transactions, NAMESPACE); + var gameplay = fixture.sources().gameplayEvidence().orElseThrow(); + var exactReceipt = receipt(fixture.operation(), gameplay); + + var result = service.read(NAMESPACE, request, exactReceipt); + + assertThat(result.requestBinding()).isSameAs(request); + assertThat(result.gameDesignDigest().appliedCommitId()) + .isEqualTo(fixture.binding().commitId().toString()); + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactions).getTransaction(definition.capture()); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThat(definition.getValue().isReadOnly()).isTrue(); + + org.mockito.Mockito.reset(owner, transactions); + when(transactions.getTransaction(any())).thenReturn(transactionStatus); + when(owner.read(request.derivedWorkflowIdentity())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + fixture.operation(), "PENDING", new byte[] {1}))); + when(owner.readSourceCapture(fixture.operation())).thenReturn(Optional.of(fixture.capture())); + when(owner.readSynchronized(fixture.binding().target(), fixture.binding().commitId())) + .thenReturn(Optional.of(fixture.sources())); + var changedGameplay = + new GameplayRuleSnapshot( + gameplay.binding(), + new java.math.BigInteger(gameplay.sourceEpoch()) + .add(java.math.BigInteger.ONE) + .toString(), + gameplay.inheritedCommitId(), + gameplay.genesisReceiptId(), + gameplay.entries()); + var sameBindingDifferentReceipt = receipt(fixture.operation(), changedGameplay); + assertThat(sameBindingDifferentReceipt.authorization().source().binding()) + .isEqualTo(fixture.binding()); + assertThat(sameBindingDifferentReceipt.authorization().source().canonicalBytes()) + .isNotEqualTo(gameplay.canonicalBytes()); + + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> service.read(NAMESPACE, request, sameBindingDifferentReceipt)); + } + + @Test + void namespaceMalformedScopeAndAmbientSqlAreRejectedBeforeOwnerReads() throws Exception { + var fixture = fixture(); + var service = new SelectedDraftPublicationDigestReadService(owner, transactions, NAMESPACE); + + assertCode( + Status.Code.PERMISSION_DENIED, () -> service.read("other", request(fixture.operation()))); + assertCode(Status.Code.INVALID_ARGUMENT, () -> service.read(NAMESPACE, null)); + assertCode( + Status.Code.INVALID_ARGUMENT, + () -> + service.read( + NAMESPACE, + PublicationDigestRequestBinding.patch( + UUID.randomUUID().toString(), "19", "patch", "publish-id"))); + assertCode( + Status.Code.INVALID_ARGUMENT, + () -> + service.read( + NAMESPACE, + PublicationDigestRequestBinding.full("not-a-canonical-uuid", "19", "publish-id"))); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> service.read(NAMESPACE, request(fixture.operation()), null)); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> service.read(NAMESPACE, request(fixture.operation()))); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> service.read(NAMESPACE, request(fixture.operation()))); + + verifyNoInteractions(owner, transactions); + } + + @Test + void wrongActualVersionOrPublicationRequestCannotReuseAnotherOriginalOperation() + throws Exception { + var fixture = fixture(); + var validRequest = request(fixture.operation()); + when(transactions.getTransaction(any())).thenReturn(transactionStatus); + when(owner.read(any())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + fixture.operation(), "PENDING", new byte[] {1}))); + var service = new SelectedDraftPublicationDigestReadService(owner, transactions, NAMESPACE); + + var wrongVersion = + PublicationDigestRequestBinding.full( + validRequest.tenantId(), "20", validRequest.publishRequestId()); + assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, wrongVersion)); + var wrongTenant = + PublicationDigestRequestBinding.full( + "33333333-3333-4333-8333-333333333333", + validRequest.versionId(), + validRequest.publishRequestId()); + assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, wrongTenant)); + var wrongRequest = + PublicationDigestRequestBinding.full( + validRequest.tenantId(), validRequest.versionId(), "different-request"); + assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, wrongRequest)); + + verify(owner, never()).requireExactSelection(any()); + verify(owner, never()).readSourceCapture(any()); + verify(owner, never()).readSynchronized(any(), any()); + } + + @Test + void missingOperationOrRetainedSelectionFailsBeforeSourceReads() throws Exception { + var fixture = fixture(); + var request = request(fixture.operation()); + when(transactions.getTransaction(any())).thenReturn(transactionStatus); + when(owner.read(request.derivedWorkflowIdentity())).thenReturn(Optional.empty()); + var service = new SelectedDraftPublicationDigestReadService(owner, transactions, NAMESPACE); + assertCode(Status.Code.NOT_FOUND, () -> service.read(NAMESPACE, request)); + verify(owner, never()).requireExactSelection(any()); + verify(owner, never()).readSourceCapture(any()); + + org.mockito.Mockito.reset(owner); + when(owner.read(request.derivedWorkflowIdentity())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + fixture.operation(), "PENDING", new byte[] {1}))); + org.mockito.Mockito.doThrow(new IllegalStateException("selection readback unavailable")) + .when(owner) + .requireExactSelection(fixture.operation()); + assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, request)); + verify(owner, never()).readSourceCapture(any()); + } + + @Test + void transactionAcquisitionFailureIsSanitizedAsUnavailable() throws Exception { + var fixture = fixture(); + var request = request(fixture.operation()); + when(transactions.getTransaction(any())) + .thenThrow(new CannotCreateTransactionException("database-secret")); + var service = new SelectedDraftPublicationDigestReadService(owner, transactions, NAMESPACE); + + assertSanitizedUnavailable(service, request); + verifyNoInteractions(owner); + } + + @Test + void transactionRollbackFailureIsSanitizedAsUnavailable() throws Exception { + var fixture = fixture(); + var request = request(fixture.operation()); + when(transactions.getTransaction(any())).thenReturn(transactionStatus); + org.mockito.Mockito.doThrow(new TransactionSystemException("rollback-database-secret")) + .when(transactions) + .rollback(transactionStatus); + org.mockito.Mockito.doThrow(new IllegalStateException("selection-secret")) + .when(owner) + .read(request.derivedWorkflowIdentity()); + var service = new SelectedDraftPublicationDigestReadService(owner, transactions, NAMESPACE); + + assertSanitizedUnavailable(service, request); + } + + @Test + void missingSourceFamiliesAndFrozenSnapshotMismatchCannotProveAnEmptyOrDifferentSource() + throws Exception { + var fixture = fixture(); + var request = request(fixture.operation()); + when(transactions.getTransaction(any())).thenReturn(transactionStatus); + when(owner.read(request.derivedWorkflowIdentity())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + fixture.operation(), "PENDING", new byte[] {1}))); + when(owner.readSourceCapture(fixture.operation())).thenReturn(Optional.of(fixture.capture())); + var missingBranding = + new GameDesignSourceRepository.SynchronizedSources( + fixture.sources().command(), + fixture.sources().policy(), + fixture.sources().assetEvidence(), + fixture.sources().gameplayEvidence(), + Optional.empty(), + fixture.sources().templateConfig()); + when(owner.readSynchronized(fixture.binding().target(), fixture.binding().commitId())) + .thenReturn(Optional.of(missingBranding)); + var service = new SelectedDraftPublicationDigestReadService(owner, transactions, NAMESPACE); + assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, request)); + + org.mockito.Mockito.reset(owner); + when(owner.read(request.derivedWorkflowIdentity())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + fixture.operation(), "PENDING", new byte[] {1}))); + when(owner.readSourceCapture(fixture.operation())).thenReturn(Optional.of(fixture.capture())); + var changedAsset = + new AssetSnapshot( + fixture.binding(), + "1", + null, + UUID.fromString("77777777-7777-4777-8777-777777777777"), + List.of()); + var changedSources = + new GameDesignSourceRepository.SynchronizedSources( + fixture.sources().command(), + fixture.sources().policy(), + Optional.of(changedAsset), + fixture.sources().gameplayEvidence(), + fixture.sources().branding(), + fixture.sources().templateConfig()); + when(owner.readSynchronized(fixture.binding().target(), fixture.binding().commitId())) + .thenReturn(Optional.of(changedSources)); + assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, request)); + + org.mockito.Mockito.reset(owner); + when(owner.read(request.derivedWorkflowIdentity())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + fixture.operation(), "PENDING", new byte[] {1}))); + when(owner.readSourceCapture(fixture.operation())).thenReturn(Optional.of(fixture.capture())); + var changedGameplay = + new GameplayRuleSnapshot( + fixture.binding(), + "0", + null, + UUID.fromString("88888888-8888-4888-8888-888888888888"), + List.of()); + assertThat( + Arrays.equals( + changedGameplay.canonicalBytes(), + fixture.sources().gameplayEvidence().orElseThrow().canonicalBytes())) + .isFalse(); + var changedGameplaySources = + new GameDesignSourceRepository.SynchronizedSources( + fixture.sources().command(), + fixture.sources().policy(), + fixture.sources().assetEvidence(), + Optional.of(changedGameplay), + fixture.sources().branding(), + fixture.sources().templateConfig()); + when(owner.readSynchronized(fixture.binding().target(), fixture.binding().commitId())) + .thenReturn(Optional.of(changedGameplaySources)); + assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, request)); + + org.mockito.Mockito.reset(owner); + when(owner.read(request.derivedWorkflowIdentity())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + fixture.operation(), "PENDING", new byte[] {1}))); + when(owner.readSourceCapture(fixture.operation())).thenReturn(Optional.of(fixture.capture())); + var anotherCommit = + DraftCommitBinding.create( + fixture.binding().target(), + fixture.binding().requestId(), + UUID.fromString("99999999-9999-4999-8999-999999999999"), + fixture.binding().baseCommitId(), + fixture.binding().revisions(), + fixture.binding().affectedUnits()); + when(owner.readSynchronized(fixture.binding().target(), fixture.binding().commitId())) + .thenReturn(Optional.of(sources(anotherCommit))); + assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, request)); + } + + @Test + void absentFrozenFamilyDeniesBeforeSynchronizedSourceRead() throws Exception { + var fixture = fixture(); + var request = request(fixture.operation()); + when(transactions.getTransaction(any())).thenReturn(transactionStatus); + when(owner.read(request.derivedWorkflowIdentity())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + fixture.operation(), "PENDING", new byte[] {1}))); + var complete = fixture.capture(); + var missingFamilies = + List.of( + new GameDesignSourceRepository.Capture( + complete.command(), + complete.policy(), + Optional.empty(), + complete.gameplay(), + complete.branding(), + complete.templateConfig()), + new GameDesignSourceRepository.Capture( + complete.command(), + complete.policy(), + complete.asset(), + Optional.empty(), + complete.branding(), + complete.templateConfig()), + new GameDesignSourceRepository.Capture( + complete.command(), + complete.policy(), + complete.asset(), + complete.gameplay(), + Optional.empty(), + complete.templateConfig()), + new GameDesignSourceRepository.Capture( + complete.command(), + complete.policy(), + complete.asset(), + complete.gameplay(), + complete.branding(), + Optional.empty())); + var service = new SelectedDraftPublicationDigestReadService(owner, transactions, NAMESPACE); + for (var missing : missingFamilies) { + when(owner.readSourceCapture(fixture.operation())).thenReturn(Optional.of(missing)); + assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, request)); + } + verify(owner, never()).readSynchronized(any(), any()); + } + + private static PublicationDigestRequestBinding request(GameDesignPublicationOperation operation) { + var selection = operation.account().input().selection(); + return PublicationDigestRequestBinding.full( + selection.intent().canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + selection.intent().publishRequestId()); + } + + private static Fixture fixture() throws Exception { + var operation = + IsolatedPublicationOperationFixtures.fresh( + new TargetProof( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 19L, + "tenant-key", + 42L, + "tenant-key", + "NEW_GAME_ROW")); + var binding = operation.account().input().selection().selectedCommit(); + var sources = sources(binding); + var capture = + new GameDesignSourceRepository.Capture( + new CommandSnapshot.Capture(operation, sources.command()), + new RealmPolicySnapshot.Capture(operation, sources.policy()), + Optional.of(new AssetSnapshot.Capture(operation, sources.asset())), + Optional.of( + new GameplayRuleSnapshot.Capture( + operation, sources.gameplayEvidence().orElseThrow())), + Optional.of( + new BrandingSourceSnapshot.Capture(operation, sources.branding().orElseThrow())), + Optional.of( + new TemplateConfigSourceSnapshot.Capture( + operation, sources.templateConfig().orElseThrow()))); + return new Fixture(operation, binding, sources, capture); + } + + private static GameDesignSourceRepository.SynchronizedSources sources( + DraftCommitBinding binding) { + var command = new CommandSnapshot(binding, "0", null, "sha256:" + "a".repeat(64), List.of()); + // Controlled inherited policy provenance; this World-only commit need not mutate policy. + var policy = + new RealmPolicySnapshot( + binding, + "1", + List.of( + new RealmPolicySource.Policy( + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + "inherited-policy", + net.firedevops.firemud.common.publication.RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\",\"entryPolicy\":\"PRESEEDED_ONLY\"}", + new tools.jackson.databind.ObjectMapper())))); + var asset = + new AssetSnapshot( + binding, "0", null, UUID.fromString("33333333-3333-4333-8333-333333333333"), List.of()); + var gameplay = + new GameplayRuleSnapshot( + binding, "0", null, UUID.fromString("44444444-4444-4444-8444-444444444444"), List.of()); + var branding = + new BrandingSourceSnapshot( + binding, "0", null, UUID.fromString("55555555-5555-4555-8555-555555555555"), List.of()); + var template = + new TemplateConfigSourceSnapshot( + binding, "0", null, UUID.fromString("66666666-6666-4666-8666-666666666666"), List.of()); + return new GameDesignSourceRepository.SynchronizedSources( + command, + policy, + Optional.of(asset), + Optional.of(gameplay), + Optional.of(branding), + Optional.of(template)); + } + + private static SelectedDraftGameLogicReceipt receipt( + GameDesignPublicationOperation operation, GameplayRuleSnapshot snapshot) { + var selection = operation.account().input().selection(); + var source = new GameplayRuleSelectedSource(snapshot.canonicalJson()); + UUID actor = UUID.randomUUID(); + var authorization = + new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + source, + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + var terminal = + GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation("test", authorization), + source.canonicalBytes(), + source.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + return new SelectedDraftGameLogicReceipt( + AuthoredDraftPublishSelection.fromStored(selection.canonicalJson(), selection.digest()), + authorization, + new AccountGameLogicIntakeSettlementEvidence(terminal)); + } + + private static void assertCode(Status.Code expected, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private void assertSanitizedUnavailable( + SelectedDraftPublicationDigestReadService service, PublicationDigestRequestBinding request) { + assertThatThrownBy(() -> service.read(NAMESPACE, request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> { + var status = ((StatusRuntimeException) failure).getStatus(); + assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(status.getDescription()) + .isEqualTo("Selected publication source readback unavailable") + .doesNotContain("secret"); + }); + } + + private record Fixture( + GameDesignPublicationOperation operation, + DraftCommitBinding binding, + GameDesignSourceRepository.SynchronizedSources sources, + GameDesignSourceRepository.Capture capture) {} +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java index 4a0efa3c9e..8304f5ca9e 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java @@ -67,6 +67,15 @@ class StartSessionLaunchDescriptorProducerTest { private static final long FENCE = 8L; private static final JsonMapper JSON = JsonMapper.builder().build(); + @Test + void selectedReleaseMatchingRetainsV2AndAcceptsOnlyFullV4() { + assertThat(PublishedReleaseBundleDto.isSelectedAttestationSchema("v2")).isTrue(); + assertThat(PublishedReleaseBundleDto.isSelectedAttestationSchema("v4")).isTrue(); + assertThat(PublishedReleaseBundleDto.isSelectedAttestationSchema("v1")).isFalse(); + assertThat(PublishedReleaseBundleDto.isSelectedAttestationSchema("v3")).isFalse(); + assertThat(PublishedReleaseBundleDto.isSelectedAttestationSchema(null)).isFalse(); + } + @Test void requiresExactReplayAndSameNamespacePeerBeforeOwnerWork() { var associationReader = mock(StartSessionTemplateAssociationReadService.class); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java index 714e30c47f..d296297cae 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java @@ -56,6 +56,38 @@ void selectorReleaseIsAssembledFromImmutableLocalBundleWithoutMutableOwnerReads( verifyReadOnlyCallsOnly(); } + @Test + void selectedFullV4ReadbackUsesExactEntityAndAutomationSchemas() throws Exception { + var selector = selectorEvidence(4); + var participants = + PublishedWorldSelectorFixtures.participants( + VERSION_ID, + selector, + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); + givenBundle(selectedFullBundle(selector, participants)); + + var result = + service.getCompleteLaunchBinding( + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + CONTROL_PLANE_REQUEST_ID, + descriptor.requestDigest(), + descriptor.resultDigest()); + + assertEquals( + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION, + result.releaseAttestation().schemaVersion()); + assertEquals( + List.of(4, 3, 1, 6, 2), + result.releaseAttestation().participantDigests().stream() + .map(AuthoredWorldReleaseAttestationEvidence.Participant::digestSchemaVersion) + .toList()); + assertEquals(selector, result.releaseAttestation().worldStartLocationEvidence()); + result.releaseAttestation().requireValid(descriptor); + verifyReadOnlyCallsOnly(); + } + @Test void completeLaunchBindingRejectsObsoleteOrUnselectedWorldSchemas() { for (int schema : List.of(2, 4)) { @@ -1003,6 +1035,12 @@ private WorldPublishedStartLocationEvidence selectorEvidence() throws Exception source.provenanceKind())); } + private WorldPublishedStartLocationEvidence selectorEvidence(int digestSchemaVersion) + throws Exception { + var base = selectorEvidence(); + return PublishedWorldSelectorFixtures.withDigestSchemaVersion(base, digestSchemaVersion); + } + private PublishedReleaseBundleDto selectorBundle( WorldPublishedStartLocationEvidence selector, List participants) { @@ -1029,6 +1067,32 @@ private PublishedReleaseBundleDto selectorBundle( selector); } + private PublishedReleaseBundleDto selectedFullBundle( + WorldPublishedStartLocationEvidence selector, + List participants) { + return new PublishedReleaseBundleDto( + bundle.id(), + bundle.tenantId(), + bundle.versionId(), + bundle.versionNumber(), + PublishedReleaseBundleContract.SELECTED_FULL_ATTESTATION_SCHEMA_VERSION, + selector.request().publishWorkflowId(), + bundle.manifestHash(), + bundle.requiredManifestAssetKeys(), + participants, + bundle.commandDefinitions(), + bundle.generationConfigRevision(), + bundle.scriptOnly(), + bundle.scriptPatchVersion(), + bundle.publishedAt(), + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.publishedReleaseBundleRef(), + bundle.manifestSchemaVersion(), + bundle.artifactDigests(), + selector); + } + private List selectorParticipants( WorldPublishedStartLocationEvidence selector) { return PublishedWorldSelectorFixtures.participants(VERSION_ID, selector).stream() diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java index 1c54a243b1..086d29c6df 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java @@ -2,14 +2,18 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.time.LocalDateTime; import java.util.List; +import java.util.Optional; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.client.AutomationScriptingClient; import net.firedevops.firemud.gamedesign.client.EntityManagementClient; @@ -20,13 +24,20 @@ import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptRepository; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationDigestReadService; import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; +import net.firedevops.firemud.gamedesign.service.PublicationFailureClassifier; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.springframework.dao.TransientDataAccessResourceException; class PublishGateServiceImplTest { @Mock private ControlPlaneDigestService controlPlaneDigestService; @@ -34,6 +45,8 @@ class PublishGateServiceImplTest { @Mock private EntityManagementClient entityManagementClient; @Mock private GameLogicClient gameLogicClient; @Mock private AutomationScriptingClient automationScriptingClient; + @Mock private SelectedDraftGameLogicReceiptRepository selectedGameLogicReceiptRepository; + @Mock private SelectedDraftPublicationDigestReadService selectedPublicationDigestReader; private PublishGateServiceImpl service; @@ -46,7 +59,10 @@ void setUp() { worldManagementClient, entityManagementClient, gameLogicClient, - automationScriptingClient); + automationScriptingClient, + selectedGameLogicReceiptRepository, + selectedPublicationDigestReader, + "test"); } @Test @@ -92,6 +108,10 @@ void collectFullVersionParticipantDigestsPassesWhenParticipantsConverge() { assertEquals(5, digests.size()); assertEquals("WORLD_MANAGEMENT", digests.get(0).participantKey()); + assertEquals( + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + "WORLD_MANAGEMENT"), + digests.get(0).digestSchemaVersion()); assertDoesNotThrow(() -> service.assertGatePassed(version, digests)); PublicationDigestRequestBinding expectedBinding = @@ -102,6 +122,269 @@ void collectFullVersionParticipantDigestsPassesWhenParticipantsConverge() { assertBinding(captureVersionBinding(automationScriptingClient), expectedBinding); } + @Test + void selectedFullVersionGateUsesCanonicalBindingAndExactReceiptForOwnerReads() { + VersionDto version = selectedVersion(); + PublicationDigestRequestBinding binding = selectedBinding(version); + SelectedDraftGameLogicReceipt receipt = + org.mockito.Mockito.mock(SelectedDraftGameLogicReceipt.class); + stubSelectedParticipantDigests(version, binding, receipt); + + List digests = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + + assertEquals(5, digests.size()); + assertDoesNotThrow(() -> service.assertSelectedGatePassed(version, digests)); + assertEquals(2, digests.get(4).digestSchemaVersion()); + assertEquals(6, digests.get(3).digestSchemaVersion()); + assertEquals("b".repeat(64), digests.getFirst().contentDigest()); + assertEquals("c".repeat(64), digests.get(4).contentDigest()); + verify(selectedPublicationDigestReader).read("test", binding); + verify(selectedPublicationDigestReader).read("test", binding, receipt); + org.mockito.Mockito.verifyNoInteractions(worldManagementClient, controlPlaneDigestService); + assertBinding(captureVersionBinding(entityManagementClient), binding); + ArgumentCaptor gameLogicBinding = + ArgumentCaptor.forClass(PublicationDigestRequestBinding.class); + verify(gameLogicClient) + .getDraftDesignDigestForVersion(gameLogicBinding.capture(), same(receipt)); + assertBinding(gameLogicBinding.getValue(), binding); + assertBinding(captureVersionBinding(automationScriptingClient), binding); + + var publicationOrder = + org.mockito.Mockito.inOrder( + selectedGameLogicReceiptRepository, selectedPublicationDigestReader, gameLogicClient); + publicationOrder.verify(selectedGameLogicReceiptRepository).readForPublication(binding); + publicationOrder.verify(selectedPublicationDigestReader).read("test", binding, receipt); + publicationOrder.verify(gameLogicClient).getDraftDesignDigestForVersion(binding, receipt); + verify(gameLogicClient, org.mockito.Mockito.never()) + .getDraftDesignDigestForVersion(any(PublicationDigestRequestBinding.class)); + } + + @Test + void selectedFullGateRejectsEveryMixedParticipantProfile() { + var version = selectedVersion(); + var binding = selectedBinding(version); + var receipt = org.mockito.Mockito.mock(SelectedDraftGameLogicReceipt.class); + stubSelectedParticipantDigests(version, binding, receipt); + var participants = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + for (int index = 0; index < participants.size(); index++) { + var mixed = new java.util.ArrayList<>(participants); + var participant = mixed.get(index); + mixed.set( + index, + new PublishParticipantDigestDto( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + participant.digestSchemaVersion() == 1 ? 2 : participant.digestSchemaVersion() - 1, + participant.abilitySchemaDigest(), + participant.errorCode(), + participant.errorMessage())); + assertThrows( + PublishGateFailureException.class, + () -> service.assertSelectedGatePassed(version, mixed), + "mixed profile for " + participant.participantKey()); + } + } + + @Test + void closureQualifiedSelectedGateRequiresWorldDigestSchemaFour() { + VersionDto version = selectedVersion(); + PublicationDigestRequestBinding binding = selectedBinding(version); + SelectedDraftGameLogicReceipt receipt = + org.mockito.Mockito.mock(SelectedDraftGameLogicReceipt.class); + stubSelectedParticipantDigests(version, binding, receipt); + when(selectedPublicationDigestReader.read("test", binding)) + .thenReturn( + new SelectedDraftPublicationDigestReadService.ReadResult( + binding, + binding.requestDigest(), + new DesignControlPlaneDigestDto( + binding.tenantId(), "7", "selected-commit", "c".repeat(64), 2), + new PublishParticipantDigestDto( + "WORLD_MANAGEMENT", "7", "selected-commit", "b".repeat(64), 4, null, null))); + + List digests = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + + assertEquals(4, digests.getFirst().digestSchemaVersion()); + assertEquals(2, digests.getLast().digestSchemaVersion()); + assertDoesNotThrow(() -> service.assertSelectedGatePassed(version, digests)); + } + + @Test + void selectedFullVersionGateKeepsMissingReceiptPendingAndNeverUsesLegacyRead() { + VersionDto version = selectedVersion(); + PublicationDigestRequestBinding binding = selectedBinding(version); + when(selectedGameLogicReceiptRepository.readForPublication(binding)) + .thenReturn(Optional.empty()); + stubNonGameLogicParticipants(version, binding); + + List digests = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + + assertEquals("PARTICIPANT_UNAVAILABLE", digests.get(2).errorCode()); + PublishGateFailureException thrown = + assertThrows( + PublishGateFailureException.class, + () -> service.assertSelectedGatePassed(version, digests)); + assertTrue(PublicationFailureClassifier.isRetryableParticipantDependencyFailure(thrown)); + verify(gameLogicClient, org.mockito.Mockito.never()) + .getDraftDesignDigestForVersion(any(PublicationDigestRequestBinding.class)); + verify(gameLogicClient, org.mockito.Mockito.never()) + .getDraftDesignDigestForVersion( + any(PublicationDigestRequestBinding.class), any(SelectedDraftGameLogicReceipt.class)); + } + + @Test + void selectedReceiptStorageInterruptionRemainsRetryable() { + VersionDto version = selectedVersion(); + PublicationDigestRequestBinding binding = selectedBinding(version); + when(selectedGameLogicReceiptRepository.readForPublication(binding)) + .thenThrow(new org.jooq.exception.DataAccessException("database unavailable")); + stubNonGameLogicParticipants(version, binding); + + List digests = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + + assertEquals("UNAVAILABLE", digests.get(2).errorCode()); + PublishGateFailureException thrown = + assertThrows( + PublishGateFailureException.class, + () -> service.assertSelectedGatePassed(version, digests)); + assertTrue(PublicationFailureClassifier.isRetryableParticipantDependencyFailure(thrown)); + } + + @Test + void selectedReceiptSpringStorageInterruptionRemainsRetryable() { + VersionDto version = selectedVersion(); + PublicationDigestRequestBinding binding = selectedBinding(version); + when(selectedGameLogicReceiptRepository.readForPublication(binding)) + .thenThrow(new TransientDataAccessResourceException("database unavailable")); + stubNonGameLogicParticipants(version, binding); + + List digests = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + + assertEquals("UNAVAILABLE", digests.get(2).errorCode()); + PublishGateFailureException thrown = + assertThrows( + PublishGateFailureException.class, + () -> service.assertSelectedGatePassed(version, digests)); + assertTrue(PublicationFailureClassifier.isRetryableParticipantDependencyFailure(thrown)); + } + + @Test + void selectedGameLogicSourceReadFailureRemainsRetryableAndPreventsClientCall() { + VersionDto version = selectedVersion(); + PublicationDigestRequestBinding binding = selectedBinding(version); + SelectedDraftGameLogicReceipt receipt = + org.mockito.Mockito.mock(SelectedDraftGameLogicReceipt.class); + stubSelectedParticipantDigests(version, binding, receipt); + when(selectedPublicationDigestReader.read("test", binding, receipt)) + .thenThrow(io.grpc.Status.UNAVAILABLE.asRuntimeException()); + + List digests = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + + assertEquals("UNAVAILABLE", digests.get(2).errorCode()); + PublishGateFailureException thrown = + assertThrows( + PublishGateFailureException.class, + () -> service.assertSelectedGatePassed(version, digests)); + assertTrue(PublicationFailureClassifier.isRetryableParticipantDependencyFailure(thrown)); + verify(gameLogicClient, org.mockito.Mockito.never()) + .getDraftDesignDigestForVersion(binding, receipt); + } + + @Test + void missingSelectedGameLogicSourceEvidencePreventsClientCall() { + VersionDto version = selectedVersion(); + PublicationDigestRequestBinding binding = selectedBinding(version); + SelectedDraftGameLogicReceipt receipt = + org.mockito.Mockito.mock(SelectedDraftGameLogicReceipt.class); + stubSelectedParticipantDigests(version, binding, receipt); + when(selectedPublicationDigestReader.read("test", binding, receipt)) + .thenThrow(io.grpc.Status.FAILED_PRECONDITION.asRuntimeException()); + + List digests = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + + assertEquals("FAILED_PRECONDITION", digests.get(2).errorCode()); + verify(gameLogicClient, org.mockito.Mockito.never()) + .getDraftDesignDigestForVersion(binding, receipt); + } + + @Test + void nullSelectedGameLogicSourceReadPreventsClientCall() { + VersionDto version = selectedVersion(); + PublicationDigestRequestBinding binding = selectedBinding(version); + SelectedDraftGameLogicReceipt receipt = + org.mockito.Mockito.mock(SelectedDraftGameLogicReceipt.class); + stubSelectedParticipantDigests(version, binding, receipt); + when(selectedPublicationDigestReader.read("test", binding, receipt)).thenReturn(null); + + List digests = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + + assertEquals("FAILED_PRECONDITION", digests.get(2).errorCode()); + verify(gameLogicClient, org.mockito.Mockito.never()) + .getDraftDesignDigestForVersion(binding, receipt); + } + + @Test + void selectedGameLogicSourceReadForAnotherRequestPreventsClientCall() { + VersionDto version = selectedVersion(); + PublicationDigestRequestBinding binding = selectedBinding(version); + SelectedDraftGameLogicReceipt receipt = + org.mockito.Mockito.mock(SelectedDraftGameLogicReceipt.class); + stubSelectedParticipantDigests(version, binding, receipt); + PublicationDigestRequestBinding other = + PublicationDigestRequestBinding.full( + binding.tenantId(), binding.versionId(), "other-request"); + when(selectedPublicationDigestReader.read("test", binding, receipt)) + .thenReturn(selectedSnapshot(other)); + + List digests = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + + assertEquals("FAILED_PRECONDITION", digests.get(2).errorCode()); + verify(gameLogicClient, org.mockito.Mockito.never()) + .getDraftDesignDigestForVersion(binding, receipt); + } + + @Test + void selectedFullVersionGateRejectsPrivateTenantKeyAsPublicationIdentity() { + VersionDto version = selectedVersion(); + PublicationDigestRequestBinding privateTenantBinding = + PublicationDigestRequestBinding.full("private-tenant-key", "7", "selected-request-1"); + + assertThrows( + IllegalArgumentException.class, + () -> + service.collectSelectedFullVersionParticipantDigests( + version, privateTenantBinding, privateTenantBinding.derivedWorkflowIdentity())); + org.mockito.Mockito.verifyNoInteractions( + worldManagementClient, + entityManagementClient, + gameLogicClient, + automationScriptingClient, + selectedGameLogicReceiptRepository); + } + @Test void fullVersionGateRejectsUnavailableGameLogicManifest() { VersionDto version = @@ -139,8 +422,9 @@ void fullVersionGateRejectsUnavailableGameLogicManifest() { assertTrue(thrown.getMessage().contains("GAME_LOGIC")); } - @Test - void fullVersionGateRejectsObsoleteWorldDigestSchema() { + @ParameterizedTest + @ValueSource(ints = {2, 4}) + void fullVersionGateRejectsObsoleteAndUnknownWorldSchemas(int worldSchema) { VersionDto version = new VersionDto( 7L, @@ -157,13 +441,13 @@ void fullVersionGateRejectsObsoleteWorldDigestSchema() { List digests = List.of( new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 2, null, null), + "WORLD_MANAGEMENT", "7", "version:7", "digest-world", worldSchema, null, null), new PublishParticipantDigestDto( "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 1, null, null), new PublishParticipantDigestDto( "GAME_LOGIC", "7", "version:7", "digest-logic", 1, null, null), new PublishParticipantDigestDto( - "AUTOMATION_SCRIPTING", "7", "version:7", "digest-script", 4, null, null), + "AUTOMATION_SCRIPTING", "7", "version:7", "digest-script", 5, null, null), new PublishParticipantDigestDto( "GAME_DESIGN_CONTROL_PLANE", "7", "version:7", "digest-design", 1, null, null)); @@ -456,6 +740,246 @@ void scriptPatchGatePassesWhenParticipantsConverge() { PublicationDigestRequestBinding.patch("tenant-1", "7", "patch-1", "publish-request-1")); } + @Test + void unavailableSelectedReaderFailsBothOwnersWithoutLegacyFallback() { + VersionDto version = selectedVersion(); + var binding = selectedBinding(version); + var receipt = org.mockito.Mockito.mock(SelectedDraftGameLogicReceipt.class); + stubSelectedParticipantDigests(version, binding, receipt); + when(selectedPublicationDigestReader.read("test", binding)) + .thenThrow(io.grpc.Status.UNAVAILABLE.asRuntimeException()); + when(selectedPublicationDigestReader.read("test", binding, receipt)) + .thenThrow(io.grpc.Status.UNAVAILABLE.asRuntimeException()); + + var digests = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + + assertEquals(5, digests.size()); + assertEquals("UNAVAILABLE", digests.getFirst().errorCode()); + assertEquals("UNAVAILABLE", digests.get(4).errorCode()); + assertNull(digests.getFirst().appliedCommitId()); + assertNull(digests.getFirst().digestSchemaVersion()); + PublishGateFailureException failure = + assertThrows( + PublishGateFailureException.class, + () -> service.assertSelectedGatePassed(version, digests)); + assertEquals(PublishGateFailureCode.PARTICIPANT_UNAVAILABLE, failure.failureCode()); + assertEquals("UNAVAILABLE", failure.participantFailureCode()); + assertTrue(PublicationFailureClassifier.isRetryableParticipantDependencyFailure(failure)); + org.mockito.Mockito.verifyNoInteractions(worldManagementClient, controlPlaneDigestService); + verify(gameLogicClient, org.mockito.Mockito.never()) + .getDraftDesignDigestForVersion(binding, receipt); + } + + @Test + void missingSelectedReaderFailsClosed() { + VersionDto version = selectedVersion(); + var binding = selectedBinding(version); + service = + new PublishGateServiceImpl( + controlPlaneDigestService, + worldManagementClient, + entityManagementClient, + gameLogicClient, + automationScriptingClient, + selectedGameLogicReceiptRepository); + when(selectedGameLogicReceiptRepository.readForPublication(binding)) + .thenReturn(Optional.empty()); + when(entityManagementClient.getDraftDesignDigestForVersion(binding)) + .thenReturn( + new PublishParticipantDigestDto( + "ENTITY_MANAGEMENT", + "7", + null, + null, + null, + "UNSUPPORTED_SCOPE", + "selected Entity evidence unavailable")); + when(automationScriptingClient.getDraftDesignDigestForVersion(binding)) + .thenReturn( + new PublishParticipantDigestDto( + "AUTOMATION_SCRIPTING", + "7", + null, + null, + null, + "UNSUPPORTED_SCOPE", + "selected Automation evidence unavailable")); + + var digests = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + + assertEquals(5, digests.size()); + assertEquals("PARTICIPANT_UNAVAILABLE", digests.getFirst().errorCode()); + assertEquals("PARTICIPANT_UNAVAILABLE", digests.get(4).errorCode()); + assertThrows( + PublishGateFailureException.class, + () -> service.assertSelectedGatePassed(version, digests)); + org.mockito.Mockito.verifyNoInteractions(worldManagementClient, controlPlaneDigestService); + } + + @Test + void selectedSnapshotForAnotherRequestCannotSatisfyEitherOwner() { + VersionDto version = selectedVersion(); + var binding = selectedBinding(version); + var other = PublicationDigestRequestBinding.full(binding.tenantId(), "7", "other-request"); + when(selectedPublicationDigestReader.read("test", binding)).thenReturn(selectedSnapshot(other)); + when(selectedGameLogicReceiptRepository.readForPublication(binding)) + .thenReturn(Optional.empty()); + + var digests = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + + assertEquals("FAILED_PRECONDITION", digests.getFirst().errorCode()); + assertEquals("FAILED_PRECONDITION", digests.get(4).errorCode()); + org.mockito.Mockito.verifyNoInteractions(worldManagementClient, controlPlaneDigestService); + } + + @Test + void selectedGateRequiresSchemaTwoAndPreservesUnsupportedOwnerDenial() { + VersionDto version = selectedVersion(); + var binding = selectedBinding(version); + var receipt = org.mockito.Mockito.mock(SelectedDraftGameLogicReceipt.class); + stubSelectedParticipantDigests(version, binding, receipt); + var digests = + new java.util.ArrayList<>( + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity())); + var selected = digests.get(4); + digests.set( + 4, + new PublishParticipantDigestDto( + selected.participantKey(), + selected.scopeValue(), + selected.appliedCommitId(), + selected.contentDigest(), + 1, + null, + null)); + var unsupported = + assertThrows( + PublishGateFailureException.class, + () -> service.assertSelectedGatePassed(version, digests)); + assertEquals(PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA, unsupported.failureCode()); + assertTrue(unsupported.getMessage().contains("GAME_DESIGN_CONTROL_PLANE")); + + when(entityManagementClient.getDraftDesignDigestForVersion(binding)) + .thenReturn( + new PublishParticipantDigestDto( + "ENTITY_MANAGEMENT", + "7", + null, + null, + null, + "UNSUPPORTED_SCOPE", + "selected owner evidence unavailable")); + var denied = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + assertEquals(5, denied.size()); + var failure = + assertThrows( + PublishGateFailureException.class, + () -> service.assertSelectedGatePassed(version, denied)); + assertEquals(PublishGateFailureCode.PARTICIPANT_UNAVAILABLE, failure.failureCode()); + assertEquals("UNSUPPORTED_SCOPE", failure.participantFailureCode()); + + when(entityManagementClient.getDraftDesignDigestForVersion(binding)) + .thenReturn( + new PublishParticipantDigestDto( + "ENTITY_MANAGEMENT", "7", "selected-commit", "entity-digest", 3, null, null)); + when(automationScriptingClient.getDraftDesignDigestForVersion(binding)) + .thenReturn( + new PublishParticipantDigestDto( + "AUTOMATION_SCRIPTING", + "7", + null, + null, + null, + "UNSUPPORTED_SCOPE", + "selected Automation evidence unavailable")); + var automationDenied = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + var automationFailure = + assertThrows( + PublishGateFailureException.class, + () -> service.assertSelectedGatePassed(version, automationDenied)); + assertEquals("UNSUPPORTED_SCOPE", automationFailure.participantFailureCode()); + } + + private void stubSelectedParticipantDigests( + VersionDto version, + PublicationDigestRequestBinding binding, + SelectedDraftGameLogicReceipt receipt) { + stubNonGameLogicParticipants(version, binding); + when(selectedGameLogicReceiptRepository.readForPublication(binding)) + .thenReturn(Optional.of(receipt)); + when(gameLogicClient.getDraftDesignDigestForVersion(binding, receipt)) + .thenReturn( + new PublishParticipantDigestDto( + "GAME_LOGIC", "7", "selected-commit", "logic-digest", 1, null, null)); + } + + private void stubNonGameLogicParticipants( + VersionDto version, PublicationDigestRequestBinding binding) { + when(selectedPublicationDigestReader.read("test", binding)) + .thenReturn(selectedSnapshot(binding)); + when(selectedPublicationDigestReader.read( + org.mockito.ArgumentMatchers.eq("test"), + org.mockito.ArgumentMatchers.eq(binding), + any(SelectedDraftGameLogicReceipt.class))) + .thenReturn(selectedSnapshot(binding)); + when(entityManagementClient.getDraftDesignDigestForVersion(binding)) + .thenReturn( + new PublishParticipantDigestDto( + "ENTITY_MANAGEMENT", "7", "selected-commit", "entity-digest", 3, null, null)); + when(automationScriptingClient.getDraftDesignDigestForVersion(binding)) + .thenReturn( + new PublishParticipantDigestDto( + "AUTOMATION_SCRIPTING", + "7", + "selected-commit", + "automation-digest", + 6, + null, + null)); + } + + private static SelectedDraftPublicationDigestReadService.ReadResult selectedSnapshot( + PublicationDigestRequestBinding binding) { + return new SelectedDraftPublicationDigestReadService.ReadResult( + binding, + binding.requestDigest(), + new DesignControlPlaneDigestDto( + binding.tenantId(), "7", "selected-commit", "c".repeat(64), 2), + new PublishParticipantDigestDto( + "WORLD_MANAGEMENT", "7", "selected-commit", "b".repeat(64), 4, null, null)); + } + + private static VersionDto selectedVersion() { + return new VersionDto( + 7L, + "private-tenant-key", + 8, + VersionLifecycleState.DRAFT, + 2L, + null, + null, + false, + "selected notes", + LocalDateTime.now(), + LocalDateTime.now()); + } + + private static PublicationDigestRequestBinding selectedBinding(VersionDto version) { + return PublicationDigestRequestBinding.full( + "11111111-1111-4111-8111-111111111111", String.valueOf(version.id()), "selected-request-1"); + } + private static PublicationDigestRequestBinding captureVersionBinding( WorldManagementClient client) { ArgumentCaptor captor = @@ -531,7 +1055,7 @@ void scriptPatchGateFailsClosedForWrongParticipantSet() { 7L, "script-patch:patch-1", "digest-world", - 2, + 3, null, null)); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java index 4b656d76aa..4ae810148b 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java @@ -37,6 +37,52 @@ void exactRepairAcceptsCompleteSelectorV2Bundle() throws Exception { selectorBundle(selector, selectorParticipants(selector)), exportedManifest)); } + @Test + void exactRepairAcceptsFull4VectorAndRejectsLegacyParticipantSchemas() throws Exception { + var selector = selectorEvidence(4); + var participants = + PublishedWorldSelectorFixtures.participants( + VERSION_ID, + selector, + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); + var full = bundle("v4", selector, participants); + assertDoesNotThrow( + () -> PublishedReleaseBundleContract.requireExactRepairMatch(full, exportedManifest)); + + var legacyAutomation = participants.get(3); + var mixed = + replaceParticipant( + participants, + 3, + new PublishParticipantDigestDto( + legacyAutomation.participantKey(), + legacyAutomation.scopeValue(), + legacyAutomation.baseVersionId(), + legacyAutomation.appliedCommitId(), + legacyAutomation.contentDigest(), + 5, + legacyAutomation.abilitySchemaDigest(), + legacyAutomation.errorCode(), + legacyAutomation.errorMessage())); + assertSelectorRepairRejected( + bundle("v4", selector, mixed), + "Selected-full release requires all exact successful ordered release participants"); + IllegalArgumentException denied = + assertThrows( + IllegalArgumentException.class, + () -> + PublishedReleaseBundleContract.requireFreshSelectedFullParticipantVector( + VERSION_ID, + selector.request().appliedCommitId(), + PublishedWorldSelectorFixtures.participants( + VERSION_ID, + selector, + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION))); + assertEquals( + "Selected-full release requires the exact 4/3/1/6/2 successful participant vector", + denied.getMessage()); + } + @Test void exactRepairRejectsMalformedSelectorV2Binding() throws Exception { WorldPublishedStartLocationEvidence selector = selectorEvidence(); @@ -294,6 +340,12 @@ private static WorldPublishedStartLocationEvidence selectorEvidence() throws Exc "NEW_GAME_ROW")); } + private static WorldPublishedStartLocationEvidence selectorEvidence(int digestSchemaVersion) + throws Exception { + var base = selectorEvidence(); + return PublishedWorldSelectorFixtures.withDigestSchemaVersion(base, digestSchemaVersion); + } + private static List selectorParticipants( WorldPublishedStartLocationEvidence selector) { return PublishedWorldSelectorFixtures.participants(VERSION_ID, selector).stream() diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java index 20de82ffc8..612b022b33 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java @@ -43,12 +43,13 @@ class PublishedReleaseBundleServiceImplTest { private PublishedReleaseBundleServiceImpl service; @Test - void selectorV2PersistsActualOriginalBytesAndRetryReturnsStoredEvidenceWithoutResolvingDefaults() - throws Exception { + void + selectedFullV4PersistsActualOriginalBytesAndRetryReturnsStoredEvidenceWithoutResolvingDefaults() + throws Exception { var evidence = selectorEvidence(); var participants = PublishedWorldSelectorFixtures.participants( - 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); // ISOLATED source-repository response; this test covers service assembly only. when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) .thenReturn(List.of(validCommandDefinition())); @@ -70,7 +71,7 @@ void selectorV2PersistsActualOriginalBytesAndRetryReturnsStoredEvidenceWithoutRe "genrev-1", participants, evidence); - assertEquals("v2", first.attestationSchemaVersion()); + assertEquals("v4", first.attestationSchemaVersion()); assertThat(first.worldPublishedStartLocationEvidence().canonicalBytes()) .containsExactly(evidence.canonicalBytes()); assertThat(first.commandDefinitions()).containsExactly(validCommandDefinition()); @@ -102,9 +103,8 @@ void selectorV2PersistsActualOriginalBytesAndRetryReturnsStoredEvidenceWithoutRe evidence)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("IDEMPOTENCY_CONFLICT"); - assertThatThrownBy(() -> PublishedReleaseBundleContract.requireSupportedSchemaForLaunch(first)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("SCHEMA_VERSION_UNSUPPORTED"); + PublishedReleaseBundleContract.requireSelectedFullBinding(first); + PublishedReleaseBundleContract.requireSupportedSchemaForLaunch(first); PublishedReleaseBundleContract.requireExactRepairMatch(first, emptyManifest()); assertThatThrownBy( () -> PublishedReleaseBundleContract.requireExactRepairMatch(first, logoManifest())) @@ -113,12 +113,58 @@ void selectorV2PersistsActualOriginalBytesAndRetryReturnsStoredEvidenceWithoutRe } @Test - void selectorV2RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChangedWorldDigest() + void exactRetainedV2RetryStillReturnsItsOriginalSelectorWithoutWriting() throws Exception { + var evidence = selectorEvidence(3); + var participants = + PublishedWorldSelectorFixtures.participants( + 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + var retained = new PublishedReleaseBundle(); + retained.setId(11L); + retained.setPublishedReleaseBundleRef("retained-v2-release"); + retained.setTenantId("tenant-1"); + retained.setVersionId(7L); + retained.setCanonicalTenantId(sourceIdentity().getCanonicalTenantId()); + retained.setCanonicalVersionId(sourceIdentity().getCanonicalVersionId()); + retained.setVersionNumber(selectorVersion().versionNumber()); + retained.setAttestationSchemaVersion("v2"); + retained.setPublishWorkflowId("publish-workflow"); + retained.setManifestHash(MANIFEST_HASH); + retained.setManifestSchemaVersion(1); + retained.setArtifactDigestsJson("[]"); + retained.setGenerationConfigRevision("genrev-1"); + retained.setRequiredManifestAssetKeysJson("[]"); + retained.setParticipantDigestsJson(new ObjectMapper().writeValueAsString(participants)); + retained.setCommandDefinitionsJson( + new ObjectMapper().writeValueAsString(List.of(validCommandDefinition()))); + retained.setWorldPublishedStartLocationEvidenceJson( + new String(evidence.canonicalBytes(), StandardCharsets.UTF_8)); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(retained)); + when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) + .thenReturn(List.of(validCommandDefinition())); + + var retry = + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + participants, + evidence); + + assertEquals("v2", retry.attestationSchemaVersion()); + assertThat(retry.worldPublishedStartLocationEvidence().canonicalBytes()) + .containsExactly(evidence.canonicalBytes()); + org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); + org.mockito.Mockito.verifyNoInteractions(versionRepository); + } + + @Test + void selectedFullV4RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChangedWorldDigest() throws Exception { var evidence = selectorEvidence(); var participants = PublishedWorldSelectorFixtures.participants( - 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); assertThatThrownBy( () -> service.createFullVersionBundle( @@ -159,7 +205,7 @@ void selectorV2RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChangedWorl null, world.appliedCommitId(), "e".repeat(64), - 3, + world.digestSchemaVersion(), null, null, null)); @@ -173,11 +219,62 @@ void selectorV2RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChangedWorl changed, evidence)) .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + PublishedWorldSelectorFixtures.participants( + 7L, + evidence, + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + evidence)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Selected-full"); + org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); + } + + @Test + void selectedFullV4RejectsEveryMixedParticipantSchemaBeforeWrite() throws Exception { + var evidence = selectorEvidence(); + var participants = + PublishedWorldSelectorFixtures.participants( + 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); + for (int index = 0; index < participants.size(); index++) { + var mixed = new java.util.ArrayList<>(participants); + var participant = mixed.get(index); + mixed.set( + index, + new PublishParticipantDigestDto( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + participant.digestSchemaVersion() == 1 ? 2 : participant.digestSchemaVersion() - 1, + participant.abilitySchemaDigest(), + participant.errorCode(), + participant.errorMessage())); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + mixed, + evidence)) + .as("mixed profile for %s", participant.participantKey()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Selected-full release requires the exact 4/3/1/6/2"); + } org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); } @Test - void selectorV2RequiresSelectedSourceCaptureBeforeBundleWrite() throws Exception { + void selectedFullV4RequiresSelectedSourceCaptureBeforeBundleWrite() throws Exception { var evidence = selectorEvidence(); when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) .thenThrow(new IllegalStateException("SELECTED_SOURCE_CAPTURE_UNAVAILABLE")); @@ -192,7 +289,7 @@ void selectorV2RequiresSelectedSourceCaptureBeforeBundleWrite() throws Exception PublishedWorldSelectorFixtures.participants( 7L, evidence, - AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION), evidence)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("SELECTED_SOURCE_CAPTURE_UNAVAILABLE"); @@ -220,7 +317,7 @@ void historicalReleaseNeverGainsSelectorAndCorruptedStoredCarrierFailsReadback() PublishedWorldSelectorFixtures.participants( 7L, evidence, - AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION), evidence)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("selector-ineligible"); @@ -235,15 +332,22 @@ void historicalReleaseNeverGainsSelectorAndCorruptedStoredCarrierFailsReadback() } private WorldPublishedStartLocationEvidence selectorEvidence() throws Exception { - return PublishedWorldSelectorFixtures.evidence( - new TargetProof( - sourceIdentity().getCanonicalTenantId(), - sourceIdentity().getCanonicalVersionId(), - 7L, - "tenant-1", - 42L, - "tenant-1", - "NEW_GAME_ROW")); + return selectorEvidence(4); + } + + private WorldPublishedStartLocationEvidence selectorEvidence(int digestSchemaVersion) + throws Exception { + var base = + PublishedWorldSelectorFixtures.evidence( + new TargetProof( + sourceIdentity().getCanonicalTenantId(), + sourceIdentity().getCanonicalVersionId(), + 7L, + "tenant-1", + 42L, + "tenant-1", + "NEW_GAME_ROW")); + return PublishedWorldSelectorFixtures.withDigestSchemaVersion(base, digestSchemaVersion); } private VersionDto selectorVersion() { @@ -406,7 +510,7 @@ void selectedBundleEntryPointRequiresCapturedCommandAndPolicySources() throws Ex var evidence = selectorEvidence(); var participants = PublishedWorldSelectorFixtures.participants( - 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); when(versionRepository.findByTenantIdAndId("tenant-1", 7L)) .thenReturn(Optional.of(sourceIdentity())); @@ -447,7 +551,7 @@ void selectedFullVersionBundlePersistsImmutableAttestation() throws Exception { var evidence = selectorEvidence(); var participants = PublishedWorldSelectorFixtures.participants( - 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) .thenReturn(List.of(validCommandDefinition())); when(repository.save(any(PublishedReleaseBundle.class))) @@ -479,7 +583,7 @@ void selectedFullVersionBundlePersistsImmutableAttestation() throws Exception { assertEquals(List.of("logo.png"), dto.requiredManifestAssetKeys()); assertEquals(participants, dto.participantDigests()); assertEquals(List.of(validCommandDefinition()), dto.commandDefinitions()); - assertEquals("v2", dto.attestationSchemaVersion()); + assertEquals("v4", dto.attestationSchemaVersion()); assertEquals("owner-issued-reference-11", dto.publishedReleaseBundleRef()); assertEquals(sourceIdentity().getCanonicalTenantId(), dto.canonicalTenantId()); assertEquals(sourceIdentity().getCanonicalVersionId(), dto.canonicalVersionId()); @@ -531,7 +635,9 @@ private void assertSelectedCommandsRejected( emptyManifest(), "genrev-1", PublishedWorldSelectorFixtures.participants( - 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + 7L, + evidence, + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION), evidence)); org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index cb2fc917c8..3154858876 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamedesign.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -28,6 +29,10 @@ import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.client.AutomationScriptingClient; +import net.firedevops.firemud.gamedesign.client.EntityManagementClient; +import net.firedevops.firemud.gamedesign.client.GameLogicClient; +import net.firedevops.firemud.gamedesign.client.WorldManagementClient; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; @@ -48,6 +53,9 @@ import net.firedevops.firemud.gamedesign.model.PublishType; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptRepository; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationDigestReadService; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; @@ -55,6 +63,7 @@ import net.firedevops.firemud.gamedesign.service.AssetExportService; import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.PublicationFailureClassifier; import net.firedevops.firemud.gamedesign.service.PublishAttemptService; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; import net.firedevops.firemud.gamedesign.service.PublishGateService; @@ -66,6 +75,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; import org.mapstruct.factory.Mappers; import org.mockito.InOrder; import org.mockito.Mock; @@ -152,21 +162,25 @@ void setup() { .when(publishAttemptService) .executeFullVersionTransaction(any()); VersionMapper mapper = Mappers.getMapper(VersionMapper.class); - service = - new VersionPublishCommandServiceImpl( - versionRepository, - gameRepository, - publishAttemptRepository, - mapper, - assetExportService, - publishAttemptService, - publishGateService, - controlPlaneDigestService, - versionAssetArtifactService, - publishedReleaseBundleService, - recordedParticipantDigestService, - authoredSelections, - worldProducerProvider); + service = commandService(mapper, publishGateService); + } + + private VersionPublishCommandServiceImpl commandService( + VersionMapper mapper, PublishGateService gateService) { + return new VersionPublishCommandServiceImpl( + versionRepository, + gameRepository, + publishAttemptRepository, + mapper, + assetExportService, + publishAttemptService, + gateService, + controlPlaneDigestService, + versionAssetArtifactService, + publishedReleaseBundleService, + recordedParticipantDigestService, + authoredSelections, + worldProducerProvider); } @Test @@ -247,6 +261,9 @@ void legacyPendingAttemptIsDeniedBeforeReadbackOrMutation() { assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); verify(publishAttemptRepository, never()).save(any(PublishAttempt.class)); verify(authoredSelections, never()).reserve(any(PublishIntent.class)); + verify(publishGateService, never()) + .collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class)); verify(publishGateService, never()) .collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class)); @@ -411,6 +428,7 @@ void succeededReplayUsesStoredBundleAfterLifecycleDriftWithoutWritesOrGates() { void selectedSucceededReplayRevalidatesExactTerminalEvidenceWithoutWriting( VersionLifecycleState lifecycleState) throws Exception { SelectedSucceededReplayFixture fixture = selectedSucceededReplayFixture(lifecycleState); + delegateGateAssertionsToRealGate(); PublishWorkflowSnapshot snapshot = service.reconcileFullVersionPublish(fixture.request()); @@ -425,7 +443,7 @@ void selectedSucceededReplayRevalidatesExactTerminalEvidenceWithoutWriting( .PUBLISHED); verify(publishAttemptRepository).requirePublishedOperation(fixture.attempt()); verify(publishGateService) - .assertGatePassed( + .assertSelectedGatePassed( any(VersionDto.class), org.mockito.ArgumentMatchers.eq(fixture.participantDigests())); verify(recordedParticipantDigestService) .assertMatchesRecordedDigests( @@ -545,7 +563,7 @@ void selectedSucceededReplayRejectsPublicationGateMismatch() throws Exception { org.mockito.Mockito.doThrow( new IllegalStateException("ISOLATED retained publication gate mismatch")) .when(publishGateService) - .assertGatePassed( + .assertSelectedGatePassed( any(VersionDto.class), org.mockito.ArgumentMatchers.eq(fixture.participantDigests())); assertThrows( @@ -553,7 +571,7 @@ void selectedSucceededReplayRejectsPublicationGateMismatch() throws Exception { () -> service.reconcileFullVersionPublish(fixture.request())); verify(publishGateService) - .assertGatePassed( + .assertSelectedGatePassed( any(VersionDto.class), org.mockito.ArgumentMatchers.eq(fixture.participantDigests())); assertNoPublicationWrites(); } @@ -853,8 +871,8 @@ void bundleFailureAfterExternalExportRemainsPendingWithoutDeletingSharedAssets() when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, request.publishWorkflowId())) .thenReturn(staged); when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) + when(publishGateService.collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class))) .thenReturn(participantDigests()); when(controlPlaneDigestService.getDigestForVersion(any(VersionDto.class))) .thenReturn(new DesignControlPlaneDigestDto("tenant-1", "10", "version:10", "digest", 1)); @@ -897,8 +915,8 @@ void bundleFailureAfterExternalExportRemainsPendingWithoutDeletingSharedAssets() names = {"UNAVAILABLE", "DEADLINE_EXCEEDED"}) void transientParticipantReadLeavesSelectedFullAttemptPending(Status.Code statusCode) { SelectedPublishFixture fixture = selectedPublishFixture(1); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) + when(publishGateService.collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class))) .thenThrow(new StatusRuntimeException(Status.fromCode(statusCode))); VersionPublishCommandServiceImpl.PendingReconciliationException thrown = @@ -917,6 +935,194 @@ void transientParticipantReadLeavesSelectedFullAttemptPending(Status.Code status verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); } + @ParameterizedTest + @EnumSource(TransientCollectorFailure.class) + void transientSelectedCollectorObservationsLeaveAttemptPending( + TransientCollectorFailure transientFailure) { + SelectedPublishFixture fixture = selectedPublishFixture(1); + var worldClient = org.mockito.Mockito.mock(WorldManagementClient.class); + var entityClient = org.mockito.Mockito.mock(EntityManagementClient.class); + var gameLogicClient = org.mockito.Mockito.mock(GameLogicClient.class); + var automationClient = org.mockito.Mockito.mock(AutomationScriptingClient.class); + var selectedReceiptRepository = + org.mockito.Mockito.mock(SelectedDraftGameLogicReceiptRepository.class); + var selectedDigestReader = + org.mockito.Mockito.mock(SelectedDraftPublicationDigestReadService.class); + var binding = + PublicationDigestRequestBinding.full( + fixture.request().intent().canonicalTenantId().toString(), + String.valueOf(fixture.version().getId()), + fixture.request().publishRequestId()); + org.mockito.ArgumentMatcher exactBinding = + candidate -> + candidate != null + && java.util.Arrays.equals( + binding.canonicalPreimage(), candidate.canonicalPreimage()); + var selectedCommit = fixture.reservation().selection().selectedCommit().commitId().toString(); + if (transientFailure == TransientCollectorFailure.SELECTED_SNAPSHOT_UNAVAILABLE) { + when(selectedDigestReader.read( + org.mockito.ArgumentMatchers.eq("test"), + org.mockito.ArgumentMatchers.argThat(exactBinding))) + .thenThrow(Status.UNAVAILABLE.asRuntimeException()); + when(selectedDigestReader.read( + org.mockito.ArgumentMatchers.eq("test"), + org.mockito.ArgumentMatchers.argThat(exactBinding), + org.mockito.ArgumentMatchers.any(SelectedDraftGameLogicReceipt.class))) + .thenThrow(Status.UNAVAILABLE.asRuntimeException()); + } else { + when(selectedDigestReader.read( + org.mockito.ArgumentMatchers.eq("test"), + org.mockito.ArgumentMatchers.argThat(exactBinding))) + .thenReturn( + new SelectedDraftPublicationDigestReadService.ReadResult( + binding, + binding.requestDigest(), + new DesignControlPlaneDigestDto( + binding.tenantId(), "10", selectedCommit, "c".repeat(64), 2), + new PublishParticipantDigestDto( + "WORLD_MANAGEMENT", + "10", + null, + selectedCommit, + "d".repeat(64), + 4, + null, + null, + null))); + } + when(entityClient.getDraftDesignDigestForVersion( + org.mockito.ArgumentMatchers.argThat(exactBinding))) + .thenReturn( + new PublishParticipantDigestDto( + "ENTITY_MANAGEMENT", + "10", + null, + selectedCommit, + "a".repeat(64), + 3, + null, + null, + null)); + when(automationClient.getDraftDesignDigestForVersion( + org.mockito.ArgumentMatchers.argThat(exactBinding))) + .thenReturn( + new PublishParticipantDigestDto( + "AUTOMATION_SCRIPTING", + "10", + null, + selectedCommit, + "b".repeat(64), + 6, + null, + null, + null)); + if (transientFailure == TransientCollectorFailure.GAME_LOGIC_RECEIPT_MISSING) { + when(selectedReceiptRepository.readForPublication( + org.mockito.ArgumentMatchers.argThat(exactBinding))) + .thenReturn(Optional.empty()); + } else if (transientFailure + == TransientCollectorFailure.GAME_LOGIC_RECEIPT_STORAGE_UNAVAILABLE) { + when(selectedReceiptRepository.readForPublication( + org.mockito.ArgumentMatchers.argThat(exactBinding))) + .thenThrow(new org.jooq.exception.DataAccessException("database unavailable")); + } else { + var selectedReceipt = org.mockito.Mockito.mock(SelectedDraftGameLogicReceipt.class); + when(selectedReceiptRepository.readForPublication( + org.mockito.ArgumentMatchers.argThat(exactBinding))) + .thenReturn(Optional.of(selectedReceipt)); + when(gameLogicClient.getDraftDesignDigestForVersion( + org.mockito.ArgumentMatchers.argThat(exactBinding), same(selectedReceipt))) + .thenReturn( + new PublishParticipantDigestDto( + "GAME_LOGIC", + "10", + null, + selectedCommit, + "e".repeat(64), + 1, + "sha256:" + "f".repeat(64), + null, + null)); + } + PublishGateServiceImpl realGateService = + new PublishGateServiceImpl( + controlPlaneDigestService, + worldClient, + entityClient, + gameLogicClient, + automationClient, + selectedReceiptRepository, + selectedDigestReader, + "test"); + VersionMapper mapper = Mappers.getMapper(VersionMapper.class); + service = commandService(mapper, realGateService); + + VersionDto versionDto = mapper.toDto(fixture.version()); + List observed = + realGateService.collectSelectedFullVersionParticipantDigests( + versionDto, binding, fixture.request().publishWorkflowId()); + if (transientFailure == TransientCollectorFailure.SELECTED_SNAPSHOT_UNAVAILABLE) { + assertEquals("UNAVAILABLE", observed.getFirst().errorCode()); + assertNull(observed.getFirst().appliedCommitId()); + assertNull(observed.getFirst().digestSchemaVersion()); + assertEquals("UNAVAILABLE", observed.getLast().errorCode()); + assertNull(observed.getLast().appliedCommitId()); + assertNull(observed.getLast().digestSchemaVersion()); + assertEquals("UNAVAILABLE", observed.get(2).errorCode()); + assertNull(observed.get(2).appliedCommitId()); + assertNull(observed.get(2).digestSchemaVersion()); + } else { + assertTrue(observed.getFirst().succeeded()); + assertEquals(selectedCommit, observed.getFirst().appliedCommitId()); + assertEquals(4, observed.getFirst().digestSchemaVersion()); + assertTrue(observed.getLast().succeeded()); + assertEquals(selectedCommit, observed.getLast().appliedCommitId()); + assertEquals(2, observed.getLast().digestSchemaVersion()); + assertEquals( + transientFailure == TransientCollectorFailure.GAME_LOGIC_RECEIPT_MISSING + ? "PARTICIPANT_UNAVAILABLE" + : "UNAVAILABLE", + observed.get(2).errorCode()); + assertNull(observed.get(2).appliedCommitId()); + assertNull(observed.get(2).digestSchemaVersion()); + } + PublishGateFailureException gateFailure = + assertThrows( + PublishGateFailureException.class, + () -> realGateService.assertSelectedGatePassed(versionDto, observed)); + assertTrue(PublicationFailureClassifier.isRetryableParticipantDependencyFailure(gateFailure)); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> reflectiveUnitHarnessReconcileSelectedPublicationMechanics(fixture.request())); + + assertTrue(thrown.getMessage().contains("temporarily unavailable")); + assertEquals(PublishAttemptStatus.PENDING, fixture.attempt().getStatus()); + org.mockito.Mockito.verify(selectedDigestReader, org.mockito.Mockito.times(2)) + .read( + org.mockito.ArgumentMatchers.eq("test"), + org.mockito.ArgumentMatchers.argThat(exactBinding)); + if (transientFailure == TransientCollectorFailure.SELECTED_SNAPSHOT_UNAVAILABLE) { + org.mockito.Mockito.verify(selectedDigestReader, org.mockito.Mockito.times(2)) + .read( + org.mockito.ArgumentMatchers.eq("test"), + org.mockito.ArgumentMatchers.argThat(exactBinding), + org.mockito.ArgumentMatchers.any(SelectedDraftGameLogicReceipt.class)); + verify(gameLogicClient, never()) + .getDraftDesignDigestForVersion( + org.mockito.ArgumentMatchers.argThat(exactBinding), + org.mockito.ArgumentMatchers.any(SelectedDraftGameLogicReceipt.class)); + } + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + verify(publishAttemptRepository, never()) + .sealPublication(any(PublishAttempt.class), org.mockito.ArgumentMatchers.anyBoolean()); + verify(versionAssetArtifactService, never()) + .stageExport(any(String.class), any(Long.class), any(Integer.class), any(String.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + } + @Test void uncertainAssetExportRemainsPendingForExactRetry() { SelectedPublishFixture fixture = selectedPublishFixture(1); @@ -926,8 +1132,8 @@ void uncertainAssetExportRemainsPendingForExactRetry() { .thenReturn(Optional.empty(), Optional.of(staged)); when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, request.publishWorkflowId())) .thenReturn(staged); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) + when(publishGateService.collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class))) .thenReturn(participantDigests()); when(assetExportService.exportAssets("tenant-1", 1)) .thenThrow(new AssetExportOutcomePendingException("exact object readback is unavailable")); @@ -950,8 +1156,8 @@ void uncertainAssetExportRemainsPendingForExactRetry() { void uncertainAssetStagingRemainsPendingBeforeAnyExternalExportOrFinalization() { SelectedPublishFixture fixture = selectedPublishFixture(1); PublishWorkflowRequest request = fixture.request(); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) + when(publishGateService.collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class))) .thenReturn(participantDigests()); when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, request.publishWorkflowId())) .thenThrow(new IllegalStateException("stage commit outcome is unknown")); @@ -1128,8 +1334,8 @@ void selectedStagedArtifactWithExactPersistedCandidateRetriesWithoutTreatingItAs when(versionAssetArtifactService.findState("tenant-1", 10L)) .thenReturn(Optional.of(stagedCandidate)); when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)).thenReturn(candidate); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) + when(publishGateService.collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class))) .thenReturn(participantDigests()); when(assetExportService.exportAssets("tenant-1", 1)) .thenThrow(new AssetExportOutcomePendingException("exact export readback is unavailable")); @@ -1232,8 +1438,8 @@ void selectedStagedCandidateRetryAttestsTheExactFullManifestBeforeSuccess() { .thenReturn(Optional.of(stagedCandidate)); when(versionAssetArtifactService.getExportCandidate("tenant-1", version.getId())) .thenReturn(candidate); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) + when(publishGateService.collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class))) .thenReturn(participantDigests); when(assetExportService.exportAssets("tenant-1", version.getVersionNumber())) .thenReturn(candidate); @@ -1386,13 +1592,14 @@ private void assertSelectedStagedArtifactRemainsPartial( @Test void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { SelectedPublishFixture fixture = selectedPublishFixture(1); + delegateGateAssertionsToRealGate(); PublishWorkflowRequest request = fixture.request(); String workflowId = request.publishWorkflowId(); PublishAttempt attempt = fixture.attempt(); Version version = fixture.version(); version.setVersionState(VersionLifecycleState.PUBLISHED); version.setVersionStateEpoch(2L); - List participantDigests = participantDigests(); + List participantDigests = legacyParticipantDigests(); PublishedReleaseBundleDto bundle = publishedReleaseBundleDto( 1L, @@ -1547,8 +1754,8 @@ void postBundleFailureAfterRollbackLeavesAttemptPendingWithoutCleaningAssets() { Optional.empty(), Optional.of(staged), Optional.of(staged), Optional.of(exportedState)); when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, workflowId)) .thenReturn(staged); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) + when(publishGateService.collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class))) .thenReturn(participantDigests); when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest); when(controlPlaneDigestService.getDigestForVersion(any(VersionDto.class))) @@ -1620,8 +1827,8 @@ void finalizationFailureWithFailedReadbackLeavesAttemptPending() { IllegalStateException operationFailure = new IllegalStateException("version finalization failed"); IllegalStateException readFailure = new IllegalStateException("publication read failed"); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) + when(publishGateService.collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class))) .thenReturn(participantDigests()); when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) @@ -1660,8 +1867,8 @@ void ambiguousFinalizationLeavesPendingAttemptAndDoesNotCleanAssets() { when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, workflowId)) .thenReturn(staged); ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) + when(publishGateService.collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class))) .thenReturn(participantDigests()); when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) @@ -1695,8 +1902,8 @@ void ambiguousFinalizationWithFailedReadbackLeavesAttemptPending() { ExportedAssetManifest manifest = exportedManifest(List.of("manifest.json")); IllegalStateException ambiguousCommit = new IllegalStateException("commit outcome unknown"); IllegalStateException readFailure = new IllegalStateException("publication read failed"); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) + when(publishGateService.collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class))) .thenReturn(participantDigests()); when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) @@ -1727,15 +1934,15 @@ void ambiguousFinalizationWithFailedReadbackLeavesAttemptPending() { void preExportFailureMarkingCommitUncertaintyLeavesAttemptPendingAndDoesNotCleanAssets() { SelectedPublishFixture fixture = selectedPublishFixture(1); PublishWorkflowRequest request = fixture.request(); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) + when(publishGateService.collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class))) .thenReturn(participantDigests()); org.mockito.Mockito.doThrow( new PublishGateFailureException( PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, "recorded digest mismatch")) .when(publishGateService) - .assertGatePassed(any(VersionDto.class), any(List.class)); + .assertSelectedGatePassed(any(VersionDto.class), any(List.class)); org.mockito.Mockito.doAnswer( invocation -> { ((java.util.function.Supplier) invocation.getArgument(0)).get(); @@ -1769,15 +1976,15 @@ void failureMarkingReadbackFailureKeepsPendingContractAndOriginalFailure() { PublishWorkflowRequest request = fixture.request(); IllegalStateException operationFailure = new IllegalStateException("failure mark uncertain"); IllegalStateException readFailure = new IllegalStateException("publication read failed"); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) + when(publishGateService.collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class))) .thenReturn(participantDigests()); org.mockito.Mockito.doThrow( new PublishGateFailureException( PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, "recorded digest mismatch")) .when(publishGateService) - .assertGatePassed(any(VersionDto.class), any(List.class)); + .assertSelectedGatePassed(any(VersionDto.class), any(List.class)); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.empty()) .thenThrow(readFailure); @@ -1834,6 +2041,9 @@ void freshFullVersionPublishIsDeniedBeforeAnyMutation() { verify(publishAttemptService, never()).executeFullVersionTransaction(any()); verify(publishAttemptService, never()) .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); + verify(publishGateService, never()) + .collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class)); verify(publishGateService, never()) .collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class)); @@ -1882,8 +2092,8 @@ void privateMechanicsUsesDurablySelectedVersionWithoutSequenceReservation() { when(versionAssetArtifactService.stageExport("tenant-1", 10L, 8, request.publishWorkflowId())) .thenReturn(staged); when(assetExportService.exportAssets("tenant-1", 8)).thenReturn(exportedManifest); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) + when(publishGateService.collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class))) .thenReturn(participantDigests); when(controlPlaneDigestService.getDigestForVersion(any(VersionDto.class))) .thenReturn(new DesignControlPlaneDigestDto("tenant-1", "10", "version:10", "digest-1", 1)); @@ -1952,6 +2162,28 @@ void privateMechanicsUsesDurablySelectedVersionWithoutSequenceReservation() { reflectiveUnitHarnessReconcileSelectedPublicationMechanics(request); assertEquals("SUCCEEDED", snapshot.status()); + var selectedBinding = + org.mockito.ArgumentCaptor.forClass(PublicationDigestRequestBinding.class); + verify(publishGateService) + .collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), + selectedBinding.capture(), + org.mockito.ArgumentMatchers.eq(request.publishWorkflowId())); + var expectedBinding = + PublicationDigestRequestBinding.full( + fixture.reservation().selection().intent().canonicalTenantId().toString(), + version.getId().toString(), + request.publishRequestId()); + assertEquals(expectedBinding.tenantId(), selectedBinding.getValue().tenantId()); + assertEquals(expectedBinding.versionId(), selectedBinding.getValue().versionId()); + assertEquals(expectedBinding.scopeKind(), selectedBinding.getValue().scopeKind()); + assertEquals(expectedBinding.requestDigest(), selectedBinding.getValue().requestDigest()); + assertEquals(request.publishWorkflowId(), selectedBinding.getValue().derivedWorkflowIdentity()); + verify(publishGateService, never()) + .collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class)); + verify(publishGateService, never()).assertGatePassed(any(VersionDto.class), any(List.class)); + assertEquals(10L, snapshot.versionId()); assertEquals(VersionLifecycleState.PUBLISHED, version.getVersionState()); assertEquals(2L, version.getVersionStateEpoch()); @@ -2001,7 +2233,7 @@ void privateMechanicsUsesDurablySelectedVersionWithoutSequenceReservation() { publishAttemptRepository); publishOrder .verify(publishGateService) - .assertGatePassed( + .assertSelectedGatePassed( any(VersionDto.class), org.mockito.ArgumentMatchers.eq(participantDigests)); publishOrder .verify(recordedParticipantDigestService) @@ -2033,8 +2265,8 @@ void privateMechanicsUsesDurablySelectedVersionWithoutSequenceReservation() { @Test void privateMechanicsRecordsTypedPublishGateFailures() { SelectedPublishFixture fixture = selectedPublishFixture(1); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) + when(publishGateService.collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class))) .thenReturn(participantDigests()); org.mockito.Mockito.doThrow( new PublishGateFailureException( @@ -2070,14 +2302,14 @@ void privateMechanicsRecordsTypedPublishGateFailures() { void privateMechanicsGateRejectionDoesNotRecordDigestsOrExportAssets() { SelectedPublishFixture fixture = selectedPublishFixture(1); List participantDigests = participantDigests(); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) + when(publishGateService.collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class))) .thenReturn(participantDigests); org.mockito.Mockito.doThrow( new PublishGateFailureException( PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, "gate rejected")) .when(publishGateService) - .assertGatePassed(any(VersionDto.class), any(List.class)); + .assertSelectedGatePassed(any(VersionDto.class), any(List.class)); PublishWorkflowSnapshot snapshot = reflectiveUnitHarnessReconcileSelectedPublicationMechanics(fixture.request()); @@ -2099,6 +2331,88 @@ void privateMechanicsGateRejectionDoesNotRecordDigestsOrExportAssets() { .NO_PUBLICATION); } + @Test + void freshSelectedPublishRejectsLegacyOwnerVectorBeforeAssetEffects() throws Exception { + SelectedPublishFixture fixture = selectedPublishFixture(1); + var fullVector = participantDigests(); + var legacySchemas = List.of(3, 2, 1, 5, 2); + List legacyVector = + java.util.stream.IntStream.range(0, fullVector.size()) + .mapToObj( + index -> { + var participant = fullVector.get(index); + return new PublishParticipantDigestDto( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + legacySchemas.get(index), + participant.abilitySchemaDigest(), + participant.errorCode(), + participant.errorMessage()); + }) + .toList(); + when(publishGateService.collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class))) + .thenReturn(legacyVector); + + PublishWorkflowSnapshot snapshot = + reflectiveUnitHarnessReconcileSelectedPublicationMechanics(fixture.request()); + + assertEquals("FAILED", snapshot.status()); + assertEquals("PUBLISH_FAILED", snapshot.failureCode()); + assertEquals( + "Selected-full release requires the exact 4/3/1/6/2 successful participant vector", + snapshot.failureMessage()); + verify(publishGateService) + .assertSelectedGatePassed( + any(VersionDto.class), org.mockito.ArgumentMatchers.eq(legacyVector)); + verify(versionAssetArtifactService, never()) + .stageExport(any(String.class), any(Long.class), any(Integer.class), any(String.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + } + + @ParameterizedTest + @ValueSource(ints = {0, 1, 2, 3, 4}) + void freshSelectedPublishRefusesEachNoncanonicalParticipantSchemaBeforeEffects(int index) + throws Exception { + // These controlled unit carriers increment each participant schema, but none is the canonical + // selected-full schema. + SelectedPublishFixture fixture = selectedPublishFixture(1); + var vector = new java.util.ArrayList<>(participantDigests()); + var original = vector.get(index); + vector.set( + index, + new PublishParticipantDigestDto( + original.participantKey(), + original.scopeValue(), + original.baseVersionId(), + original.appliedCommitId(), + original.contentDigest(), + original.digestSchemaVersion() + 1, + original.abilitySchemaDigest(), + original.errorCode(), + original.errorMessage())); + when(publishGateService.collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class))) + .thenReturn(vector); + + var result = reflectiveUnitHarnessReconcileSelectedPublicationMechanics(fixture.request()); + + assertEquals("FAILED", result.status()); + assertEquals("PUBLISH_FAILED", result.failureCode()); + assertEquals( + "Selected-full release requires the exact 4/3/1/6/2 successful participant vector", + result.failureMessage()); + verify(publishGateService) + .assertSelectedGatePassed(any(VersionDto.class), org.mockito.ArgumentMatchers.eq(vector)); + verify(publishGateService, never()).assertGatePassed(any(VersionDto.class), any(List.class)); + verify(versionAssetArtifactService, never()) + .stageExport(any(String.class), any(Long.class), any(Integer.class), any(String.class)); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + } + @Test void privateMechanicsPreservesSharedAssetsWhenAttestationWriteIsUncertain() { SelectedPublishFixture fixture = selectedPublishFixture(1); @@ -2129,8 +2443,8 @@ void privateMechanicsPreservesSharedAssetsWhenAttestationWriteIsUncertain() { when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, request.publishWorkflowId())) .thenReturn(staged); when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) + when(publishGateService.collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class))) .thenReturn(participantDigests()); org.mockito.Mockito.doThrow(new IllegalStateException("attestation write outcome is unknown")) .when(versionAssetArtifactService) @@ -2171,6 +2485,7 @@ void privateMechanicsPreservesSharedAssetsWhenAttestationWriteIsUncertain() { @Test void privateMechanicsReconcilesPendingAttemptThroughCurrentGates() throws Exception { SelectedPublishFixture fixture = selectedPublishFixture(1); + delegateGateAssertionsToRealGate(); SelectionSnapshot seedReservation = fixture.reservation(); AuthoredDraftPublishSelection seedSelection = seedReservation.selection(); DraftCommitBinding seedCommit = seedSelection.selectedCommit(); @@ -2317,7 +2632,7 @@ void privateMechanicsReconcilesPendingAttemptThroughCurrentGates() throws Except assertEquals("SUCCEEDED", snapshot.status()); verify(publishGateService) - .assertGatePassed( + .assertSelectedGatePassed( any(VersionDto.class), org.mockito.ArgumentMatchers.eq(participantDigests)); verify(recordedParticipantDigestService) .assertMatchesRecordedDigests("tenant-1", PublishType.FULL_VERSION, participantDigests); @@ -2373,8 +2688,8 @@ void candidateRecordedBeforeConflictReadbackKeepsAttemptPendingForReconciliation org.mockito.Mockito.doReturn(null, manifest) .when(versionAssetArtifactService) .getExportCandidate("tenant-1", 10L); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) + when(publishGateService.collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class))) .thenReturn(participantDigests()); org.mockito.Mockito.doAnswer( ignored -> { @@ -2458,8 +2773,8 @@ void postExportFinalizationFailureWithExactCandidateRemainsPendingWithoutCleanup .thenReturn(null, manifest, manifest); when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, workflowId)) .thenReturn(staged); - when(publishGateService.collectFullVersionParticipantDigests( - any(VersionDto.class), any(String.class), any(String.class))) + when(publishGateService.collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class))) .thenReturn(participantDigests); when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest); when(controlPlaneDigestService.getDigestForVersion(any(VersionDto.class))) @@ -2891,17 +3206,107 @@ private Version fullVersion(long versionId, int versionNumber, VersionLifecycleS } private List participantDigests() { + String appliedCommitId = selectedIntent().selectedCommitId().toString(); + return List.of( + new PublishParticipantDigestDto( + "WORLD_MANAGEMENT", "10", null, appliedCommitId, "a".repeat(64), 4, null, null, null), + new PublishParticipantDigestDto( + "ENTITY_MANAGEMENT", "10", null, appliedCommitId, "b".repeat(64), 3, null, null, null), + new PublishParticipantDigestDto( + "GAME_LOGIC", + "10", + null, + appliedCommitId, + "c".repeat(64), + 1, + "sha256:" + "d".repeat(64), + null, + null), + new PublishParticipantDigestDto( + "AUTOMATION_SCRIPTING", + "10", + null, + appliedCommitId, + "e".repeat(64), + 6, + null, + null, + null), + new PublishParticipantDigestDto( + "GAME_DESIGN_CONTROL_PLANE", + "10", + null, + appliedCommitId, + "f".repeat(64), + 2, + null, + null, + null)); + } + + private List legacyParticipantDigests() { + String appliedCommitId = selectedIntent().selectedCommitId().toString(); return List.of( + new PublishParticipantDigestDto( + "WORLD_MANAGEMENT", "10", null, appliedCommitId, "a".repeat(64), 3, null, null, null), + new PublishParticipantDigestDto( + "ENTITY_MANAGEMENT", "10", null, appliedCommitId, "b".repeat(64), 1, null, null, null), + new PublishParticipantDigestDto( + "GAME_LOGIC", "10", null, appliedCommitId, "c".repeat(64), 1, null, null, null), + new PublishParticipantDigestDto( + "AUTOMATION_SCRIPTING", + "10", + null, + appliedCommitId, + "e".repeat(64), + 5, + null, + null, + null), new PublishParticipantDigestDto( "GAME_DESIGN_CONTROL_PLANE", "10", - selectedIntent().selectedCommitId().toString(), - "digest", + null, + appliedCommitId, + "f".repeat(64), 1, null, + null, null)); } + private void delegateGateAssertionsToRealGate() { + PublishGateServiceImpl realGate = + new PublishGateServiceImpl( + controlPlaneDigestService, + org.mockito.Mockito.mock(WorldManagementClient.class), + org.mockito.Mockito.mock(EntityManagementClient.class), + org.mockito.Mockito.mock(GameLogicClient.class), + org.mockito.Mockito.mock(AutomationScriptingClient.class), + org.mockito.Mockito.mock(SelectedDraftGameLogicReceiptRepository.class)); + org.mockito.Mockito.doAnswer( + invocation -> { + realGate.assertSelectedGatePassed( + invocation.getArgument(0), invocation.getArgument(1)); + return null; + }) + .when(publishGateService) + .assertSelectedGatePassed(any(VersionDto.class), any(List.class)); + org.mockito.Mockito.doAnswer( + invocation -> { + realGate.assertGatePassed(invocation.getArgument(0), invocation.getArgument(1)); + return null; + }) + .when(publishGateService) + .assertGatePassed(any(VersionDto.class), any(List.class)); + } + + private enum TransientCollectorFailure { + SELECTED_SNAPSHOT_UNAVAILABLE, + GAME_LOGIC_RECEIPT_MISSING, + GAME_LOGIC_RECEIPT_STORAGE_UNAVAILABLE + } + private record SelectedPublishFixture( SelectionSnapshot reservation, PublishWorkflowRequest request, diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/GameLogicDraftDesignDigestService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/GameLogicDraftDesignDigestService.java index 45de4c801c..019db94ed1 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/GameLogicDraftDesignDigestService.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/GameLogicDraftDesignDigestService.java @@ -1,7 +1,11 @@ package net.firedevops.firemud.gamelogic.service; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicPublicationSourceReadService; + public interface GameLogicDraftDesignDigestService { - GameLogicDraftDesignDigest getDraftDesignDigest(String tenantId, String versionId); + GameLogicPublicationSourceReadService.Result getDraftDesignDigest( + GameLogicPublicationSourceReadBinding binding); final class UnsupportedDigestScopeException extends RuntimeException { private static final long serialVersionUID = 1L; @@ -10,11 +14,4 @@ public UnsupportedDigestScopeException(String message) { super(message); } } - - record GameLogicDraftDesignDigest( - String tenantId, - String scopeValue, - String appliedCommitId, - String contentDigest, - int digestSchemaVersion) {} } diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicDraftDesignDigestServiceImpl.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicDraftDesignDigestServiceImpl.java index c9e218a577..4c97c0a228 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicDraftDesignDigestServiceImpl.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicDraftDesignDigestServiceImpl.java @@ -1,17 +1,35 @@ package net.firedevops.firemud.gamelogic.service.impl; +import java.util.Objects; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding; import net.firedevops.firemud.gamelogic.service.GameLogicDraftDesignDigestService; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicPublicationSourceReadService; import org.springframework.stereotype.Service; @Service -public class GameLogicDraftDesignDigestServiceImpl implements GameLogicDraftDesignDigestService { +public final class GameLogicDraftDesignDigestServiceImpl + implements GameLogicDraftDesignDigestService { + private final GameLogicPublicationSourceReadService publicationSourceReadService; + + /** Spring's default owner keeps this route denied until explicit composition provides storage. */ + public GameLogicDraftDesignDigestServiceImpl() { + publicationSourceReadService = null; + } + + /** Explicit composition for owner-local proofs and tests; this constructor is not auto-wired. */ + public GameLogicDraftDesignDigestServiceImpl( + GameLogicPublicationSourceReadService publicationSourceReadService) { + this.publicationSourceReadService = + Objects.requireNonNull(publicationSourceReadService, "publicationSourceReadService"); + } @Override - public GameLogicDraftDesignDigest getDraftDesignDigest(String tenantId, String versionId) { - if (versionId == null || versionId.isBlank()) { - throw new IllegalArgumentException("version_id is required"); + public GameLogicPublicationSourceReadService.Result getDraftDesignDigest( + GameLogicPublicationSourceReadBinding binding) { + if (publicationSourceReadService == null) { + throw new UnsupportedDigestScopeException( + "Game Logic retained publication source reader is not configured"); } - throw new UnsupportedDigestScopeException( - "Game Logic owner-local manifest and provenance are unavailable"); + return publicationSourceReadService.read(binding); } } diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcService.java index fca017ad10..3edb3234d1 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcService.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcService.java @@ -6,8 +6,8 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadGrpcCodec; import net.firedevops.firemud.common.grpc.GrpcAppErrors; -import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.GameplaySessionAttestationException; import net.firedevops.firemud.common.security.GameplaySessionAttestationService; @@ -70,6 +70,8 @@ @GrpcService public class GameLogicGrpcService extends GameLogicServiceGrpc.GameLogicServiceImplBase { private static final Logger logger = LoggerFactory.getLogger(GameLogicGrpcService.class); + private static final String PUBLICATION_READ_FAILURE_DESCRIPTION = + "Exact retained publication source read failed"; private final PingService pingService; private final CommandService commandService; private final LookAggregationService lookAggregationService; @@ -169,41 +171,10 @@ public void getDraftDesignDigest( StreamObserver responseObserver) { try { requirePublicationRead(); - if (request.getScopeCase() != GetDraftDesignDigestRequest.ScopeCase.VERSION_ID) { - responseObserver.onNext( - GetDraftDesignDigestResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "GetDraftDesignDigest", - "UNSUPPORTED_SCOPE", - "game logic supports version_id scope only")) - .build()); - responseObserver.onCompleted(); - return; - } - PublicationDigestRequestBinding binding = - PublicationDigestRequestBinding.forScope( - PublicationDigestRequestBinding.ScopeKind.FULL_VERSION, - request.getTenantId(), - request.getVersionId(), - request.getBaseVersionId(), - request.getScriptPatchVersion(), - request.getPublishRequestId()); - binding.validateSupplied(request.getDerivedWorkflowIdentity(), request.getRequestDigest()); - var digest = - gameLogicDraftDesignDigestService.getDraftDesignDigest( - request.getTenantId(), request.getVersionId()); - binding.requireOwnerScope(digest.tenantId(), digest.scopeValue()); + var binding = GameLogicPublicationSourceReadGrpcCodec.fromRequest(request); + var retainedRead = gameLogicDraftDesignDigestService.getDraftDesignDigest(binding); responseObserver.onNext( - GetDraftDesignDigestResponse.newBuilder() - .setTenantId(binding.tenantId()) - .setVersionId(binding.versionId()) - .setAppliedCommitId(digest.appliedCommitId()) - .setContentDigest(digest.contentDigest()) - .setDigestSchemaVersion(digest.digestSchemaVersion()) - .build()); + GameLogicPublicationSourceReadGrpcCodec.toResponse(binding, retainedRead.terminal())); responseObserver.onCompleted(); } catch (AdminAuthorizationException ex) { responseObserver.onNext( @@ -241,6 +212,14 @@ public void getDraftDesignDigest( ex.getMessage())) .build()); responseObserver.onCompleted(); + } catch (StatusRuntimeException ex) { + Status status = Status.fromThrowable(ex); + logger.warn("GetDraftDesignDigest retained source read failed: code={}", status.getCode()); + meterRegistry.counter("grpc.app_error", "code", status.getCode().name()).increment(); + responseObserver.onError( + Status.fromCode(status.getCode()) + .withDescription(PUBLICATION_READ_FAILURE_DESCRIPTION) + .asRuntimeException()); } catch (Exception ex) { responseObserver.onNext( GetDraftDesignDigestResponse.newBuilder() diff --git a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationDigestReadPostgresIntegrationTest.java b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationDigestReadPostgresIntegrationTest.java new file mode 100644 index 0000000000..831feb639c --- /dev/null +++ b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationDigestReadPostgresIntegrationTest.java @@ -0,0 +1,416 @@ +package net.firedevops.firemud.gamelogic.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadGrpcCodec; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.security.PublicationReadGuard; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamelogic.service.impl.GameLogicDraftDesignDigestServiceImpl; +import net.firedevops.firemud.gamelogic.service.impl.GameLogicGrpcService; +import net.firedevops.firemud.gamelogic.v1.GetDraftDesignDigestRequest; +import net.firedevops.firemud.gamelogic.v1.GetDraftDesignDigestResponse; +import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Actual current-default GL retention, immutable owner read, digest service and receiver. Account + * authorization and GD source responses are explicitly controlled upstream inputs; direct handler + * invocation supplies controlled peer context, not authenticated socket/TLS proof. No production + * composition, genuine upstream authority or registration is established. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameLogicPublicationDigestReadPostgresIntegrationTest { + private static final String NAMESPACE = "test"; + + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @AfterEach + void clearContext() { + SessionContext.clear(); + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) + TransactionSynchronizationManager.clearSynchronization(); + } + + @Test + void actualRetainedOwnerFlowsThroughDigestServiceAndReceiverWithExactReplayAndRefusals() + throws Exception { + var f = fixture(); + var authorization = authorization(); + var accountReader = mock(GameLogicIntakeAuthorizationReadClient.class); + when(accountReader.read(any())) + .thenAnswer( + invocation -> { + GameLogicIntakeAuthorizationReadEvidence.Request request = invocation.getArgument(0); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(request.binding().canonicalBytes()) + .isEqualTo(authorization.canonicalBytes()); + return new GameLogicIntakeAuthorizationReadEvidence(request); + }); + var sourceReader = mock(GameplayRuleSourceReadClient.class); + when(sourceReader.read(any())) + .thenAnswer( + invocation -> { + GameplayRuleSourceReadEvidence.Request request = invocation.getArgument(0); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(request.proof()) + .isInstanceOf(GameplayRuleSourceReadEvidence.Finalized.class); + assertThat(request.proof().canonicalBytes()) + .isEqualTo(authorization.canonicalBytes()); + return new GameplayRuleSourceReadEvidence(request, authorization.source()); + }); + var intake = + new GameLogicGameplayRuleIntakeService( + f.repository(), f.manager(), accountReader, sourceReader, NAMESPACE); + var terminal = asGameDesign(() -> intake.retain(authorization)); + var reader = new GameLogicPublicationSourceReadService(f.repository(), NAMESPACE); + var digest = new GameLogicDraftDesignDigestServiceImpl(reader); + var receiver = receiver(digest); + var binding = publicationBinding(authorization); + var request = GameLogicPublicationSourceReadGrpcCodec.toRequest(binding); + String retained = row(f, authorization.operationId()); + + var response = asGameDesign(() -> invoke(receiver, request)); + assertThat(response.hasError()).isFalse(); + var evidence = + GameLogicPublicationSourceReadGrpcCodec.fromResponse(binding, response, NAMESPACE); + assertThat(evidence.terminal().canonicalBytes()).isEqualTo(terminal.canonicalBytes()); + assertThat(evidence.terminal().selectedSourceBytes()) + .isEqualTo(authorization.source().canonicalBytes()); + assertThat(evidence.manifestDigest()).isEqualTo(authorization.source().manifest().digest()); + assertThat(asGameDesign(() -> digest.getDraftDesignDigest(binding)).terminalBytes()) + .isEqualTo(terminal.canonicalBytes()); + assertThat(asGameDesign(() -> invoke(receiver, request))).isEqualTo(response); + + var missing = + copyAuthorization( + authorization, + UUID.randomUUID(), + authorization.fenceId(), + authorization.intakeRequestId(), + authorization.source()); + assertTransportError( + receiver, + GameLogicPublicationSourceReadGrpcCodec.toRequest(publicationBinding(missing)), + Status.Code.FAILED_PRECONDITION); + var changed = + copyAuthorization( + authorization, + authorization.operationId(), + UUID.randomUUID(), + authorization.intakeRequestId(), + authorization.source()); + assertTransportError( + receiver, + GameLogicPublicationSourceReadGrpcCodec.toRequest(publicationBinding(changed)), + Status.Code.ALREADY_EXISTS); + assertError( + receiver, + request.toBuilder().clearSourceReadBinding().clearSourceReadBindingDigest().build(), + "INVALID_ARGUMENT"); + assertError( + receiver(new GameLogicDraftDesignDigestServiceImpl()), request, "UNSUPPORTED_SCOPE"); + + var wrongPeer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/world-management-service") + .orElseThrow(); + var context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, wrongPeer); + var previous = context.attach(); + try { + assertThat(invoke(receiver, request).getError().getCode()).isEqualTo("PERMISSION_DENIED"); + } finally { + context.detach(previous); + } + SessionContext.setContext("controlled-user", List.of(), Map.of()); + assertError(receiver, request, "PERMISSION_DENIED"); + SessionContext.clear(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertTransportError(receiver, request, Status.Code.FAILED_PRECONDITION); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + assertThat(row(f, authorization.operationId())).isEqualTo(retained); + + var abortedAuthorization = authorization(); + var abortAccountReader = mock(GameLogicIntakeAuthorizationReadClient.class); + when(abortAccountReader.read(any())) + .thenAnswer( + invocation -> { + GameLogicIntakeAuthorizationReadEvidence.Request heldRequest = + invocation.getArgument(0); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(heldRequest.binding().canonicalBytes()) + .isEqualTo(abortedAuthorization.canonicalBytes()); + return new GameLogicIntakeAuthorizationReadEvidence(heldRequest); + }); + var unusedAbortSourceReader = mock(GameplayRuleSourceReadClient.class); + var abortOwner = + new GameLogicGameplayRuleIntakeService( + f.repository(), f.manager(), abortAccountReader, unusedAbortSourceReader, NAMESPACE); + asGameDesign(() -> abortOwner.abort(abortedAuthorization)); + verify(abortAccountReader).read(any()); + verify(unusedAbortSourceReader, never()).read(any()); + String aborted = row(f, abortedAuthorization.operationId()); + assertTransportError( + receiver, + GameLogicPublicationSourceReadGrpcCodec.toRequest(publicationBinding(abortedAuthorization)), + Status.Code.FAILED_PRECONDITION); + assertThat(row(f, abortedAuthorization.operationId())).isEqualTo(aborted); + assertThat(row(f, authorization.operationId())).isEqualTo(retained); + } + + private static GameLogicGrpcService receiver(GameLogicDraftDesignDigestServiceImpl digest) { + // Unrelated gameplay owners are unused by this focused direct receiver composition. + return new GameLogicGrpcService( + null, + null, + null, + null, + null, + null, + digest, + null, + new SimpleMeterRegistry(), + new PublicationReadGuard(NAMESPACE)); + } + + private static GetDraftDesignDigestResponse invoke( + GameLogicGrpcService receiver, GetDraftDesignDigestRequest request) { + var result = new AtomicReference(); + receiver.getDraftDesignDigest( + request, + new StreamObserver<>() { + @Override + public void onNext(GetDraftDesignDigestResponse value) { + result.set(value); + } + + @Override + public void onError(Throwable failure) { + throw new AssertionError(failure); + } + + @Override + public void onCompleted() {} + }); + assertThat(result.get()).isNotNull(); + return result.get(); + } + + private static void assertError( + GameLogicGrpcService receiver, GetDraftDesignDigestRequest request, String code) + throws Exception { + var response = asGameDesign(() -> invoke(receiver, request)); + assertThat(response.getError().getCode()).isEqualTo(code); + assertThat(response.getRetainedIntakeTerminal().isEmpty()).isTrue(); + assertThat(response.getContentDigest()).isEmpty(); + assertThat(response.getAbilitySchemaDigest()).isEmpty(); + } + + private static void assertTransportError( + GameLogicGrpcService receiver, GetDraftDesignDigestRequest request, Status.Code code) + throws Exception { + var failure = new AtomicReference(); + var response = new AtomicReference(); + var completed = new AtomicReference<>(false); + asGameDesign( + () -> { + receiver.getDraftDesignDigest( + request, + new StreamObserver<>() { + @Override + public void onNext(GetDraftDesignDigestResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable value) { + failure.set(value); + } + + @Override + public void onCompleted() { + completed.set(true); + } + }); + return null; + }); + assertThat(failure.get()).isInstanceOf(StatusRuntimeException.class); + var statusFailure = (StatusRuntimeException) failure.get(); + assertThat(statusFailure.getStatus().getCode()).isEqualTo(code); + assertThat(statusFailure.getStatus().getDescription()) + .isEqualTo("Exact retained publication source read failed"); + assertThat(statusFailure.getCause()).isNull(); + assertThat(statusFailure.getTrailers()).isNull(); + assertThat(response.get()).isNull(); + assertThat(completed.get()).isFalse(); + } + + private static String row(Fixture f, UUID operation) { + return f.dsl() + .fetchSingle( + "SELECT row_to_json(t)::TEXT || ':' || t.xmin::TEXT FROM game_logic_gameplay_rule_intake_terminal t WHERE operation_id = ?", + operation) + .get(0, String.class); + } + + private static Fixture fixture() { + String schema = "gl_intake_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = new DriverManagerDataSource(); + dataSource.setUrl(POSTGRES.getJdbcUrl()); + dataSource.setUsername(POSTGRES.getUsername()); + dataSource.setPassword(POSTGRES.getPassword()); + dataSource.setSchema(schema); + org.flywaydb.core.Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .table("flyway_schema_history") + .locations("classpath:db/migration") + .load() + .migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var transactionManager = new DataSourceTransactionManager(dataSource); + return new Fixture(dsl, transactionManager, new GameLogicGameplayRuleIntakeRepository(dsl)); + } + + private static T asGameDesign(java.util.concurrent.Callable action) throws Exception { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-design-service", NAMESPACE, "game-design-service"); + Context previous = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).attach(); + try { + return action.call(); + } finally { + Context.current().detach(previous); + } + } + + private static GameLogicIntakeAuthorizationBinding authorization() { + var actor = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "private", 2, "private", "NEW_GAME_ROW"); + var binding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var source = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", binding.canonicalJson(), + "bindingDigest", binding.digest(), + "sourceEpoch", "1", + "inheritedCommitId", "", + "genesisReceiptId", UUID.randomUUID().toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + var accountSource = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {4, 5, 6}); + return new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + source, + List.of(accountSource)); + } + + private static GameLogicIntakeAuthorizationBinding copyAuthorization( + GameLogicIntakeAuthorizationBinding original, + UUID operationId, + UUID fenceId, + UUID intakeRequestId, + GameplayRuleSelectedSource source) { + return new GameLogicIntakeAuthorizationBinding( + operationId, + fenceId, + intakeRequestId, + original.actorAccountId(), + source, + original.sources()); + } + + private static GameLogicPublicationSourceReadBinding publicationBinding( + GameLogicIntakeAuthorizationBinding authorization) { + var target = authorization.source().binding().target(); + return new GameLogicPublicationSourceReadBinding( + PublicationDigestRequestBinding.full( + authorization.tenantId().toString(), + Long.toString(target.gameDesignVersionRowId()), + "publication-read"), + authorization); + } + + private record Fixture( + DSLContext dsl, + DataSourceTransactionManager manager, + GameLogicGameplayRuleIntakeRepository repository) {} +} diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicDraftDesignDigestServiceImplTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicDraftDesignDigestServiceImplTest.java index ef11de7c7d..7cdec12c0b 100644 --- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicDraftDesignDigestServiceImplTest.java +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicDraftDesignDigestServiceImplTest.java @@ -1,29 +1,41 @@ package net.firedevops.firemud.gamelogic.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding; import net.firedevops.firemud.gamelogic.service.GameLogicDraftDesignDigestService; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicPublicationSourceReadService; import org.junit.jupiter.api.Test; class GameLogicDraftDesignDigestServiceImplTest { - private final GameLogicDraftDesignDigestServiceImpl service = - new GameLogicDraftDesignDigestServiceImpl(); - @Test - void getDraftDesignDigestFailsWhenOwnerManifestAndProvenanceAreUnavailable() { + void defaultSpringCompositionRemainsDeniedWithoutAConfiguredOwnerReader() { + var service = new GameLogicDraftDesignDigestServiceImpl(); + GameLogicDraftDesignDigestService.UnsupportedDigestScopeException thrown = assertThrows( GameLogicDraftDesignDigestService.UnsupportedDigestScopeException.class, - () -> service.getDraftDesignDigest("tenant-1", "7")); + () -> service.getDraftDesignDigest(null)); assertEquals( - "Game Logic owner-local manifest and provenance are unavailable", thrown.getMessage()); + "Game Logic retained publication source reader is not configured", thrown.getMessage()); } @Test - void getDraftDesignDigestRejectsMissingVersionBeforeManifestCheck() { - assertThrows( - IllegalArgumentException.class, () -> service.getDraftDesignDigest("tenant-1", " ")); + void explicitlyComposedServiceReturnsTheExactRetainedReadResultForTheLookupBinding() { + var sourceReader = mock(GameLogicPublicationSourceReadService.class); + var binding = mock(GameLogicPublicationSourceReadBinding.class); + var expected = mock(GameLogicPublicationSourceReadService.Result.class); + when(sourceReader.read(binding)).thenReturn(expected); + var service = new GameLogicDraftDesignDigestServiceImpl(sourceReader); + + assertSame(expected, service.getDraftDesignDigest(binding)); + + verify(sourceReader).read(binding); } } diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java index 10f908bd74..3b1043f54d 100644 --- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java @@ -1,10 +1,13 @@ package net.firedevops.firemud.gamelogic.service.impl; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; +import com.google.protobuf.ByteString; import io.grpc.Context; import io.grpc.Status; import io.grpc.StatusRuntimeException; @@ -12,7 +15,18 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.List; import java.util.Map; +import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding; +import net.firedevops.firemud.common.gamelogic.GameplayAbilitySchemaProjection; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.security.GameplaySessionAttestationException; @@ -38,6 +52,8 @@ import net.firedevops.firemud.gamelogic.service.LookAggregationService; import net.firedevops.firemud.gamelogic.service.MoveAggregationService; import net.firedevops.firemud.gamelogic.service.PingService; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeRepository; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicPublicationSourceReadService; import net.firedevops.firemud.gamelogic.v1.DropCarriedItemRequest; import net.firedevops.firemud.gamelogic.v1.ExecuteCommandRequest; import net.firedevops.firemud.gamelogic.v1.ExecuteCommandResponse; @@ -57,6 +73,7 @@ class GameLogicGrpcServiceTest { private static final String TEST_NAMESPACE = "test"; + private static final UUID TEST_TENANT = UUID.fromString("00000000-0000-0000-0000-000000000001"); private static final GrpcPeerIdentity WRONG_PEER = new GrpcPeerIdentity( "spiffe://firemud/ns/test/sa/world-management-service", @@ -79,17 +96,105 @@ private static void runAsGameDesign(Runnable action) { } private static GetDraftDesignDigestRequest fullDigestRequest(String tenantId, String versionId) { - PublicationDigestRequestBinding binding = - PublicationDigestRequestBinding.full(tenantId, versionId, "request-7"); + var authorization = digestAuthorization(UUID.fromString(tenantId), Long.parseLong(versionId)); + return fullDigestRequest(publicationBinding(authorization, "request-7")); + } + + private static GetDraftDesignDigestRequest fullDigestRequest( + GameLogicPublicationSourceReadBinding binding) { + PublicationDigestRequestBinding publicationRequest = binding.publicationRequest(); return GetDraftDesignDigestRequest.newBuilder() - .setTenantId(binding.tenantId()) - .setVersionId(binding.versionId()) - .setPublishRequestId(binding.publishRequestId()) - .setDerivedWorkflowIdentity(binding.derivedWorkflowIdentity()) - .setRequestDigest(binding.requestDigest()) + .setTenantId(publicationRequest.tenantId()) + .setVersionId(publicationRequest.versionId()) + .setPublishRequestId(publicationRequest.publishRequestId()) + .setDerivedWorkflowIdentity(publicationRequest.derivedWorkflowIdentity()) + .setRequestDigest(publicationRequest.requestDigest()) + .setSourceReadBinding(ByteString.copyFrom(binding.canonicalBytes())) + .setSourceReadBindingDigest(binding.digest()) .build(); } + private static GameLogicPublicationSourceReadBinding publicationBinding( + GameLogicIntakeAuthorizationBinding authorization, String publishRequestId) { + var target = authorization.source().binding().target(); + return new GameLogicPublicationSourceReadBinding( + PublicationDigestRequestBinding.full( + authorization.tenantId().toString(), + Long.toString(target.gameDesignVersionRowId()), + publishRequestId), + authorization); + } + + private static GameLogicIntakeAuthorizationBinding digestAuthorization( + UUID tenantId, long gameDesignVersionRowId) { + var actor = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenantId, + UUID.randomUUID(), + gameDesignVersionRowId, + "private", + 29, + "private", + "NEW_GAME_ROW"); + var commit = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var source = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", commit.canonicalJson(), + "bindingDigest", commit.digest(), + "sourceEpoch", "1", + "inheritedCommitId", "", + "genesisReceiptId", UUID.randomUUID().toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + var accountSource = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + return new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + source, + List.of(accountSource)); + } + + private static GameLogicGameplayRuleIntakeTerminal retainedTerminal( + GameLogicIntakeAuthorizationBinding authorization) { + return GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation(TEST_NAMESPACE, authorization), + authorization.source().canonicalBytes(), + authorization.source().manifest().canonicalBytes()); + } + private GameLogicDraftDesignDigestService mockDigestService() { return Mockito.mock(GameLogicDraftDesignDigestService.class); } @@ -257,7 +362,7 @@ public void onCompleted() {} } @Test - void getDraftDesignDigestMapsUnavailableManifestToErrorResponse() { + void getDraftDesignDigestMapsUnconfiguredRetainedSourceToErrorResponse() { PingService pingService = new PingServiceImpl(); var dispatcher = new EventDispatcher(); var processor = new SimpleCommandProcessor(dispatcher, new NoOpScriptingHook()); @@ -267,10 +372,11 @@ void getDraftDesignDigestMapsUnavailableManifestToErrorResponse() { Mockito.mock(CommunicationAggregationService.class); MoveAggregationService moveAggregationService = Mockito.mock(MoveAggregationService.class); GameLogicDraftDesignDigestService digestService = mockDigestService(); - Mockito.when(digestService.getDraftDesignDigest("1", "7")) + Mockito.when( + digestService.getDraftDesignDigest(any(GameLogicPublicationSourceReadBinding.class))) .thenThrow( new GameLogicDraftDesignDigestService.UnsupportedDigestScopeException( - "Game Logic owner-local manifest and provenance are unavailable")); + "Game Logic retained publication source reader is not configured")); SessionContext.setContext( null, List.of(), Map.of(), true, "game-design-service", "test-instance"); GameLogicGrpcService service = @@ -290,7 +396,7 @@ void getDraftDesignDigestMapsUnavailableManifestToErrorResponse() { runAsGameDesign( () -> service.getDraftDesignDigest( - fullDigestRequest("1", "7"), + fullDigestRequest(TEST_TENANT.toString(), "7"), new StreamObserver<>() { @Override public void onNext(GetDraftDesignDigestResponse value) { @@ -316,23 +422,160 @@ public void onCompleted() {} assertEquals(0, ref.get().getDigestSchemaVersion()); } + @Test + void getDraftDesignDigestEchoesTheExactRetainedSourceAndCanonicalDigests() { + var authorization = digestAuthorization(TEST_TENANT, 7); + var binding = publicationBinding(authorization, "request-7"); + var terminal = retainedTerminal(authorization); + var repository = Mockito.mock(GameLogicGameplayRuleIntakeRepository.class); + Mockito.when(repository.findTerminal(authorization.operationId())) + .thenReturn(Optional.of(terminal)); + var digestService = + new GameLogicDraftDesignDigestServiceImpl( + new GameLogicPublicationSourceReadService(repository, TEST_NAMESPACE)); + var service = newDigestService(digestService); + SessionContext.setContext( + null, List.of(), Map.of(), true, "game-design-service", "test-instance"); + + AtomicReference responseReference = new AtomicReference<>(); + runAsGameDesign(() -> responseReference.set(invokeDigest(service, fullDigestRequest(binding)))); + GetDraftDesignDigestResponse response = responseReference.get(); + + assertEquals("", response.getError().getCode()); + assertEquals(TEST_TENANT.toString(), response.getTenantId()); + assertEquals("7", response.getVersionId()); + assertEquals( + authorization.source().binding().commitId().toString(), response.getAppliedCommitId()); + assertEquals(authorization.source().manifest().digest(), response.getContentDigest()); + assertEquals(1, response.getDigestSchemaVersion()); + assertEquals( + GameplayAbilitySchemaProjection.digest(authorization.source().manifest()), + response.getAbilitySchemaDigest()); + assertEquals("RFC8785", response.getCanonicalization()); + assertEquals(binding.digest(), response.getSourceReadBindingDigest()); + assertArrayEquals(binding.canonicalBytes(), response.getSourceReadBinding().toByteArray()); + assertEquals(terminal.digest(), response.getRetainedIntakeTerminalDigest()); + assertArrayEquals( + terminal.canonicalBytes(), response.getRetainedIntakeTerminal().toByteArray()); + Mockito.verify(repository).findTerminal(authorization.operationId()); + } + + @Test + void getDraftDesignDigestRejectsMissingBindingAndUnversionedScopeBeforeServiceCall() { + var digestService = mockDigestService(); + var service = newDigestService(digestService); + SessionContext.setContext( + null, List.of(), Map.of(), true, "game-design-service", "test-instance"); + var valid = fullDigestRequest(TEST_TENANT.toString(), "7"); + var missingBinding = + valid.toBuilder().clearSourceReadBinding().clearSourceReadBindingDigest().build(); + var unversionedScope = valid.toBuilder().clearScope().build(); + + runAsGameDesign( + () -> { + var missingResponse = invokeDigest(service, missingBinding); + assertEquals("INVALID_ARGUMENT", missingResponse.getError().getCode()); + assertEquals("", missingResponse.getContentDigest()); + assertEquals(0, missingResponse.getDigestSchemaVersion()); + var scopeResponse = invokeDigest(service, unversionedScope); + assertEquals("INVALID_ARGUMENT", scopeResponse.getError().getCode()); + assertEquals("", scopeResponse.getContentDigest()); + assertEquals(0, scopeResponse.getDigestSchemaVersion()); + }); + Mockito.verifyNoInteractions(digestService); + } + + @Test + void getDraftDesignDigestDeniesSourceBindingThatDiffersFromRetainedOperation() { + var authorization = digestAuthorization(TEST_TENANT, 7); + var stored = retainedTerminal(authorization); + var changedAuthorization = + new GameLogicIntakeAuthorizationBinding( + authorization.operationId(), + UUID.randomUUID(), + authorization.intakeRequestId(), + authorization.actorAccountId(), + authorization.source(), + authorization.sources()); + var changedBinding = publicationBinding(changedAuthorization, "request-7"); + var repository = Mockito.mock(GameLogicGameplayRuleIntakeRepository.class); + Mockito.when(repository.findTerminal(authorization.operationId())) + .thenReturn(Optional.of(stored)); + var service = + newDigestService( + new GameLogicDraftDesignDigestServiceImpl( + new GameLogicPublicationSourceReadService(repository, TEST_NAMESPACE))); + SessionContext.setContext( + null, List.of(), Map.of(), true, "game-design-service", "test-instance"); + + AtomicReference failureReference = new AtomicReference<>(); + runAsGameDesign( + () -> + failureReference.set(invokeDigestFailure(service, fullDigestRequest(changedBinding)))); + + assertThat(failureReference.get().getStatus().getCode()).isEqualTo(Status.Code.ALREADY_EXISTS); + Mockito.verify(repository).findTerminal(authorization.operationId()); + } + @Test void getDraftDesignDigestMapsUnexpectedUnsupportedOperationToInternalError() { GameLogicDraftDesignDigestService digestService = mockDigestService(); - Mockito.when(digestService.getDraftDesignDigest("1", "7")) + Mockito.when( + digestService.getDraftDesignDigest(any(GameLogicPublicationSourceReadBinding.class))) .thenThrow(new UnsupportedOperationException("unexpected implementation failure")); SessionContext.setContext( null, List.of(), Map.of(), true, "game-design-service", "test-instance"); GameLogicGrpcService service = newDigestService(digestService); AtomicReference response = new AtomicReference<>(); - runAsGameDesign(() -> response.set(invokeDigest(service, fullDigestRequest("1", "7")))); + runAsGameDesign( + () -> response.set(invokeDigest(service, fullDigestRequest(TEST_TENANT.toString(), "7")))); assertTrue(response.get().hasError()); assertEquals("INTERNAL", response.get().getError().getCode()); assertEquals("Internal error", response.get().getError().getMessage()); } + @Test + void getDraftDesignDigestReturnsSanitizedTransportStatusesWhenSourceReadFails() { + GameLogicDraftDesignDigestService digestService = mockDigestService(); + SessionContext.setContext( + null, List.of(), Map.of(), true, "game-design-service", "test-instance"); + var meters = new SimpleMeterRegistry(); + GameLogicGrpcService service = newDigestService(digestService, TEST_NAMESPACE, meters); + for (Status.Code code : + List.of( + Status.Code.FAILED_PRECONDITION, + Status.Code.UNAVAILABLE, + Status.Code.ALREADY_EXISTS, + Status.Code.INTERNAL, + Status.Code.UNKNOWN)) { + Mockito.reset(digestService); + Mockito.when( + digestService.getDraftDesignDigest(any(GameLogicPublicationSourceReadBinding.class))) + .thenThrow( + Status.fromCode(code) + .withDescription("database-password-secret") + .asRuntimeException()); + AtomicReference failure = new AtomicReference<>(); + runAsGameDesign( + () -> + failure.set( + invokeDigestFailure(service, fullDigestRequest(TEST_TENANT.toString(), "7")))); + + var statusFailure = failure.get(); + assertThat(statusFailure.getStatus().getCode()).isEqualTo(code); + assertThat(statusFailure.getStatus().getDescription()) + .isEqualTo("Exact retained publication source read failed") + .hasSizeLessThan(128) + .doesNotContain("secret", "database"); + assertThat(statusFailure.getCause()).isNull(); + assertThat(statusFailure.getTrailers()).isNull(); + assertThat(meters.get("grpc.app_error").tag("code", code.name()).counter().count()) + .isEqualTo(1.0); + } + } + @Test void getDraftDesignDigestRejectsMissingPeerIdentityForInternalCaller() { GameLogicDraftDesignDigestService digestService = mockDigestService(); @@ -358,7 +601,7 @@ void getDraftDesignDigestRejectsMissingPeerIdentityForInternalCaller() { .run( () -> service.getDraftDesignDigest( - fullDigestRequest("1", "7"), + fullDigestRequest(TEST_TENANT.toString(), "7"), new StreamObserver<>() { @Override public void onNext(GetDraftDesignDigestResponse value) { @@ -379,7 +622,7 @@ public void onCompleted() {} void getDraftDesignDigestRejectsWrongPeerAndUserOrAdminJwt() { GameLogicDraftDesignDigestService digestService = mockDigestService(); GameLogicGrpcService service = newDigestService(digestService); - GetDraftDesignDigestRequest request = fullDigestRequest("1", "7"); + GetDraftDesignDigestRequest request = fullDigestRequest(TEST_TENANT.toString(), "7"); SessionContext.setContext(null, List.of(), Map.of(), true, "game-design-service", "instance-1"); withPeer( @@ -408,6 +651,13 @@ private GameLogicGrpcService newDigestService(GameLogicDraftDesignDigestService private GameLogicGrpcService newDigestService( GameLogicDraftDesignDigestService digestService, String workloadNamespace) { + return newDigestService(digestService, workloadNamespace, new SimpleMeterRegistry()); + } + + private GameLogicGrpcService newDigestService( + GameLogicDraftDesignDigestService digestService, + String workloadNamespace, + SimpleMeterRegistry meters) { return new GameLogicGrpcService( new PingServiceImpl(), new CommandServiceImpl( @@ -419,7 +669,7 @@ private GameLogicGrpcService newDigestService( Mockito.mock(ItemRuntimeService.class), digestService, mockAttestationService(), - new SimpleMeterRegistry(), + meters, workloadNamespace); } @@ -435,25 +685,11 @@ void getDraftDesignDigestFailsClosedWhenWorkloadNamespaceIsMissingOrInvalid() { () -> assertEquals( "PERMISSION_DENIED", - invokeDigest(service, fullDigestRequest("1", "7")).getError().getCode())); + invokeDigest(service, fullDigestRequest(TEST_TENANT.toString(), "7")) + .getError() + .getCode())); } Mockito.verifyNoInteractions(digestService); - - GameLogicDraftDesignDigestService configuredDigestService = mockDigestService(); - Mockito.when(configuredDigestService.getDraftDesignDigest("1", "7")) - .thenReturn( - new GameLogicDraftDesignDigestService.GameLogicDraftDesignDigest( - "1", "7", "version:7", "digest-game-logic", 1)); - GameLogicGrpcService configuredService = - newDigestService(configuredDigestService, TEST_NAMESPACE); - AtomicReference configuredResponse = new AtomicReference<>(); - runAsGameDesign( - () -> configuredResponse.set(invokeDigest(configuredService, fullDigestRequest("1", "7")))); - - assertTrue(configuredResponse.get().getError().getCode().isEmpty()); - assertEquals("1", configuredResponse.get().getTenantId()); - assertEquals("7", configuredResponse.get().getVersionId()); - Mockito.verify(configuredDigestService).getDraftDesignDigest("1", "7"); } private GetDraftDesignDigestResponse invokeDigest( @@ -486,6 +722,36 @@ public void onCompleted() {} return response; } + private StatusRuntimeException invokeDigestFailure( + GameLogicGrpcService service, GetDraftDesignDigestRequest request) { + AtomicReference failure = new AtomicReference<>(); + service.getDraftDesignDigest( + request, + new StreamObserver<>() { + @Override + public void onNext(GetDraftDesignDigestResponse value) { + fail("expected a transport failure, got response: " + value); + } + + @Override + public void onError(Throwable t) { + failure.set(t); + } + + @Override + public void onCompleted() { + fail("transport failure must not complete successfully"); + } + }); + if (failure.get() == null) { + throw new AssertionError("getDraftDesignDigest completed without a transport failure"); + } + if (!(failure.get() instanceof StatusRuntimeException statusFailure)) { + throw new AssertionError("getDraftDesignDigest returned a non-status failure", failure.get()); + } + return statusFailure; + } + private static void withPeer(GrpcPeerIdentity peer, Runnable action) { Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); Context previous = context.attach(); diff --git a/services/game-session-service/Dockerfile b/services/game-session-service/Dockerfile index c1b20e68bf..fec569e1ef 100644 --- a/services/game-session-service/Dockerfile +++ b/services/game-session-service/Dockerfile @@ -3,8 +3,12 @@ FROM ${BASE_IMAGE} USER root WORKDIR /app COPY --chmod=644 *.jar /app/ +# Gradle emits proof-only JARs alongside the executable Spring Boot JAR. RUN set -e; \ - jar="$(find /app -maxdepth 1 -type f -name 'game-session-service-*.jar' ! -name '*-plain.jar' ! -name '*-test-fixtures.jar' | head -n 1)"; \ + candidates="$(find /app -maxdepth 1 -type f -name 'game-session-service-*.jar' ! -name '*-plain.jar' ! -name '*-test-fixtures.jar' ! -name '*-classes-proof.jar')"; \ + test -n "${candidates}"; \ + test "$(printf '%s\n' "${candidates}" | wc -l)" -eq 1; \ + jar="${candidates}"; \ test -n "${jar}"; \ mv "${jar}" /app/app.jar; \ find /app -maxdepth 1 -type f -name '*.jar' ! -name 'app.jar' -delete; \ diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java index cbc19aa846..a08009b045 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java @@ -196,36 +196,38 @@ public static Result applyFreezeAndCapture( new java.util.concurrent.atomic.AtomicReference< WorldSelectedDraftPublicationCheckpointRepository.CapturedCheckpoint>(); var createdCheckpointInTransaction = new java.util.concurrent.atomic.AtomicBoolean(); + var freezeTransaction = new TransactionTemplate(worldTransactions); + freezeTransaction.setIsolationLevel( + org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); var frozenAttempt = Objects.requireNonNull( - new TransactionTemplate(worldTransactions) - .execute( - status -> { - createdCheckpointInTransaction.set(false); - var attempt = - fence.claimFreeze( - freeze, - () -> { - var captured = checkpointRepository.captureWithSource(freeze, plan); - capturedCheckpoint.set(captured); - createdCheckpointInTransaction.set(true); - return captured.checkpoint(); - }); - var retainedAccount = - authorizationRepository.retainOrRequireExact( - attempt, accountBinding, createdCheckpointInTransaction.get()); - if (!java.util.Arrays.equals( - retainedAccount.canonicalBytes(), accountBinding.canonicalBytes())) { - throw new IllegalStateException( - "World did not retain the exact original Account publication binding"); - } - inventoryRepository.retainOrRequireExact( - attempt, - retainedAccount, - createdCheckpointInTransaction.get(), - capturedCheckpoint.get()); - return attempt; - })); + freezeTransaction.execute( + status -> { + createdCheckpointInTransaction.set(false); + var attempt = + fence.claimFreeze( + freeze, + () -> { + var captured = checkpointRepository.captureWithSource(freeze, plan); + capturedCheckpoint.set(captured); + createdCheckpointInTransaction.set(true); + return captured.checkpoint(); + }); + var retainedAccount = + authorizationRepository.retainOrRequireExact( + attempt, accountBinding, createdCheckpointInTransaction.get()); + if (!java.util.Arrays.equals( + retainedAccount.canonicalBytes(), accountBinding.canonicalBytes())) { + throw new IllegalStateException( + "World did not retain the exact original Account publication binding"); + } + inventoryRepository.retainOrRequireExact( + attempt, + retainedAccount, + createdCheckpointInTransaction.get(), + capturedCheckpoint.get()); + return attempt; + })); var checkpoint = Objects.requireNonNull( @@ -345,6 +347,8 @@ public static AppliedGraph applyGraph( var intakeRepository = new WorldAuthoredSourceIntakeRepository(worldDsl); var versionRepository = new WorldAuthoredVersionIdentityRepository(worldDsl); var write = new TransactionTemplate(worldTransactions); + write.setIsolationLevel( + org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); var intake = Objects.requireNonNull( write.execute(