diff --git a/.github/workflows/build-trusted-minio-source-images.yml b/.github/workflows/build-trusted-minio-source-images.yml index 86a75dc4fe..50f6d17101 100644 --- a/.github/workflows/build-trusted-minio-source-images.yml +++ b/.github/workflows/build-trusted-minio-source-images.yml @@ -6,12 +6,36 @@ on: - '.github/workflows/build-trusted-minio-source-images.yml' - 'docker/minio/**' - 'dev-tools/minio/**' + - 'services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/AssetStoreProperties.java' + - 'services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java' + - 'services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/AssetExportOutcomePendingException.java' + - 'services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/AssetExportService.java' + - 'services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/ExportedAssetManifest.java' + - 'services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedArtifactDigest.java' + - 'services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetExportCandidateService.java' + - 'services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationService.java' + - 'services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java' + - 'services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java' + - 'services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceMinioIntegrationTest.java' + - 'services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationMinioPostgresIntegrationTest.java' push: branches: [develop] paths: - '.github/workflows/build-trusted-minio-source-images.yml' - 'docker/minio/**' - 'dev-tools/minio/**' + - 'services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/AssetStoreProperties.java' + - 'services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java' + - 'services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/AssetExportOutcomePendingException.java' + - 'services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/AssetExportService.java' + - 'services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/ExportedAssetManifest.java' + - 'services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedArtifactDigest.java' + - 'services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetExportCandidateService.java' + - 'services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationService.java' + - 'services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java' + - 'services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java' + - 'services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceMinioIntegrationTest.java' + - 'services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationMinioPostgresIntegrationTest.java' permissions: contents: read @@ -52,14 +76,16 @@ jobs: changed_paths="$(git diff --name-only "$BASE_SHA...$HEAD_SHA")" has_source_change=false has_workflow_change=false + has_asset_export_change=false while IFS= read -r path; do case "$path" in docker/minio/*|dev-tools/minio/*) has_source_change=true ;; .github/workflows/build-trusted-minio-source-images.yml) has_workflow_change=true ;; + services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/AssetStoreProperties.java|services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java|services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/AssetExportOutcomePendingException.java|services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/AssetExportService.java|services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/ExportedAssetManifest.java|services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedArtifactDigest.java|services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetExportCandidateService.java|services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationService.java|services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java|services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java|services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceMinioIntegrationTest.java|services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationMinioPostgresIntegrationTest.java) has_asset_export_change=true ;; esac done <<< "$changed_paths" - if [[ "$has_source_change" == true && "$has_workflow_change" == false ]]; then + if [[ "$has_source_change" == true && "$has_workflow_change" == false && "$has_asset_export_change" == false ]]; then should_build=false fi fi @@ -86,8 +112,22 @@ jobs: - name: Check out source uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} persist-credentials: false + - name: Set up Java + uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6 + with: + distribution: 'temurin' + java-version: '25' + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@3f5f9adaf7d9fecd50b5935e54106014257a94e6 # v6 + with: + build-scan-publish: true + build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' + build-scan-terms-of-use-agree: 'yes' + - name: Set up canonical Python uses: ./.github/actions/setup-python @@ -97,6 +137,74 @@ jobs: EXPORT_TRUSTED_MINIO_IMAGE_ARTIFACT: ${{ github.event_name == 'push' && 'true' || 'false' }} run: bash ./dev-tools/minio/build-and-smoke-images.sh "$SERVER_IMAGE" "$CLIENT_IMAGE" + - name: Prove Game Design asset export against source-built MinIO + env: + MINIO_ASSET_EXPORT_ACCESS_KEY: smoke-access-key + MINIO_ASSET_EXPORT_SECRET_KEY: smoke-secret-key-123456789 + run: | + set -euo pipefail + container_name="minio-asset-export-proof-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + container_created=false + cleanup() { + if [[ "$container_created" == true ]]; then + docker rm --force "$container_name" >/dev/null 2>&1 || true + fi + } + trap cleanup EXIT + + docker run --detach --name "$container_name" \ + --publish 127.0.0.1::9000/tcp \ + --env MINIO_ROOT_USER="$MINIO_ASSET_EXPORT_ACCESS_KEY" \ + --env MINIO_ROOT_PASSWORD="$MINIO_ASSET_EXPORT_SECRET_KEY" \ + "$SERVER_IMAGE" >/dev/null + container_created=true + + ready=false + attempt=0 + while ((attempt < 30)); do + attempt=$((attempt + 1)) + if docker exec "$container_name" busybox wget -q -T 2 -O /dev/null \ + http://127.0.0.1:9000/minio/health/live; then + ready=true + break + fi + sleep 2 + done + if [[ "$ready" != true ]]; then + docker logs "$container_name" >&2 || true + echo "Source-built MinIO provider for the Game Design proof did not become healthy." >&2 + exit 1 + fi + + published_port="$(docker port "$container_name" 9000/tcp | sed 's/.*://')" + [[ "$published_port" =~ ^[0-9]+$ ]] + export MINIO_ASSET_EXPORT_ENDPOINT="http://127.0.0.1:$published_port" + test -n "$MINIO_ASSET_EXPORT_ACCESS_KEY" + test -n "$MINIO_ASSET_EXPORT_SECRET_KEY" + ./gradlew --rerun-tasks \ + :game-design-service:test \ + --tests 'net.firedevops.firemud.gamedesign.service.AssetExportServiceMinioIntegrationTest' \ + :game-design-service:integrationTest \ + --tests 'net.firedevops.firemud.gamedesign.service.VersionAssetPublicationMinioPostgresIntegrationTest' + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.gamedesign.service.AssetExportServiceMinioIntegrationTest \ + --require-suite net.firedevops.firemud.gamedesign.service.VersionAssetPublicationMinioPostgresIntegrationTest \ + --require-case 'net.firedevops.firemud.gamedesign.service.AssetExportServiceMinioIntegrationTest#publishesConditionallyReadsBackExactBytesAndRecoversCommittedPutAgainstMinio()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.VersionAssetPublicationMinioPostgresIntegrationTest#composesPostgresSnapshotAndCandidateWithMinioBeforeWriteAndRetriesAfterLostAcknowledgement()' \ + game-design-service + + - name: Upload Game Design MinIO proof XML + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: game-design-minio-provider-proof-${{ github.run_id }}-${{ github.run_attempt }} + path: | + services/game-design-service/build/test-results/test/*AssetExportServiceMinioIntegrationTest*.xml + services/game-design-service/build/test-results/integrationTest/*VersionAssetPublicationMinioPostgresIntegrationTest*.xml + if-no-files-found: warn + retention-days: 7 + - name: Upload exact smoke-tested image artifact if: github.event_name == 'push' uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2787770b4d..71c24b14e0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,7 +4,6 @@ on: push: branches: [ main, develop ] pull_request: - branches: [ main, develop ] types: [opened, synchronize, reopened, edited] workflow_dispatch: @@ -954,12 +953,18 @@ jobs: --tests integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepositoryIntegrationTest \ --tests integration.net.firedevops.firemud.gamedesign.repository.VersionCanonicalIdentityIntegrationTest \ --tests integration.net.firedevops.firemud.gamedesign.repository.PublishedReleaseCanonicalIdentityIntegrationTest \ + --tests integration.net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepositoryIntegrationTest \ + --tests integration.net.firedevops.firemud.gamedesign.service.impl.VersionAssetExportCandidateServiceIntegrationTest \ + --tests net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepositoryIntegrationTest \ -PfullCheck --no-build-cache --no-configuration-cache bash dev-tools/validation/inspect-test-results.sh \ --strict \ --require-suite integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest \ --require-suite integration.net.firedevops.firemud.gamedesign.repository.VersionCanonicalIdentityIntegrationTest \ --require-suite integration.net.firedevops.firemud.gamedesign.repository.PublishedReleaseCanonicalIdentityIntegrationTest \ + --require-suite integration.net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepositoryIntegrationTest \ + --require-suite integration.net.firedevops.firemud.gamedesign.service.impl.VersionAssetExportCandidateServiceIntegrationTest \ + --require-suite net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepositoryIntegrationTest \ --require-suite net.firedevops.firemud.gamedesign.service.EntityDigestBaselineMigrationIntegrationTest \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest#appliesAuditedAssociationForFreshAndRetainedGameSources()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest#versionLockRepositoryUsesConfiguredIsolatedOwnerSchema()' \ @@ -977,10 +982,48 @@ jobs: --require-case 'integration.net.firedevops.firemud.gamedesign.repository.PublishedReleaseCanonicalIdentityIntegrationTest#repositoryNestedTransactionRollsBackWithOuterSpringPublisherTransaction()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.PublishedReleaseCanonicalIdentityIntegrationTest#deniesWrongTenantNilAndSubstitutedCallerOrDatabaseIdentityWithoutGrowingBundles()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.PublishedReleaseCanonicalIdentityIntegrationTest#bundleIdentityIsImmutableRetainedNullCannotBeBackfilledAndMetadataCannotBeDeleted()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepositoryIntegrationTest#v37LeavesRetainedVersionTupleAndXminUnchangedAndDeniesItsUnmappedIdentity()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepositoryIntegrationTest#freezesOnlyExactMappedBytesAndRetriesFromCommittedSnapshotAfterNewAssetAndServiceRestart()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepositoryIntegrationTest#durableHeaderDistinguishesProvedEmptySelectionFromMissingSnapshot()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepositoryIntegrationTest#deniesTenantIdentityAndUsageCollisionsWithoutMutatingOwnerRows()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepositoryIntegrationTest#concurrentDraftMappingAndFirstFreezeSerializeOnTheExactVersionRow()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepositoryIntegrationTest#frozenSnapshotAndItsRepairSourcesRejectMutationAndSnapshotBuildRollsBackAtomically()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepositoryIntegrationTest#committedSnapshotSurvivesCallingTransactionRollback()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.impl.VersionAssetExportCandidateServiceIntegrationTest#durableCandidateIsSnapshotBoundRetryableAndIncludesManifestAndBinaryProofs()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.impl.VersionAssetExportCandidateServiceIntegrationTest#emptyFrozenSnapshotIsExplicitAndMissingSnapshotOrArtifactIsNeverInferred()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.impl.VersionAssetExportCandidateServiceIntegrationTest#retainedNullCandidateFieldsRemainAbsentAcrossV38WithoutReadInference()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.impl.VersionAssetExportCandidateServiceIntegrationTest#failedDatabaseCandidateWriteRollsBackAllEvidenceAndEpoch()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.impl.VersionAssetExportCandidateServiceIntegrationTest#concurrentExactCandidateRecordsCommitOneEpochAndCallerRollbackCannotUndoIt()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.impl.VersionAssetExportCandidateServiceIntegrationTest#databaseFreezesAllCandidateProofFieldsAndEpochOverflowWritesNothing()' \ + --require-case 'net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepositoryIntegrationTest#stagedIntentCommitsThroughSpringProxyBeforeCallingTransactionRollsBack()' \ + --require-case 'net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepositoryIntegrationTest#saveAndFindRoundTripTimestampFields()' \ --require-case 'net.firedevops.firemud.gamedesign.service.EntityDigestBaselineMigrationIntegrationTest#exactRetryReadsCommittedEvidenceWithoutCallingEntityAgain()' \ --require-case 'net.firedevops.firemud.gamedesign.service.EntityDigestBaselineMigrationIntegrationTest#databaseMigrationRolesHaveOnlyTheirDirectTablePrivileges()' \ game-design-service + - name: Verify Game Design fresh tenant creation PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'game-design-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepositoryIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepositoryIntegrationTest#createCandidateExactRetryReturnsCommittedReceiptWithoutSecondGameWrite()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepositoryIntegrationTest#concurrentDuplicateCreationRequestsConvergeOnOneUuidAndReceipt()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepositoryIntegrationTest#runtimeIdentityLookupReadsOnlyExactNewAndRetainedGameDesignRows()' \ + game-design-service + + - name: Verify Game Design authored-world source PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'game-design-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepositoryIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepositoryIntegrationTest#registersAndReadsExactFreshAndRetainedV29ToV30Sources()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepositoryIntegrationTest#failedOwnerCommitRollsBackBothTenantSelectorAndWorldSource()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepositoryIntegrationTest#concurrentExactRegistrationRetriesReturnOnePersistedReceipt()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepositoryIntegrationTest#concurrentDifferentTenantsCannotClaimTheSameTenantSlug()' \ + game-design-service + - name: Capture Game Design owner component proof before later test selectors if: ${{ always() && matrix.module == 'game-design-service' }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 @@ -1014,7 +1057,10 @@ jobs: --require-case 'integration.net.firedevops.firemud.gamedesign.service.LaunchDescriptorServiceIntegrationTest#concurrentSuccessAndFailureCandidatesPersistOnlyTheFirstOutcome()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.service.LaunchDescriptorServiceIntegrationTest#rolledBackDescriptorInsertLeavesNoCanonicalOrPrivateRequestClaim()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.service.LaunchDescriptorServiceIntegrationTest#v35AndV36MigrationsPreserveRetainedBundleAndUnboundDescriptorWithoutBackfill()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.LaunchDescriptorServiceIntegrationTest#v39MigrationPreservesRetainedPublicationEvidenceAndStoresLongDiagnostics()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.PublishAttemptServiceTransactionIntegrationTest#recordsAndIndependentlyReadsDedicatedAbilitySchemaDigestOnPublishAttempt()' \ --require-case 'net.firedevops.firemud.gamedesign.service.PublishAttemptServiceTransactionIntegrationTest#reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogether()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.PublishAttemptServiceTransactionIntegrationTest#finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet()' \ --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldLaunchDescriptorMtlsTest#exactGameSessionPeerResolvesAndEchoesTheFullCanonicalDescriptor()' \ --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldLaunchDescriptorMtlsTest#gameSessionAndWorldPeersReadExactDescriptorAndEchoReadRequestIdentity()' \ --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldLaunchDescriptorMtlsTest#worldPeerCannotResolveBeforeDescriptorProducerAccess()' \ @@ -2285,29 +2331,6 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationIntegrationTest#generationFailureRollsBackFreshAssociationAndCanonicalClaim()' \ account-service - - name: Verify Game Design fresh tenant creation PostgreSQL proof - if: ${{ !cancelled() && matrix.module == 'game-design-service' }} - run: | - bash dev-tools/validation/inspect-test-results.sh \ - --strict \ - --require-suite integration.net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepositoryIntegrationTest \ - --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepositoryIntegrationTest#createCandidateExactRetryReturnsCommittedReceiptWithoutSecondGameWrite()' \ - --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepositoryIntegrationTest#concurrentDuplicateCreationRequestsConvergeOnOneUuidAndReceipt()' \ - --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepositoryIntegrationTest#runtimeIdentityLookupReadsOnlyExactNewAndRetainedGameDesignRows()' \ - game-design-service - - - name: Verify Game Design authored-world source PostgreSQL proof - if: ${{ !cancelled() && matrix.module == 'game-design-service' }} - run: | - bash dev-tools/validation/inspect-test-results.sh \ - --strict \ - --require-suite integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepositoryIntegrationTest \ - --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepositoryIntegrationTest#registersAndReadsExactFreshAndRetainedV29ToV30Sources()' \ - --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepositoryIntegrationTest#failedOwnerCommitRollsBackBothTenantSelectorAndWorldSource()' \ - --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepositoryIntegrationTest#concurrentExactRegistrationRetriesReturnOnePersistedReceipt()' \ - --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepositoryIntegrationTest#concurrentDifferentTenantsCannotClaimTheSameTenantSlug()' \ - game-design-service - - name: Verify Account fresh UUID pair and snapshot PostgreSQL proof if: ${{ !cancelled() && matrix.module == 'account-service' }} run: | @@ -2438,7 +2461,7 @@ jobs: contents: read pull-requests: write needs: [buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, validation-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 19c5fa387a..412f34e874 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -179,8 +179,8 @@ jobs: fail("source workflow run API id does not match the event") if source_run.get("workflow_id") != int(workflow_id_text): fail("source workflow identity changed between event and API") - if source_run.get("name") != source_title: - fail("source workflow API name differs from its exact run title") + if source_run.get("name") not in {"Build Runtime Images", source_title}: + fail("source workflow API name is neither its owning name nor exact run title") if source_run.get("path") != SOURCE_WORKFLOW_PATH: fail("source workflow API path is not the trusted runtime-images workflow") if source_run.get("event") != source_event: diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 67013db104..df21260621 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -113,6 +113,7 @@ jobs: uses: ./.github/actions/setup-trivy - name: 🔍 Run Trivy and Save Report + shell: bash run: | echo "::group::Run Trivy" trivy fs --config config/security/trivy.yaml . | tee trivy-report.txt @@ -207,7 +208,7 @@ jobs: contents: read pull-requests: write # Publishes the consolidated security result on the PR. needs: [changes, trivy-scan, secret-compliance, security-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c65b36fb4f..b7e861e41a 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -88,6 +88,7 @@ jobs: ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", "dev-tools/smoke/", + "dev-tools/minio/", ]; const fullRelevantFiles = new Set([ "build.gradle.kts", @@ -145,7 +146,7 @@ jobs: contents: read pull-requests: write needs: [changes] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -198,6 +199,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -277,7 +298,7 @@ jobs: contents: read pull-requests: write needs: [changes, smoke-gate, smoke-summary-pending] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -334,6 +355,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -476,7 +517,11 @@ jobs: const eventMergeSha = context.sha; const prNumber = String(context.payload.pull_request.number); const started = Date.now(); - const timeoutMs = 25 * 60 * 1000; + // Contract-checked against pr-local-smoke; bounded overhead covers metadata, + // runner scheduling and API convergence, not unbounded queue delays. + const producerTimeoutMinutes = 45; + const prerequisiteAndQueueAllowanceMinutes = 45; + const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000; const cancelledReplacementTimeoutMs = 5 * 60 * 1000; const sleepMs = 15000; const pullRequestCheckInterval = 4; diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 4a89119f45..b4c906f7b3 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -65,7 +65,8 @@ jobs: if ( currentPullRequest.state !== "open" || !sourceWorkflowName || - context.payload.workflow_run.name !== expectedSourceTitle || + (context.payload.workflow_run.name !== sourceWorkflowName && + context.payload.workflow_run.name !== expectedSourceTitle) || context.payload.workflow_run.display_title !== expectedSourceTitle ) { core.info("The source run is not bound to the current open pull-request base and head."); diff --git a/design/architecture/microservices/automation-scripting-service/api-contracts.md b/design/architecture/microservices/automation-scripting-service/api-contracts.md index 91b3ec3d96..15dc0d8a54 100644 --- a/design/architecture/microservices/automation-scripting-service/api-contracts.md +++ b/design/architecture/microservices/automation-scripting-service/api-contracts.md @@ -207,7 +207,7 @@ Retry identity and timer catch-up behavior follow the linked scripting contract. The service exposes control-plane read and lifecycle surfaces for script patch visibility and plugin runtime lifecycle management: -- `GetScriptPatchStatus(tenantId, scriptPatchVersion)` – returns the current runtime-readiness lifecycle state plus the published script patch `baseVersionId`, compatibility digest metadata, timestamps, and any last-error details. Target `abilitySchemaDigest` must come only from the dedicated Game Logic-owned release attestation; if that attestation is missing or unavailable, the status/compatibility result must fail closed or report an explicit unavailable compatibility state, never fall back to Automation's aggregate participant digest. The current response is not compliant: it returns an empty digest when release-attestation lookup fails and otherwise derives the field from Automation's aggregate participant digest, so it does not prove ability-schema compatibility. +- `GetScriptPatchStatus(tenantId, scriptPatchVersion)` – returns the current runtime-readiness lifecycle state plus the published script patch `baseVersionId`, compatibility digest metadata, timestamps, and any last-error details. Target `abilitySchemaDigest` must come only from the dedicated Game Logic-owned release attestation; if that attestation is missing or unavailable, the status/compatibility result must fail closed or report an explicit unavailable compatibility state, never fall back to Automation's aggregate participant digest. The candidate reader makes the existing tenant-scoped owner request and accepts only one supported Game Logic participant with dedicated evidence for the exact full base Version; missing, conflicting or unavailable proof leaves compatibility metadata empty. That absence is not positive compatibility evidence. The local tenant selector is not an independently verified canonical UUID association to the response. That binding, the normal Game Logic rule/ability source producer and complete authenticated activation proof remain open. - `ListScriptPatchStatuses(tenantId, status?, changedAfter?, changedBefore?)` – lists known tenant patch statuses with the same publication metadata fields used by the single-patch read. - `ScriptPatchTenantStatusChanged` – emitted whenever `` transitions between tenant readiness lifecycle states. - `ScriptPatchPinChanged` – consumed only as a non-authoritative notification to refresh Automation's observed pin/convergence projection. Game Session's direct current-pin and bounded rollout-history reads remain authoritative. Any legacy patch-only `PINNED`, `REPINNED`, and `ROLLED_BACK` projection statuses/events are internal migration diagnostics only; they must never be exposed or consumed as public rollout status/event semantics. The target projection remains exact-epoch observed state and must not derive rollout history locally. diff --git a/design/architecture/microservices/game-design-service/ability-action-tools.md b/design/architecture/microservices/game-design-service/ability-action-tools.md index d938afe9f5..4e8d22d3d8 100644 --- a/design/architecture/microservices/game-design-service/ability-action-tools.md +++ b/design/architecture/microservices/game-design-service/ability-action-tools.md @@ -1,6 +1,6 @@ # Ability & Action Design Tools -This document outlines the editors for defining abilities, actions, and combat mechanics. The tooling is part of the Game Design Service and pushes finalized data to the [Game Logic Service](../game-logic-service/README.md) during version publishing. +This document outlines the editors for defining abilities, actions, and combat mechanics. The tooling is part of the Game Design Service. Its target owner handoff applies Draft rule and ability revisions to the [Game Logic Service](../game-logic-service/README.md) before publication under the canonical [commit and revision synchronization contract](version-control.md#design-time-synchronization); publication verifies that existing owner state rather than copying a separate design database. The publish workflow is part of the durable control-plane workflow described in [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md). @@ -9,7 +9,7 @@ The publish workflow is part of the durable control-plane workflow described in The current proven behavior is stable-reference validation against the exact published base version for the plugin publication path. `abilitySchemaDigest` is persisted in plugin metadata and exposed by the publication read, but dedicated Game Logic-owned release-attested ability-schema validation remains target-state and unproved. Current plugin publication and activation compare the plugin's `abilitySchemaDigest` with the published `AUTOMATION_SCRIPTING` aggregate participant digest; that aggregate comparison is not a dedicated ability-schema attestation. Script-patch publication does not currently enforce same-tenant published-base identity, and launch resolution does not currently prove same-base published patch identity or Automation `READY`; those are implementation gaps. Exact `scriptPinEpoch` propagation and same-version old-epoch rejection at runtime handoff are target-state and remain unproved; this design-time editor does not establish that runtime proof. See the [Automation and Scheduler Runtime tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#script-transition-reconciliation) and [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md). Data entered in these editors is stored as revisions using the `SaveRevision` gRPC call defined in [`game_design_service.proto`](../../../../protos/game-design/v1/game_design_service.proto). -Finalized versions are published with `PublishVersion` so the Game Logic Service can load the rules as part of the cross-service publish workflow described in the [Game Design Service Architecture](README.md). +Finalized versions are published with `PublishVersion` only after the required owner Draft state and exact commit-bound evidence exist under [version control](version-control.md#history-and-provenance-across-services). The current generic revision store is not a completed Game Logic rule/ability producer; that owner-local application, provenance and dedicated digest remain open in the [publishing tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md). Ability definitions use a structured schema delivered through the API. diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 4247471204..2d8215c996 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -131,7 +131,7 @@ For a `SaveRevision` request carrying `worldDesignMutation`, the same authorizat The release-attestation, launch-resolution, version-state, settings, asset-purge, script-patch publication-read APIs, and first plugin publication workflow (`UploadPluginBundle`, `PublishPluginVersion`, `GetPublishedPluginVersion`, and `ListPluginVersionStatuses`) are present in the current proto/service path. Public full-version `PublishVersion` requires the Temporal `publish` orchestrator and returns `PUBLISH_WORKFLOW_UNAVAILABLE` when it is absent or disabled. The underlying command and readback callbacks remain workflow activities; they are not a synchronous public fallback. The four owner-to-owner digest reads use the distinct Game Design workload identity, exact method guards, and complete tenant/scope/request binding. End-to-end Temporal publication remains unproved: Automation rejects both unsupported digest scopes, Game Logic fails closed without the owner-local rule-input manifest/provenance, and live mounted-certificate, Temporal-activity, and multi-version owner proof remain outstanding (see [Game Logic API Contracts](../game-logic-service/api-contracts.md#implementation-status)). An exception after external export or release-bundle write leaves the original attempt outcome pending until reconciliation reads back its identity and all release evidence; a failure marker alone does not prove terminality or safe cleanup. -`UploadPluginBundle` parses signed plugin bundles, enforces bounded ZIP intake limits, verifies allowlisted Ed25519 signatures, extracts immutable manifest metadata, persists the raw bundle in Game Design storage, and records a durable `SIGNATURE_VERIFIED` row. Current intake selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set; the current proto/storage also lack an append-only signature-evidence ledger and append RPC. `PublishPluginVersion` validates the uploaded bundle and published base-version release, applies component policy, exports plugin assets into a version-scoped distribution manifest, and best-effort supersedes older published versions. Its current `abilitySchemaDigest` comparison incorrectly uses the attested `AUTOMATION_SCRIPTING` aggregate participant digest; exact ability-schema compatibility remains unproved until the release bundle and validator use the dedicated Game Logic-owned attestation for the same base version. `RevokePluginVersion` and `ListPluginVersionStatusEvents` provide the current design-time revoke and append-only publication-event read surfaces; dedicated ability-schema proof and broader activation-time alias/binding validation remain open. The official-hosted Account currentness evaluation and durable tenant/evidence binding required by [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) are not implemented for creator mutations. +`UploadPluginBundle` parses signed plugin bundles, enforces bounded ZIP intake limits, verifies allowlisted Ed25519 signatures, extracts immutable manifest metadata, persists the raw bundle in Game Design storage, and records a durable `SIGNATURE_VERIFIED` row. Current intake selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set; the current proto/storage also lack an append-only signature-evidence ledger and append RPC. `PublishPluginVersion` validates the uploaded bundle and published base-version release, applies component policy, exports plugin assets into a version-scoped distribution manifest, and best-effort supersedes older published versions. The candidate now compares the dedicated `GAME_LOGIC` participant `abilitySchemaDigest` retained with its exact full-version release scope, commit and supported digest schema; an aggregate digest, absent value or wrong owner is rejected without publication mutation. The normal Game Logic ability-schema source producer and complete activation compatibility remain unproved. `RevokePluginVersion` and `ListPluginVersionStatusEvents` provide the current design-time revoke and append-only publication-event read surfaces; dedicated ability-schema proof and broader activation-time alias/binding validation remain open. The official-hosted Account currentness evaluation and durable tenant/evidence binding required by [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) are not implemented for creator mutations. The following implementation and proof gaps remain in these live paths: @@ -233,7 +233,8 @@ Detailed request and response schemas are defined in the [OpenAPI specification] - `CompareAndSetVersionState(CompareAndSetVersionStateRequest) returns (CompareAndSetVersionStateResponse)` – **Target state:** performs database CAS-guarded, legal lifecycle transitions; the current implementation locks the exact Version row for its epoch comparison/save, but does not enforce the legal transition, release-artifact, or retirement predicates. - `GetDesignControlPlaneDigest(GetDesignControlPlaneDigestRequest) returns (GetDesignControlPlaneDigestResponse)` – returns normalized metadata digest used by publish gates. - `GetTemplateReferencePhase(GetTemplateReferencePhaseRequest) returns (GetTemplateReferencePhaseResponse)` – **Target state only; the current proto has no such RPC:** returns the persisted normalized-reference enforcement phase (`BACKFILLING`, `VALIDATED`, `ENFORCED`) used by instance-creation and retirement workflows. -- `GetPublishedReleaseBundle(GetPublishedReleaseBundleRequest) returns (GetPublishedReleaseBundleResponse)` – **Target response:** returns the immutable `(tenantId, versionId)` release attestation including participant digests, the dedicated Game Logic-owned `abilitySchemaDigest` for the same target commit (using Game Logic's existing participant `digestSchemaVersion` and canonicalization evidence), any required `artifactDigests[]` and `requiredManifestAssetKeys[]` for exported derived assets, `manifestHash`, `generationConfigRevision`, and the canonical publish workflow runtime metadata (`publishWorkflowId`, `workflowRunId`, `workflowStatus`). **Current live response/compatibility path:** the implementation still uses the attested `AUTOMATION_SCRIPTING` aggregate participant digest in place of the dedicated ability-schema field; that aggregate is not ability-schema proof, so consumers must fail closed until the target field and evidence converge. Missing, unsupported, or mismatched ability-schema evidence fails closed. Missing attestation must surface as `NOT_FOUND`, and unreadable attestation schema must surface as `SCHEMA_VERSION_UNSUPPORTED`. +- `GetPublishedReleaseBundle(GetPublishedReleaseBundleRequest) returns (GetPublishedReleaseBundleResponse)` – **Target response:** returns the immutable `(tenantId, versionId)` release attestation including participant digests, the dedicated Game Logic-owned `abilitySchemaDigest` for the same target commit (using Game Logic's existing participant `digestSchemaVersion` and canonicalization evidence), any required `artifactDigests[]` and `requiredManifestAssetKeys[]` for exported derived assets, `manifestHash`, `generationConfigRevision`, and the canonical publish workflow runtime metadata (`publishWorkflowId`, `workflowRunId`, `workflowStatus`). **Current candidate response/compatibility path:** `ParticipantDigest.ability_schema_digest` carries the Game Logic-owned value in its existing immutable participant record; plugin validation reads that exact record rather than Automation's aggregate. Legacy records retain absent evidence. This carrier and rejection path do not establish the normal Game Logic source producer or a complete launch attestation. Missing, unsupported, or mismatched ability-schema evidence fails closed. Missing attestation must surface as `NOT_FOUND`, and unreadable attestation schema must surface as `SCHEMA_VERSION_UNSUPPORTED`. + New ordinary-asset publication carries the stored optional `manifestSchemaVersion` and ordered `artifactDigests[]`; retained rows without that evidence remain explicitly incomplete, not a proved empty manifest. The producer and actual-byte proof contract belongs to [Asset Storage](asset-storage.md#asset-lifecycle-and-publish-workflow); these fields do not establish the missing dedicated ability-schema or complete derived-artifact evidence. - `ResolveLaunchDescriptor(ResolveLaunchDescriptorRequest) returns (ResolveLaunchDescriptorResponse)` – resolves template metadata and control-plane inputs into one immutable launch descriptor for a game-instance creation attempt. Missing attestation must surface as `RELEASE_BUNDLE_NOT_FOUND`, unsupported attestation schema as `SCHEMA_VERSION_UNSUPPORTED`, and cross-version replacement launches without exactly one approved persisted remap set for the source/target pair as `LAUNCH_REMAP_REQUIRED`. - `CreateTemplateRemapSet(CreateTemplateRemapSetRequest) returns (CreateTemplateRemapSetResponse)` – persists a draft remap set for a concrete `(tenantId, sourceVersionId, targetVersionId)` pair. @@ -241,10 +242,10 @@ Detailed request and response schemas are defined in the [OpenAPI specification] - `GetTemplateRemapSet(GetTemplateRemapSetRequest) returns (GetTemplateRemapSetResponse)` – returns the canonical remap-set payload and approval state for an existing `remapSetId`. - `GetVersionAssetArtifactState(GetVersionAssetArtifactStateRequest) returns (GetVersionAssetArtifactStateResponse)` – live authoritative lifecycle/proof read for the persisted artifact row; target complete frozen proof and scoped read authorization remain incomplete. - `AbandonFailedVersionAssets` / `GetFailedVersionAssetAbandonment` – **Target state only; no current proto RPC:** illustrative owner-local operation/read names for the durable failed-candidate abandonment proof described by [Asset Storage](asset-storage.md#api). -- `TombstoneVersionAssets(TombstoneVersionAssetsRequest) returns (TombstoneVersionAssetsResponse)` – live pre-tombstone endpoint with current support limited to `FAILED` and `PURGE_FAILED`; target retirement/abandonment authority checks and database CAS are not implemented. +- `TombstoneVersionAssets(TombstoneVersionAssetsRequest) returns (TombstoneVersionAssetsResponse)` – live pre-tombstone endpoint with current support limited to `FAILED` and `PURGE_FAILED`; artifact saves use epoch CAS, but complete retirement/abandonment authority and global reachability checks remain unimplemented. - `CanDeleteVersionAssets(CanDeleteVersionAssetsRequest) returns (CanDeleteVersionAssetsResponse)` – validates whether version-scoped assets are purge-eligible. -- `BeginPurgeVersionAssets(BeginPurgeVersionAssetsRequest) returns (BeginPurgeVersionAssetsResponse)` – **Target state:** CAS-guarded purge start that atomically re-checks deletion eligibility and transitions `version_asset_artifact` into purge-in-progress state; the current implementation lacks database CAS and mints a random workflow identity. -- `FinalizePurgeVersionAssets(FinalizePurgeVersionAssetsRequest) returns (FinalizePurgeVersionAssetsResponse)` – **Target state:** CAS-guarded purge completion that transitions purge-in-progress artifacts to `PURGED` after byte-deletion confirmation; the current implementation lacks database CAS and the shared operation ledger. +- `BeginPurgeVersionAssets(BeginPurgeVersionAssetsRequest) returns (BeginPurgeVersionAssetsResponse)` – **Target state:** fenced purge start that atomically re-checks complete eligibility and transitions the artifact into purge-in-progress state. Current artifact saves use epoch CAS, but global reachability/Version fencing remains incomplete and the endpoint still mints a random workflow identity. +- `FinalizePurgeVersionAssets(FinalizePurgeVersionAssetsRequest) returns (FinalizePurgeVersionAssetsResponse)` – **Target state:** fenced purge completion after exact authorized byte-deletion confirmation. Current physical deletion is denied pending complete [asset lifecycle authority](asset-storage.md#asset-lifecycle-and-publish-workflow); artifact CAS does not supply the missing shared operation ledger or global purge proof. - `GetVersionAssetPurgeStatus(GetVersionAssetPurgeStatusRequest) returns (GetVersionAssetPurgeStatusResponse)` – live operator-visible read of in-flight or failed purge workflow status; the target operation-ledger replay and reconciliation boundary remains incomplete. - `RepairPublishedVersionAssets(RepairPublishedVersionAssetsRequest) returns (RepairPublishedVersionAssetsResponse)` – live exact-bytes repair endpoint; target durable snapshot/readback and pre-write attestation proof are not implemented, and current repair can write version-prefix objects before mismatch detection. diff --git a/design/architecture/microservices/game-design-service/asset-storage.md b/design/architecture/microservices/game-design-service/asset-storage.md index 5ab0aa0821..2e8ba1f726 100644 --- a/design/architecture/microservices/game-design-service/asset-storage.md +++ b/design/architecture/microservices/game-design-service/asset-storage.md @@ -6,22 +6,21 @@ Target runtime architecture uses an approved public `/assets/**` origin as the b ## Implementation Status -- **Current first slice:** Ordinary uploaded bytes are persisted in `game_assets.data`, which is the retained repair source selected by the process-local snapshot for Published/Active binary assets. This source is not database-enforced immutable: the repository can update `data` for an existing row, even though no current REST update route is exposed. Publication currently exports the bytes to version-scoped object storage and exposes the numeric `GameAssetDto.id`; the target private-candidate/content-addressed publication and opaque logical asset identifier are not live. +- **Ordinary-byte producer boundary:** Owner-local Draft mappings and durable per-version snapshots select actual `game_assets.data` bytes; database guards retain referenced source identity, filename, content type and bytes. The exporter records and independently reads the complete candidate before conditional content-addressed writes and exact byte readback. This is bounded producer implementation, not authenticated creator ingress, derived-artifact completeness, public delivery or runtime activation. Detailed capability and proof status belongs to the [publishing tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md). - **Current upload admission gap:** The target upload guardrails (25 MiB maximum file size, 2 GiB per-tenant draft quota, and streaming/chunked transfer) are requirements, not current proof. `AssetController` accepts multipart uploads and `GameAssetServiceImpl` calls `MultipartFile.getBytes()` without size or quota enforcement; `AssetStoreProperties` has no matching limits. Upload admission and resource-safety readiness therefore remain incomplete and the route must not be treated as ready for external enablement. - **Hosted-content gate gap:** Current asset upload and publish paths do not evaluate Account currentness or persist a tenant/evidence binding. The target gate also applies to Draft asset writes and changed-term stale acceptance; no current route, schema, storage, UI/status, or focused proof implements it. The Gateway's explicit read-only Game Design routes do not forward `/api/design/assets` to the live `POST /assets` controller, whose service-local boundary still checks only privileged JWT/tenant access. Official-hosted asset-upload readiness remains blocked until the exact Account-owned gate is implemented and proved; edge containment is not the owner-side gate. -- **Current lifecycle proof:** `version_asset_artifact` records the exported version-number prefix and manifest asset keys, but it does not yet freeze the target exact immutable object-key/digest set or implement the target global publication/purge fence. Repair writes those live prefix objects and the manifest before its exact release-bundle comparison, so pre-write verification is target-only. -- **Current lifecycle concurrency gap:** `stateEpoch` comparisons and increments currently occur in service memory, while both `VersionAssetArtifactRepository` and `VersionRepository` update rows by `id` without an epoch predicate or affected-row check. `VersionService.compareAndSetVersionState` therefore has the same gap as artifact lifecycle writes: the live path lacks a database CAS fence for both artifact and Version lifecycle state. The target `expectedVersionStateEpoch` proof for abandonment, retirement, and reachability invalidation is blocked until both saves use a durable predicate/lock and prove the affected row. +- **Candidate and lifecycle proof:** `version_asset_artifact` retains immutable manifest/schema, complete artifact and manifest object-key/digest evidence tied to the durable snapshot. Artifact updates use tenant/version-qualified epoch CAS and checked affected-row counts. Snapshot and candidate retries read the same committed evidence; they do not rebuild ownership from listings. The global publication/reachability/purge fence and Version lifecycle CAS remain incomplete; candidate persistence does not establish those authorities. - **Current destructive-operation idempotency gap:** The target destructive lifecycle operations do not yet share an ADR 0048 operation envelope or owner-local durable result ledger. Tombstone/finalize/repair accept workflow identifiers without a canonical request digest and exact replay/conflict contract, while live `BeginPurgeVersionAssets` generates a random workflow ID server-side. A lost response can therefore not reliably replay the same result; this remains target-only. -- **Current purge finalization:** Live `FinalizePurgeVersionAssets` selects and deletes the frozen version-scoped prefix from `exported_version_number`. This current-only behavior cannot be used as the target content-addressed/shared-object finalization path, which instead operates on frozen object-key/digest proofs under the publication/refcount fence below. +- **Current purge finalization:** The exporter denies physical deletion with `CONTENT_ADDRESSED_PURGE_PROOF_REQUIRED`. An exported version number or listing cannot authorize deletion of shared content-addressed objects. Target finalization requires frozen object-key/digest proofs and the publication/refcount fence below; it is not enabled by this producer. - **Current purge failure durability gap:** `FinalizePurgeVersionAssets` catches a runtime deletion/finalization failure, saves `PURGE_FAILED`/failed-workflow state, and rethrows from its `@Transactional` method. Those status writes can roll back with the transaction, while object-store deletion may already have succeeded, leaving durable `PURGE_IN_PROGRESS` with no resumable failure evidence. Target recovery requires an independent durable failure/reconciliation boundary (or equivalent non-rollback record) and focused proof for deletion and post-delete database-save failures. - **Version-level purge boundary:** Target `FinalizePurgeVersionAssets` deletes only the frozen version-artifact objects authorized by the purge proof; it never removes `game_assets` source rows or their `game_assets.data` bytes. - **Current tombstone gap:** Live `VersionAssetArtifactServiceImpl.tombstoneVersionAssets` accepts only `FAILED` and `PURGE_FAILED`; it does not yet support the target `PUBLISHED -> TOMBSTONED` transition for an eligible retired release. Current runbooks must expose that gap and fail closed rather than claim the retired-release path is live. - **Current failed-candidate abandonment gap:** The target durable abandonment proof record and owner-local abandonment operation/read are not implemented. The live tombstone path checks only artifact state and epoch, so it does not enforce the required abandonment, caller-tenant `FAILED` authority, or no-release-reachability proof; no current implementation or focused proof claim is made for this path. - **Current purge eligibility gap:** `CanDeleteVersionAssets` rejects a non-retired version when a tenant-matching version row exists, but its `findById(versionId).filter(tenant match)` lookup treats a row owned by another tenant as absent. When no caller-tenant release bundle remains, either no row or only a wrong-tenant row can therefore fall through to `deletable=true`; this is fail-open drift for dangling artifact rows. Target eligibility must require an existing caller-tenant version authority in `RETIRED` state and fail closed for both absence and tenant mismatch. -- **Current release attestation:** The current `GetPublishedReleaseBundle` response and `published_release_bundle` row preserve `manifestHash` and narrower current attestation fields, but do not provide the complete target mandatory actual-byte `artifactDigests[]`; consumers must not synthesize absent target fields, and target-dependent admission remains unproved and blocked. -- **Current publish-failure gap:** `VersionPublishCommandServiceImpl` catches downstream exceptions after `published_release_bundle` may already have been written, then unconditionally calls `markFailed`, performs best-effort object cleanup, and deletes the version without an exact attestation readback/reconciliation branch. Because `published_release_bundle.version_id` is a non-cascading foreign key, that delete can itself fail after bundle commit; the current path therefore has neither a truthful `FAILED` result nor guaranteed reconciliation to `PUBLISHED`/nonterminal state. Target recovery must read back committed bundle state and never delete Version as compensation. This is implementation/proof drift against the transition rules below and must not be advertised as target terminality. -- **Current delivery gap:** `AssetExportServiceImpl` currently constructs generated manifest URLs from the private `ASSET_STORE_ENDPOINT` plus bucket/key, while `AssetController` exposes only `POST /assets`. No client GET/download route, gateway rewrite, signed-fetch, or `ASSET_STORE_PUBLIC_BASE_URL` path is implemented; these generated URLs are private storage references and must not be exposed as usable client manifests. Canonical `/assets/**` delivery remains target-only pending a separate approved public origin/provisioner; the current Gateway has no `/assets/**` route and private MinIO is not public delivery. -- **Identifier drift:** `game_assets.tenant_id` accepts a REST `tenantId` string without UUID-shape enforcement while Account Service still exposes numeric `Long` tenant identifiers. No authoritative numeric-to-UUID mapping exists, and the public asset row key is a `BIGSERIAL`; none of these numeric values is a canonical logical identity. +- **Current release attestation:** Newly constructed ordinary-asset bundles retain `manifestSchemaVersion` and exact `artifactDigests[]` in storage and readback. Retained incomplete rows remain explicitly without this evidence; absence is not a proved empty manifest. Full owner-provided derived-artifact, ability-schema and authenticated release/descriptor proof remains incomplete, and consumers must not synthesize it. +- **Publication recovery boundary:** `VersionPublishCommandServiceImpl` commits and independently reads the staged intent before export. An uncertain export outcome, including a later object conflict, remains `PENDING` for exact candidate/write reconciliation. Finalization recovery compares the committed bundle and complete ordinary-asset candidate; only proved rollback with no release may record failure. Neither branch deletes the retained Version or compensates by deleting shared content-addressed bytes. This boundary does not close the remaining authenticated participant, creator, full-release or abandonment proof gaps. +- **Current delivery gap:** Export requires an explicitly configured HTTPS `asset.store.public-base-url` ending at `/assets`, rejects private endpoint aliases, and never generates public locations from `ASSET_STORE_ENDPOINT`. This check does not authenticate or provision an approved origin. `AssetController` still exposes only `POST /assets`; no client GET/download or Gateway `/assets/**` rewrite is enabled. Missing origin/readiness proof remains an activation gate; private MinIO is not public delivery. +- **Asset identifier drift:** `game_assets.tenant_id` still accepts a REST `tenantId` string and the public asset row key is a `BIGSERIAL`. The owner-local export now qualifies its Version through Game Design's canonical tenant/Version provenance, but that does not migrate the public asset API or authorize an association by numeric equality. Account's separately proved identity associations are not an asset mapping authority; private numeric keys must not become canonical logical identities. - **Target convergence:** Account and downstream contracts migrate together to the opaque UUID tenant identity, and the public asset contract and `GameAssetDto.id` converge directly on an opaque UUID logical asset identifier while any numeric database key remains private. The numeric public field is removed rather than retained through compatibility translation; implementations must not invent a reversible numeric-to-UUID encoding. Draft bytes may move out of PostgreSQL only after an equivalent immutable repair source exists. Logical world and entity templates (regions, rooms, items, NPCs, loot tables, scripts, etc.) remain stored in PostgreSQL schemas owned by the corresponding domain services and are not persisted as blobs in the asset store. The asset store is strictly for binary design assets plus version-scoped manifests exported by the Game Design Service. @@ -243,12 +242,12 @@ The `game_assets` table stores ordinary design-time upload records. In the curre - `tenant_id` – **target:** identifies the owning game using the canonical UUID `tenantId`; **current:** stores an unconstrained `VARCHAR(36)` string while the UUID migration and validation remain incomplete - `file_name` – original file name - `content_type` – MIME type -- `data` – uploaded bytes for the ordinary binary asset in the current first slice; they are retained as the repair source for object-store republish/repair by current convention, not protected by a database immutability constraint (the repository can update an existing row). A future metadata-only storage model must introduce an equivalent retained immutable source before removing this source. +- `data` – retained ordinary binary source bytes. Frozen snapshot references prevent changes to the source identity, name, type or bytes and prevent deletion. A future metadata-only model must introduce equivalent immutable retained repair evidence before removing this source. - `created_at` – upload timestamp Future metadata-only storage may replace `data` with fields such as `storage_key`, `content_hash`, and `size_bytes`, but only if the new schema preserves the same repair invariant: Published/Active releases must be exactly reproducible for as long as their assets remain non-Retired or design-history reachable. -To associate assets with specific published versions while still allowing reuse across versions, the target Game Design contract requires a separate mapping table. The current implementation has neither this table nor a Draft-version authoring path for its mappings; the following shape and constraints are target-state until both exist: +Version-scoped ordinary-asset selection uses the owner-local mapping table below. Its Draft writer verifies exact canonical Version provenance and same-tenant source assets. An authenticated public creator mapping surface remains required work; private owner-row identifiers are not external identity. - `version_asset`: - `tenant_id` – owning game @@ -307,10 +306,9 @@ immutable durable per-version export snapshot. The target shape is a with the selected `asset_id`, source-row identity, and computed source `content_hash` (plus size/type metadata when needed for verification). Same-version retries and exact-bytes repair must use this snapshot, never re-select the current tenant asset -list or mutable draft mappings. This durable projection is deferred target -convergence and is not implemented by the current first slice. +list or mutable draft mappings. The durable header proves the complete selection, including a genuinely empty set; a missing header is unavailable evidence, not an empty selection. The ordinary-byte producer implements this owner-local projection; the publishing tracker records executed and outstanding proof. -`(tenant_id, version_id)` is unique in `version_asset_artifact`. This enum list is the canonical schema contract for both persistence and API validation. Target lifecycle transitions must use compare-and-set on `state_epoch` so concurrent publish/repair/purge workflows cannot race; the current implementation's in-memory check followed by an unconditional row-ID update is documented in the implementation-status and lifecycle sections below. +`(tenant_id, version_id)` is unique in `version_asset_artifact`. This enum list is the canonical schema contract for persistence and API validation. Artifact transitions use checked tenant/version/epoch CAS. This does not complete the separate Version lifecycle and global publication/purge fence. An index named `idx_game_assets_tenant` speeds up queries scoped to a tenant. Additional indexes may support common design-time queries (for example by @@ -345,18 +343,18 @@ Implementation notes: - `GetVersionAssetArtifactState`, `RepairPublishedVersionAssets`, `TombstoneVersionAssets`, `CanDeleteVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `GetVersionAssetPurgeStatus` are now live in `game-design-service`. - `version_asset_artifact` is now a persisted control-plane row and full-version publish updates it through `EXPORTED_UNATTESTED` and `PUBLISHED`. -- the persisted artifact row now stores the exact exported version number plus manifest asset keys for current completed-export cleanup/prefix deletion; it does not yet provide the durable frozen source-row/content proof or immutable object-key/digest proof required for exact repair or target content-addressed purge. The current first slice therefore keeps Published/Active repair unavailable after process loss and uses only its current version-prefix cleanup path; a failed write before `ExportAssets` returns still has no durable key proof and remains an implementation gap. See the lifecycle and repair/purge sections below for the target proof boundary. +- The persisted artifact row freezes complete candidate object proof before external writes. Durable snapshot readback supports exact ordinary-byte reproduction after process loss; incomplete retained rows remain unavailable. Shared-object purge remains denied until independent authority/reachability proof exists. See the lifecycle and repair/purge sections below. - `CanDeleteVersionAssets` now also fails closed on live launch-descriptor references and on approved template remap sets that still name the source or target version, so purge cannot silently remove bytes still needed by current launch and replacement-cutover control-plane truth. - `version_asset_purge_workflow` is now the retained workflow-status surface for purge start/finalization outcomes. A basic repository (`GameAssetRepository`) and service implementation (`GameAssetServiceImpl`) persist uploads through the service-local jOOQ/PostgreSQL data boundary. -At publish time, the current implementation reads asset bytes from `game_assets.data`, freezes a process-local selection for the version, revalidates that the version has not become Published/Active immediately before caching the snapshot, and exports those bytes into version-scoped published prefixes in object storage, referencing them in the generated `manifest.json`. This direct prefix export is implementation drift; target convergence builds and verifies a private candidate with mandatory actual-byte digests, then exposes immutable content-addressed objects through the [Asset Lifecycle and Publish Workflow](#asset-lifecycle-and-publish-workflow). Duplicate file-name usage keys and the reserved `manifest.json` key fail closed before any object-store write. The process-local snapshot cache is bounded by `asset.store.frozen-snapshot-cache-max-entries` (default `256`); a new uncached version scope fails closed with `EXPORT_SNAPSHOT_CAPACITY` at capacity rather than evicting retry evidence. Target runtime clients load branding and theme resources directly from the approved public `/assets/**` origin using the manifest; that origin may be backed by a CDN, but a CDN is not required. The Game Design Service is not involved in byte delivery, but its `GetPublishedReleaseBundle` response and attested `manifestHash` remain the control-plane authority. In the current first slice, generated manifest URLs use the private `ASSET_STORE_ENDPOINT` and are not client-facing or usable by runtime clients; delivery remains blocked pending a separate approved public origin/provisioner for canonical `/assets/**`, and private MinIO is not public delivery. A future metadata-only storage model may use retained immutable object-store draft keys, but those keys are target-only and are not the current upload or repair source. See [Game Design Service Architecture](README.md) for how these assets fit into published versions. +At publish time, the owner locks the canonical Draft Version, freezes its mappings and actual-byte proofs durably, and independently reads them before constructing the candidate. Duplicate file-name usage keys, invalid text and the reserved `manifest.json` key fail closed before object-store writes. Complete manifest/object proof is recorded and independently read from the lifecycle row before conditional content-addressed writes; every successful or lost-acknowledgement write requires exact byte/type/length readback. Unresolved writes remain outcome-pending, not permission to delete or remint. No process-local cache is recovery authority. Configured HTTPS `/assets` URLs remain delivery locations pending approved origin/provisioning/readiness proof; private MinIO and object existence establish neither release nor public-delivery authority. See [Game Design Service Architecture](README.md) and the [publishing tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md). -The current repair ordering is not the target pre-write safety rule: `AssetExportServiceImpl` writes each version-prefix object and then `manifest.json`; only after that export returns does `VersionAssetArtifactServiceImpl` compare the resulting hash/key set with the published release bundle. A repair mismatch can therefore write or overwrite live prefix keys before it fails with `REPAIR_ATTESTATION_MISMATCH`. Target repair must build and verify away from published keys before any live write; this target rule is not current implementation proof. +Ordinary-byte retries and repair compare the complete candidate against its immutable durable evidence before conditional writes and exact readback. They cannot overwrite a published content key or reinterpret absent retained proof as an empty set. Full release repair still requires all applicable owner-source and release evidence; shared-object purge remains separately gated. -The target export boundary persists the artifact `STAGED` intent and its deterministic candidate prefix/manifest evidence before the first object-store write, records each written key (or an equivalent immutable candidate manifest) durably, and uses idempotent content-addressed writes and deletes. A durable cleanup retry/outbox reconciles partial candidates; an object-store timeout or lost response remains nonterminal until exact key/content readback proves the candidate state. Only the owner-local artifact and release-attestation commit can make bytes launchable, and a storage listing cannot substitute for that authority. The current first slice does not yet satisfy this pre-write intent or ambiguous-export recovery boundary. +The export boundary persists the artifact `STAGED` intent and complete immutable candidate manifest/object evidence before the first object-store write. Conditional content-addressed writes require exact byte readback; an object-store timeout or lost response remains nonterminal until that proof resolves the outcome. Only the owner-local artifact and complete release-attestation commit can make bytes launchable, and a storage listing cannot substitute for that authority. The ordinary-byte producer implements intent/candidate storage and readback; the separate owner-controlled reachability/abandonment and cleanup workflow remains incomplete. In the target contract, the `published_release_bundle` attestation must reference the final asset state for the version by including `manifestHash` and mandatory actual-byte `artifactDigests[]` entries exposed through Game Design’s `GetPublishedReleaseBundle` API. Activation, cutover preflight, and repair tooling must consume the API instead of reconstructing asset state from `version_asset_artifact` and version metadata separately. @@ -364,7 +362,7 @@ In the target contract, the `published_release_bundle` attestation must referenc ### Interaction with Script-Only Patches -Script-only patches (see `system-architecture-versioning-runtime.md`) do not change assets or any data stored in `game_assets` / `version_asset`. In the target contract, published asset selection is bound to `(tenantId, versionId)` and exported during full `PublishVersion` flows. The current first slice does not yet persist that binding: `AssetExportServiceImpl` initially selects every tenant asset, freezes the selection only in process-local memory, and has no `version_asset` authoring path. A same-runtime rerun reuses the frozen selection; a Published/Active retry fails with `REPAIR_VERSION_SCOPE_UNAVAILABLE` when that selection is unavailable instead of reselecting the tenant-wide list. Asset changes therefore belong in a new `versionId` in the target state, while the current tenant-wide selection remains an implementation gap to be corrected before persisted version-bound export can be treated as proven. +Script-only patches (see `system-architecture-versioning-runtime.md`) do not change assets or data stored in `game_assets` / `version_asset`. Ordinary full-version publication selects only its exact owner-qualified mappings. Retries and repair read the durable snapshot rather than the current tenant asset list. Missing snapshot proof is denied; changed bytes or mappings require a new Version, with no process-local fallback. ### Asset Lifecycle and Publish Workflow @@ -376,7 +374,7 @@ The target publication topology follows [ADR 0095](../../decisions/adr-0095-cont - Every binary and derived artifact is hashed from its actual bytes with mandatory SHA-256. The attested manifest records a stable usage key, immutable content-addressed object key, digest, content type/schema, and delivery location; URLs, names, and byte lengths are not byte attestation. - Candidate bytes and manifests are built and verified in a private staging or quarantine namespace. Public manifest and object keys are immutable and content-addressed, and no candidate becomes a runtime discovery surface before the complete release attestation succeeds. - Retrying the same verified bytes is idempotent. Changed bytes require a new content key and, for an attested release, a new version; a retry or repair never overwrites a live key with an unverified candidate. -- Target state: `version_asset_artifact` and Version lifecycle state/epoch remain the lifecycle authorities. Storage listings, object existence, and CDN responses are delivery evidence only and cannot establish launch, retirement, or purge eligibility. Current artifact and Version state-epoch checks are in-memory followed by unconditional repository updates by row ID; neither target database CAS/atomic-lock behavior is live. Until both saves use an epoch predicate/lock and affected-row proof, an `expectedVersionStateEpoch` or artifact epoch cannot prove that abandonment, retirement, or reachability evidence remained valid. +- `version_asset_artifact` and Version lifecycle state/epoch remain the lifecycle authorities. Storage listings, object existence, and CDN responses are delivery evidence only and cannot establish launch, retirement, or purge eligibility. Artifact saves use checked tenant/version epoch CAS; incomplete Version lifecycle CAS and global reachability/fence proof still block target abandonment, retirement and physical purge. Artifact lifecycle states for a `(tenantId, versionId)` prefix are explicit: @@ -385,7 +383,7 @@ Artifact lifecycle states for a `(tenantId, versionId)` prefix are explicit: - `PUBLISHED` – publish succeeded, `manifestHash` is attested in `published_release_bundle`, and the immutable bytes for the version are launchable. - `FAILED` – publish workflow failed for this version. - `TOMBSTONED` – an eligible retired `PUBLISHED` release or an abandoned `FAILED` artifact is quarantined for diagnostics and excluded from activation paths. -- Target `PURGE_IN_PROGRESS` – the purge workflow has atomically locked this prefix for deletion and is removing object-store bytes. The current implementation has no database lifecycle-row lock/CAS proving that lock. +- Target `PURGE_IN_PROGRESS` – the purge workflow has atomically fenced the exact frozen keys for deletion. The current artifact row CAS does not establish the complete global reachability/purge fence, and physical deletion remains denied. - `PURGE_FAILED` – purge workflow encountered a deletion/finalization failure; bytes may be partially deleted and require explicit operator retry/resume workflow. Allowed transitions: @@ -411,23 +409,22 @@ Allowed transitions: Transition enforcement contract: -- Target behavior: every artifact transition is persisted by updating `version_asset_artifact` with CAS on `state_epoch`, and every Version transition uses the corresponding Version epoch CAS; a failed CAS means another workflow already changed state and callers must reload current state and re-evaluate. The current repositories do not implement those predicates or affected-row checks. +- Every artifact transition is persisted with checked `state_epoch` CAS; a failed CAS means another workflow changed state and callers must reload and re-evaluate. Every Version transition must use its corresponding owner fence as well; artifact CAS alone is not Version lifecycle or reachability proof. - The durable publish workflow and operator runbooks must both use this same state record; object-store state is never treated as authoritative by itself. - `PUBLISHED` is the only success state that may be treated as launchable. Object-store bytes in `STAGED` or `EXPORTED_UNATTESTED` are not publish-complete on their own. - For each `(tenantId, versionId)` the durable publish workflow runs an `ExportAssets` step that: - - **Current implementation:** initially selects every `game_assets` row for `tenantId` through `GameAssetRepository.findByTenantId`, including assets with no `version_asset` mapping, and reads the export bytes from `game_assets.data`. It freezes that selection in process-local memory before writing bytes. The `version_asset` table and a Draft-version authoring action that creates or removes those mappings are not implemented yet. - - **Target convergence:** freezes a persisted selection from `version_asset` joined to `game_assets` for the target `(tenantId, versionId)`; unmapped tenant assets are excluded from that version's export. The candidate is built privately, every selected byte is SHA-256 hashed, and the verified manifest and objects receive immutable content-addressed keys before public delivery. + - Freezes the exact owner-qualified `version_asset`/`game_assets` selection durably; unmapped tenant assets are excluded. The candidate is built privately, actual bytes are SHA-256 hashed, and complete immutable candidate proof is committed/read back before external writes. This does not enable public delivery. - Copies the selected ordinary asset bytes from `game_assets.data` (or a future equivalent immutable repair source) into private candidate storage, verifies the complete candidate, and only then publishes immutable content-addressed objects. A tenant/version prefix may remain a delivery grouping, but it is not the object identity or lifecycle authority. - Writes the version-scoped `manifest.json` as a content-addressed immutable object after candidate verification; it must not overwrite an attested manifest key. - Updates version metadata with the manifest location. - Transitions `version_asset_artifact` from `STAGED` to `EXPORTED_UNATTESTED`. - - **Target-only validation:** once `version_asset` authoring exists, fails the workflow step if any asset referenced in `version_asset` for the target `(tenantId, versionId)` is missing, so partially published versions cannot be marked as Published. The current implementation cannot perform this validation because the mapping table and authoring path do not exist. + - Rejects missing or inconsistent mapped sources; composite foreign keys and owner readback bind each exact asset to its tenant and Version. Missing snapshot evidence is not permission to select the current tenant list. - **Target-state retry behavior:** Once the frozen export snapshot exists, rerunning `ExportAssets` for the same `(tenantId, versionId)` reuses that snapshot, recomputes and verifies the same content-addressed bytes, and leaves the version metadata consistent. It must not re-select assets after the snapshot is frozen, and it must not overwrite an attested public key. Changed bytes require a new key and release version. -- **Current implementation boundary:** `AssetExportServiceImpl` freezes a process-local version-scoped snapshot and reuses it for same-runtime reruns, but it does not persist `version_asset_export_item` evidence. A Published/Active retry reuses that frozen snapshot when it is still available and fails closed with `REPAIR_VERSION_SCOPE_UNAVAILABLE` when it is absent, rather than calling `GameAssetRepository.findByTenantId` again. After process loss, exact repair therefore remains unavailable until the target persisted snapshot exists. **Current drift:** if the Version row is now `RETIRED`, the live resolver can instead take a fresh tenant-wide `findByTenantId` snapshot after process loss because only `PUBLISHED`/`ACTIVE` fail closed; that selection is not exact repair proof and operators must treat the path as fail-closed until the target durable snapshot exists. +- **Ordinary-byte implementation boundary:** Retry and repair reuse the persisted source snapshot and exact recorded candidate across process loss. An absent snapshot or incomplete retained candidate is unavailable, including for Retired Versions; no lifecycle state permits tenant-wide reselection or synthesized empty evidence. - A later `FinalizePublishedRelease` step must read the computed `manifestHash`, write `published_release_bundle`, and only then transition `version_asset_artifact` from `EXPORTED_UNATTESTED` to `PUBLISHED`. If the attestation write has a lost or ambiguous response, the artifact remains `EXPORTED_UNATTESTED` and reconciliation-required; it may move to `FAILED` only after exact readback proves that no `published_release_bundle` exists for the tenant/version at all and no unresolved attestation write or cleanup ambiguity remains. Any existing row, including a mismatched attestation, keeps the artifact nonterminal until owner reconciliation determines the outcome; a matching committed attestation permits reconciliation to `PUBLISHED` and never `FAILED`. Implementations must not expose launchable `PUBLISHED` assets without a matching release attestation. - The `EXPORTED_UNATTESTED` readback and any transition to `FAILED` must be serialized against concurrent publication for the same `(tenantId, versionId)`. The owner transaction (or one shared lifecycle CAS/lock fence held across the readback and state transition) must lock or compare the artifact row and exact `published_release_bundle` identity together, re-read the bundle immediately before deciding `FAILED`, and reject a stale state epoch. A matching bundle that committed before or during the readback reconciles the artifact to `PUBLISHED`; a missing bundle can transition to `FAILED` only when the same fenced readback proves no publication committed and no external write remains ambiguous. A later failure must never demote a matching publication or delete its version/assets. -- Current implementation drift is sharper than the target rule: after bundle creation, the publish catch path still marks failure, performs best-effort cleanup, and calls `VersionRepository.delete`. Since `published_release_bundle.version_id` is a non-cascading foreign key, that compensation delete can fail after a committed bundle. Target recovery must reconcile bundle/readback evidence and must never delete Version to compensate for an ambiguous post-bundle failure; focused proof must cover committed-bundle, missing-bundle, and lost-response branches. +- Current publication recovery retains the Version and candidate evidence and reconciles complete bundle readback; uncertain export and finalization remain nonterminal. Focused proof must distinguish committed-bundle, proved rollback/no-bundle, incomplete or mismatched proof, and lost-response branches. Ordinary-byte evidence does not establish the remaining complete owner-derived release or activation boundary. - Once a version is in the **Published** or **Active** state, immutability rules apply: - `version_asset` rows for `(tenantId, versionId)` must be treated as immutable mappings. - Referenced `game_assets` binaries must not be modified in place; replacing bytes requires a new `game_assets` row and (for Draft versions only) an updated mapping. @@ -449,10 +446,10 @@ Transition enforcement contract: Exact-bytes repair rule: - Repair of a Published/Active version must begin by reading `GetPublishedReleaseBundle(tenantId, versionId)`. -- **Target state:** Repair must also read `GetVersionAssetArtifactState(tenantId, versionId)` and prove the expected `artifactState`, `stateEpoch`, and `manifestHash` before any bytes are rewritten. **Current implementation:** the export invoked by repair writes version-prefix objects and `manifest.json` before `VersionAssetArtifactServiceImpl` performs the exact repair-match comparison, so a mismatch can mutate live prefix keys before returning `REPAIR_ATTESTATION_MISMATCH`. +- Repair must also read `GetVersionAssetArtifactState(tenantId, versionId)` and prove expected state, epoch and manifest hash before byte writes. The ordinary producer checks the recorded complete candidate before conditional content-addressed writes; that is not a substitute for the complete published release and owner-source checks. - Repair must materialize candidate bytes away from published keys and verify every attested object and manifest digest before writing any missing immutable object. It may restore only exact attested content-addressed objects; if a repair source or digest is unavailable, it fails closed and requires a new version. -- Repair must read and verify the immutable per-version export snapshot, including every exported source-row ID and content hash. In the current implementation, the process-local frozen selection is the only available snapshot evidence; if it is absent because the service restarted or the version was exported without that evidence, Published/Active repair must fail closed with `REPAIR_VERSION_SCOPE_UNAVAILABLE` rather than guessing from current draft assets. Recovery then requires publishing a new `versionId` until the target persisted snapshot exists. -- Once version-scoped selection and its frozen snapshot exist, the repair workflow may regenerate ordinary object-store bytes from the retained `game_assets.data` rows recorded by that snapshot. The current repository does not enforce those rows as immutable and can update `data` by ID; target publication must replace bytes with a new source row or otherwise provide a retained immutable repair source before a Published/Active release relies on it. +- Repair reads and verifies the durable per-version snapshot, every exported source-row identity and content digest. Missing retained snapshot proof fails closed rather than guessing from current Draft assets; publishing a new Version is required if the attested bytes cannot be reproduced. +- Ordinary repair may regenerate only the exact retained `game_assets.data` bytes recorded by that snapshot. Database guards retain referenced identity, filename, content type and bytes; replacing content requires a new source row and new Version mapping. - If a future storage model replaces `game_assets.data` with metadata plus object-store handles, the replacement repair source must be immutable and retained for every non-Retired or design-history-reachable release. A mutable draft object key by itself is not a valid repair source. - The repair workflow may only regenerate object-store bytes that reproduce the existing attested `manifestHash` and every mandatory actual-byte digest in `artifactDigests[]`. - If regenerated bytes would change the attestation payload, the workflow must fail closed and require a new `versionId` rather than mutating the published release in place. @@ -462,7 +459,8 @@ Required deterministic repair/purge failure vocabulary: - `VERSION_ASSET_NOT_DELETABLE` when `CanDeleteVersionAssets` rejects eligibility. - `ASSET_ARTIFACT_STATE_CONFLICT` when `state_epoch` CAS fails or the lifecycle row no longer matches the caller's proof. - `ASSET_USAGE_KEY_COLLISION` when duplicate file-name-derived manifest keys or the reserved `manifest.json` key make the export ambiguous. -- `EXPORT_SNAPSHOT_CAPACITY` when the bounded process-local snapshot cache cannot admit a new version scope without evicting retry evidence. +- `ASSET_EXPORT_CANDIDATE_CONFLICT` when the proposed manifest or artifact evidence differs from its immutable recorded candidate. +- `CONTENT_ADDRESSED_PURGE_PROOF_REQUIRED` when shared-object deletion lacks its complete reachability and purge authority. - `REPAIR_VERSION_SCOPE_UNAVAILABLE` when a Published/Active release lacks the frozen version-scoped export snapshot required for exact repair. - `REPAIR_ATTESTATION_MISMATCH` when repair cannot reproduce the attested `manifestHash`. - `PURGE_WORKFLOW_NOT_FOUND` when status or finalization reads reference an unknown `purgeWorkflowId`. @@ -493,7 +491,7 @@ For a published/release artifact, retirement is necessary but insufficient for p Race-safe purge workflow: -- Eligibility checks and purge start must not run as a loose "check then delete" pair. The target order is: `TombstoneVersionAssets` performs the pre-tombstone authority/reachability/abandonment check and CAS transition; `CanDeleteVersionAssets` performs the post-tombstone fail-closed recheck; `BeginPurgeVersionAssets` performs the final atomic recheck and `TOMBSTONED -> PURGE_IN_PROGRESS` CAS. The current implementation has the opposite unusable drift—`CanDeleteVersionAssets` rejects pre-tombstone `FAILED`/`PUBLISHED` states, while `TombstoneVersionAssets` does not perform the target authority checks—and its artifact and Version row updates are not database CAS. Missing-tenant-matching-version/no-bundle eligibility (including a wrong-tenant version row) also currently fails open; all remain implementation gaps. +- Eligibility checks and purge start must not run as a loose "check then delete" pair. The target order is: `TombstoneVersionAssets` performs the pre-tombstone authority/reachability/abandonment check and CAS transition; `CanDeleteVersionAssets` performs the post-tombstone fail-closed recheck; `BeginPurgeVersionAssets` performs the final atomic recheck and `TOMBSTONED -> PURGE_IN_PROGRESS` CAS. Current artifact saves use database epoch CAS, but the authority/reachability/abandonment checks and Version/global fence remain incomplete. Missing-tenant-matching-version/no-bundle eligibility (including a wrong-tenant version row) also currently fails open. Physical deletion is denied rather than relying on those partial checks. - Focused proof must cover a caller-tenant artifact with no tenant-matching version authority, both when `versionId` is absent and when a row exists only for another tenant, with no caller-tenant release bundle; each case must return `deletable=false`. Positive controls are a caller-tenant `RETIRED` version for a published/release artifact and a caller-tenant `FAILED` version with durable explicit abandonment proof for an abandoned candidate, each with the other applicable reachability checks clear. A `FAILED` candidate without that abandonment proof remains non-eligible. - The target workflow calls `TombstoneVersionAssets` first for a retired `PUBLISHED` release, or for a `FAILED` candidate only after caller-tenant `FAILED` authority and durable abandonment proof are available. It then reloads the artifact `stateEpoch`, calls post-tombstone `CanDeleteVersionAssets`, and only then calls `BeginPurgeVersionAssets`; the current implementation/order drift is explicitly fail-closed until these branches are implemented. - `TombstoneVersionAssets` must independently require the matching durable abandonment proof for the failed-candidate path and perform the pre-tombstone reachability check; `CanDeleteVersionAssets` must recheck the resulting tombstone and current authority/reachability; `BeginPurgeVersionAssets` must re-evaluate all proof and reachability conditions again rather than trusting an earlier response. @@ -514,14 +512,14 @@ Race-safe purge workflow: To prevent persistence and performance failures in asset workflows: - Maximum single asset size is 25 MiB; oversized uploads must fail with `ASSET_TOO_LARGE`. -- Per-tenant draft asset quota is 2 GiB. **Target admission rule:** exclude bytes retained solely because a `version_asset` reference keeps them reachable from a Published, Active, or Failed version. The current first slice has no authoritative `version_asset` mapping and performs no quota accounting or enforcement; it therefore neither proves that exemption nor applies a conservative charge. Once version-scoped references and quota enforcement exist, the quota query must derive exempt bytes from those normalized references rather than from tenant-wide export contents or object-store path conventions. Writes that would exceed the target quota must fail with `ASSET_QUOTA_EXCEEDED`. A future metadata-only storage model may measure retained immutable draft-object bytes instead, without changing the draft-only target boundary. +- Per-tenant draft asset quota is 2 GiB. **Target admission rule:** exclude bytes retained solely because a `version_asset` reference keeps them reachable from a Published, Active, or Failed version. The owner-local mapping exists, but the upload path performs no quota accounting or enforcement and does not prove the exemption. The quota query must derive exempt bytes from normalized references rather than from tenant-wide export contents or object-store path conventions. Writes that would exceed the target quota must fail with `ASSET_QUOTA_EXCEEDED`. A future metadata-only storage model may measure retained immutable draft-object bytes instead, without changing the draft-only target boundary. - Upload/download APIs must support streaming/chunked transfer at the transport layer; services must not require buffering full payloads in memory before persistence. - Publish/export workers must process assets in bounded batches (configurable), with backpressure metrics to avoid starving version publish orchestration. - Quota and size limits must be configurable per environment but default to the values above when unset. -In the current first slice, `game_assets` is the canonical design-time store for asset metadata and bytes. Its retained `data` values become the repair source only after the frozen version-scoped export snapshot identifies the exact rows and hashes used by that release; neither the database schema nor repository update path enforces immutability, so editing a referenced row would invalidate that assumption. Until the snapshot is available, same-version repair fails with `REPAIR_VERSION_SCOPE_UNAVAILABLE` for Published/Active releases. A future metadata-only storage model may treat the table as metadata and use retained immutable object-store draft keys, but that is target-only. +`game_assets` is the canonical design-time store for asset metadata and bytes. Its retained `data` values become the repair source only after the frozen version-scoped export snapshot identifies the exact rows and hashes. Database guards preserve referenced source identity, name, type and bytes. Missing retained snapshot/candidate evidence fails closed; a future metadata-only storage model must supply equivalent immutable repair evidence before removing these bytes. -Published assets still retain their `game_assets` rows for design history and exact-bytes repair. In the target contract, version-level `FinalizePurgeVersionAssets` deletes only the frozen version-artifact objects and never removes those source rows or `game_assets.data` bytes; it routes through the Game Design reachability and CAS-guarded artifact-purge workflow rather than direct object-store commands. The current implementation only deletes the frozen version-prefix objects and lacks that database CAS/reachability fence. +Published assets retain their `game_assets` rows for design history and exact-bytes repair. Target `FinalizePurgeVersionAssets` deletes only frozen objects authorized by the complete global reachability/purge fence, never source rows or `game_assets.data`. Current physical deletion is denied pending that proof; a prefix or lifecycle CAS alone cannot authorize deletion. A separate target maintenance workflow may mark an unreferenced `game_assets` row as `obsolete` and remove that row and its `game_assets.data` bytes. That workflow must independently prove global normalized `version_asset` reachability across every version state, global normalized `revision_asset` and branch reachability, and any other retained design-history dependency, then perform its own CAS-guarded maintenance transition. Assets referenced by any retained version or history path must never be deleted, and their binary contents must not be modified in place. The current version-artifact purge workflow is not this source-row maintenance workflow and must not delete `game_assets` rows or data. A future metadata-only storage model may apply the same separate reachability/CAS boundary to unreferenced draft objects. The exact retention policy (for example “keep assets referenced by the last N versions per tenant”) is configurable but should be documented alongside operational runbooks. diff --git a/design/architecture/microservices/game-design-service/configuration.md b/design/architecture/microservices/game-design-service/configuration.md index 038b2a5e59..82a227e19a 100644 --- a/design/architecture/microservices/game-design-service/configuration.md +++ b/design/architecture/microservices/game-design-service/configuration.md @@ -2,7 +2,7 @@ ## Implementation Status -The target configuration separates the private authenticated S3 API (`ASSET_STORE_ENDPOINT`) from the gateway/CDN `/assets/**` delivery base (`ASSET_STORE_PUBLIC_BASE_URL`). The current first slice uses one `ASSET_STORE_ENDPOINT` for both S3 operations and generated manifest URLs; `ASSET_STORE_PUBLIC_BASE_URL` is not implemented or bound, so public delivery remains unavailable. The environment-variable table below remains the canonical configuration contract. +The service binds the private authenticated S3 API and public `/assets/**` base from separate environment variables. It never derives a public URL from the private endpoint, and an explicitly configured base does not establish an approved or provisioned public delivery origin. The delivery authority and activation gates remain owned by [Asset Storage](./asset-storage.md#target-external-delivery-classification). ## Environment Variables @@ -28,10 +28,9 @@ Published assets are uploaded to an S3-compatible bucket. Configure the client w | Variable | Purpose | Default | | -------- | ------- | ------- | -| `ASSET_STORE_ENDPOINT` | Private authenticated S3-compatible API used by Game Design reads and writes | *(none)* | -| `ASSET_STORE_PUBLIC_BASE_URL` | Gateway/CDN `/assets/**` base used for generated manifest links (target-only) | *(none)* | -| `ASSET_STORE_BUCKET` | Bucket used for published assets | *(none)* | +| `ASSET_STORE_ENDPOINT` | Private authenticated S3-compatible API used by Game Design reads and writes | *(unset)* | +| `ASSET_STORE_PUBLIC_BASE_URL` | Separately configured `/assets` base used for generated manifest links; never defaults from the private endpoint | *(unset)* | +| `ASSET_STORE_BUCKET` | Bucket used for published assets | *(unset)* | | `ASSET_STORE_REGION` | Region name for the S3 client | `ap-southeast-2` | -| `ASSET_STORE_ACCESS_KEY` | Access key for the bucket | *(none)* | -| `ASSET_STORE_SECRET_KEY` | Secret key for the bucket | *(none)* | -| `ASSET_STORE_FROZEN_SNAPSHOT_CACHE_MAX_ENTRIES` | Maximum process-local frozen export snapshots retained; a new uncached scope fails closed at capacity rather than evicting retry evidence | `256` | +| `ASSET_STORE_ACCESS_KEY` | Access key for the bucket | *(unset)* | +| `ASSET_STORE_SECRET_KEY` | Secret key for the bucket | *(unset)* | diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 9d2411a8b2..5bfa04fc8b 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -6,7 +6,7 @@ Game Design is the canonical authored-history, publication-coordination, release ## Implementation Status -External Git synchronization and canonical multi-branch merge semantics are not implemented. Current authoring uses Game Design-owned revision APIs with optimistic validation and ordered mutation calls, but `SaveRevision` does not provide deterministic replay: it lacks durable request/revision deduplication and can leave a World mutation committed without its corresponding Game Design revision when the later local save fails. ADR 0129's durable multi-owner coordinator, owner-local compare-and-swap application, synchronized commit fence, and proof that partially applied owner rows remain invisible to ordinary Draft reads are also not implemented. Current release-bundle schema and plugin publication/activation code incorrectly reuse Automation & Scripting's aggregate participant `contentDigest` where the dedicated Game Logic-owned `abilitySchemaDigest` is required; exact ability-schema compatibility therefore remains an implementation and proof gap. Plugin publication currently uses signed-only intake; [ADR 0111](../../decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md)'s approved unsigned provenance remains target-only. The plugin publication path now rejects terminal-state reuse: an uploaded `SUPERSEDED` or `REVOKED_DESIGN` row cannot be republished under the same `pluginVersionId`; target rollback still uses a new immutable plugin version and leaves the prior terminal row unchanged, while new-version rollback proof remains absent. Duplicate signed plugin `assetId` values are likewise not rejected before export and can produce ambiguous distribution-manifest keys; target intake rejects them deterministically before publication/export. The live World Management design handoff adds a separate lifecycle race: it checks Game Design's authoritative remote version state (`GetVersionState(...).versionState=DRAFT`) before its own transaction, but has no durable owner-local publication freeze or exact Game Design version-state epoch/fence in the mutation request. That remote state check is not proof that a WMS mutation cannot commit after publication; current status and evidence remain in [World Management Runtime and Data](../world-management-service/runtime-and-data.md#implementation-status). +External Git synchronization and canonical multi-branch merge semantics are not implemented. Current authoring uses Game Design-owned revision APIs with optimistic validation and ordered mutation calls, but `SaveRevision` does not provide deterministic replay: it lacks durable request/revision deduplication and can leave a World mutation committed without its corresponding Game Design revision when the later local save fails. ADR 0129's durable multi-owner coordinator, owner-local compare-and-swap application, synchronized commit fence, and proof that partially applied owner rows remain invisible to ordinary Draft reads are also not implemented. The candidate release carrier now retains the dedicated Game Logic-owned `abilitySchemaDigest` in immutable participant evidence, and plugin publication rejects absent, wrong-owner or mismatched proof instead of reusing Automation's aggregate `contentDigest`. The normal Game Logic source producer and complete activation compatibility remain implementation and proof gaps. Plugin publication currently uses signed-only intake; [ADR 0111](../../decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md)'s approved unsigned provenance remains target-only. The plugin publication path now rejects terminal-state reuse: an uploaded `SUPERSEDED` or `REVOKED_DESIGN` row cannot be republished under the same `pluginVersionId`; target rollback still uses a new immutable plugin version and leaves the prior terminal row unchanged, while new-version rollback proof remains absent. Duplicate signed plugin `assetId` values are likewise not rejected before export and can produce ambiguous distribution-manifest keys; target intake rejects them deterministically before publication/export. The live World Management design handoff adds a separate lifecycle race: it checks Game Design's authoritative remote version state (`GetVersionState(...).versionState=DRAFT`) before its own transaction, but has no durable owner-local publication freeze or exact Game Design version-state epoch/fence in the mutation request. That remote state check is not proof that a WMS mutation cannot commit after publication; current status and evidence remain in [World Management Runtime and Data](../world-management-service/runtime-and-data.md#implementation-status). Migration V28 corrects the historical V13 default by retaining every affected row while moving only non-script-only rows whose exact V13 marker remains (`version_state=PUBLISHED`, `version_state_epoch=1`) and whose exact `(tenant_id, version_id)` `published_release_bundle` is absent to `FAILED`, incrementing the epoch and refreshing `updated_at`. Bundled full versions and script-only publication rows are untouched, and the marker predicate makes the correction idempotent. Validation follows the shared [Validation and Runtime Proof](../../../developer-workflows/validation-and-runtime-proof.md) workflow; PostgreSQL retained-row execution remains a required migration gate. This data correction is separate from the still-open `CompareAndSetVersionState` transition gap: the live path locks the exact Version row for its epoch check but still accepts any non-null lifecycle state and does not enforce release-bundle/artifact or retirement guards. diff --git a/design/architecture/microservices/game-logic-service/runtime-and-data.md b/design/architecture/microservices/game-logic-service/runtime-and-data.md index 375cc8f220..eef0de1ac1 100644 --- a/design/architecture/microservices/game-logic-service/runtime-and-data.md +++ b/design/architecture/microservices/game-logic-service/runtime-and-data.md @@ -25,7 +25,7 @@ The sections below define the target-state runtime contract. Current implementat - The target runtime contract is that every player-delegated gameplay RPC carries the complete validated typed `PlayerExecutionContext`, including `tenantId`, `playableStateNamespaceId`, server-derived `playableStateScope`, active `gameInstanceId`, and applicable region/epoch or executor fences. The live per-RPC schemas, including `SendCommunication` and its legacy `session_attestation`, remain an implementation gap; see the [PlayerExecutionContext contract](../../system-architecture-authentication.md#gameplay-player-execution-context-contract-normative). - Gameplay gRPC requests do not include JWTs. Game Session provides player identity from Redis via `SessionContext`, may refresh a JWT from Account Service if roles change, and does not validate tokens for gameplay. Service-to-service traffic still uses mutual TLS as described in the [Security Architecture](../../system-architecture-security.md). - Utilizes the [Shared Libraries](../../system-architecture-shared-libraries.md) for DTO definitions, logging interceptors, and Micrometer metrics. -- Flyway is enabled for consistency with other services, but the initial migration is empty because no tables are required. +- Flyway is enabled; the current initial migration is empty because the owner-local versioned rule/ability source is not implemented. This is implementation status, not permission to replace the target source with another service's aggregate or process-local state. - NPC morale and aggression-state evaluation remain part of this service's runtime behavior. When gameplay rules consume faction or reputation signals sourced from Social & Groups, the local morale logic is still owned here, including transitions such as `FLEEING` and `SURRENDERED`; cross-service reputation data informs the decision, but Game Logic owns the gameplay-state consequence. ## Workflow Participation @@ -47,6 +47,8 @@ For full-version publish gating, this service is still a required digest partici Publish gating must fail closed if this service cannot attest a digest under its documented manifest for the reported `digestSchemaVersion`. +The typed digest response distinguishes the complete rule-input `contentDigest` from the dedicated `abilitySchemaDigest`. Both belong to the same exact tenant/version, `appliedCommitId`, and supported `digestSchemaVersion`; a value from Automation, another participant, another commit or an unsupported source schema cannot substitute for Game Logic's ability evidence. The optional carrier represents absent evidence, not a proved empty schema. A successful full-version publish requires the dedicated Game Logic value, preserves it in the immutable release participant evidence and compares it exactly for plugin compatibility. Defining the normal persisted input manifest, its ability-schema subset and canonicalization remains producer work; the current unavailable producer must continue rejecting the request rather than manufacture either digest. + ## Redis Role and Prefixes ### Coordination Redis diff --git a/design/architecture/system-architecture-versioning-runtime.md b/design/architecture/system-architecture-versioning-runtime.md index 9a7c1379c8..7f4e8a112b 100644 --- a/design/architecture/system-architecture-versioning-runtime.md +++ b/design/architecture/system-architecture-versioning-runtime.md @@ -315,7 +315,7 @@ Tooling in the Game Design and Logging & Admin services should surface these rel - `manifestSchemaVersion` - `requiredManifestAssetKeys[]` for stable manifest usage keys that are mandatory for launch/cutover validation of that release - `generationConfigRevision` -- The current release-bundle schema omits the dedicated `abilitySchemaDigest`, target `commitId`, `manifestSchemaVersion`, and complete `artifactDigests[]`; plugin compatibility paths also incorrectly reuse the Automation & Scripting participant digest. Those current paths are implementation drift and do not prove the target release or ability-schema attestation. +- The candidate release carrier now preserves `manifestSchemaVersion`, ordinary actual-byte `artifactDigests[]` and the dedicated `GAME_LOGIC` participant `abilitySchemaDigest`; plugin comparison rejects missing or mismatched dedicated proof rather than using Automation's aggregate. These fields do not establish the target coordinated `commitId`, normal Game Logic source producer, other derived-artifact producers, complete authenticated descriptor/attestation pair or activation proof. - `artifactDigests[]` is authoritative for mandatory actual-byte object digests. `requiredManifestAssetKeys[]` is complementary: every required usage key must select exactly one bundle artifact digest and exactly one manifest entry whose `usageKey`, `immutableObjectKey`, and `contentDigest` are byte-for-byte equal. - `manifestHash` attests the canonical manifest bytes containing those usage-key/object-key/digest bindings; it does not replace per-object byte verification. - The contract intentionally does not introduce a separate top-level artifact-path reference field outside this attested bundle shape. Runtime consumers still discover artifact locations through the attested `manifest.json`, not through ad hoc object-store path reconstruction. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 8de0b809db..21a9469e38 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -421,3 +421,8 @@ Entry format: - Context: the #2966 watcher was assigned run `37182915940`, but returned a 404 result for the unrelated run `371546092`. The intended workflow had already been dispatched and its exact head verified; the wrong-target error was not evidence that the assigned run was unavailable. - Outcome: Document rejected the unavailable-run conclusion and resumed the same sole watcher with the literal run URL and a separate workflow ID. The corrected watcher verified the assigned workflow/head and returned raw XML proving the required Account cases executed cleanly; the overall run completed with failures outside the Account job. No second watcher or duplicate parent polling was started. - Expected pattern: require the executed request identity to match the assignment before classifying an external failure. Distinguish a workflow ID from a run ID and retain any mismatched query as a delegation error, not provider evidence. + +- `2026-10-05`: Enable a diagnostic report when the exact SpotBugs task hides its findings + - Context: Game Design's integration analyzer exited with code 3 without a report; repeating the exact task with `--info` still showed only the invocation and missing annotation class, not the finding. A temporary Gradle init script enabling an XML report on that same task exposed a nullable PostgreSQL read in the new composition test. + - Outcome: the missing-row read now fails explicitly, and the canonical composed check passes without suppressions or reduced analyzer coverage. The report-only script was a temporary diagnostic input, not repository tooling or substitute validation. + - Expected pattern: if the detailed log remains inconclusive, enable the affected task's report without changing its analysis or failure policy; fix the reported issue and rerun the normal gate. A missing annotation warning alone does not explain an analyzer failure. diff --git a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md index 4bb73b3c76..2f3c63b652 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -134,7 +134,7 @@ Publish workflow state is also exposed through canonical control-plane reads; Te Publication truth, readiness truth, activation truth, and append-only runtime chronology remain separately readable. Plugin runtime state is Automation-owned and records activation, disable, drain, policy reconciliation, request/actor visibility, policy-check time/staleness, and observed Game Session runtime scope. Activation preflight consults Game Design publication and Game Session instance metadata and fails closed for revoked signer evidence, blocked or missing component policy, unsupported built-in command-alias bindings, instance-scoped binding conflicts, stale publication/policy evidence, or stale observed region/epoch. Report-only policy decisions remain activatable. Enabled states are rechecked by scheduled policy reconciliation and disabled when evidence becomes fail-closed; append-only plugin runtime events retain previous/active publication cross-links. -Game Design plugin publication reads expose tenant-scoped version statuses, durable `SIGNATURE_VERIFIED` and `VALIDATION_FAILED_DESIGN` states with `statusReason`, base-version attestation, signer/component-policy gates, and distribution-manifest export. Publication and runtime activation currently compare `abilitySchemaDigest` against Automation's aggregate participant digest rather than a dedicated Game Logic-owned release-attested ability-schema digest, so exact ability-schema enforcement remains unproved; `baseVersionId` enforcement is live. +Game Design plugin publication reads expose tenant-scoped version statuses, durable `SIGNATURE_VERIFIED` and `VALIDATION_FAILED_DESIGN` states with `statusReason`, base-version attestation, signer/component-policy gates, and distribution-manifest export. The candidate Game Design publication, Automation runtime activation and script-patch status readers use the dedicated Game Logic-owned `abilitySchemaDigest`, not Automation's aggregate participant digest. Runtime activation denies missing, wrong-owner, conflicting, unsupported or mismatched full-Version evidence before registry mutation; status reads leave unavailable compatibility metadata empty. Scoped unit carrier and negative-consumer cases are not proof of the still-missing normal Game Logic source producer or complete authenticated activation; `baseVersionId` enforcement remains separate. Plugin runtime status retains the last observed Game Session runtime scope and reuses its stored `runtimeRegionId` for later region-aware runtime-state reads rather than collapsing the selector to `{tenantId, gameInstanceId}`. 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 414e2606ef..fd876b3b91 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,7 +6,11 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The source-aware Unit 1B launch integration still depends on the complete Game Design release producer under `AR-1.4`, `AR-1.5` and `AR-3.2`. The prepared owner-reference prerequisite adds a fresh persisted opaque identity to new release-bundle rows and preserves retained rows as unbound; the source-bound descriptor uses that exact reference rather than deriving it from private identifiers. Its focused validation and executed PostgreSQL proof must be recorded separately. The existing generic release read still lacks the complete target commit, actual-byte artifact digests/manifest schema and dedicated Game Logic ability-schema evidence. Tenant-wide mutable asset export and the process-local frozen-content cache do not supply version-scoped durable attestation. Game Logic's required full-version manifest/provenance remains unavailable, so no complete source-qualified release response or successful launch can be manufactured from these seams. Separately proved source-qualified version-state reads below do not close this release gate. Retained World content additionally needs its owner-approved audited canonical association; neither Game Session's private tenant key nor Account's migration manifest can substitute for World evidence. Initial launch and admission remain denied until the corresponding owner producers and authenticated exact readback/consumer proof execute. +The source-aware Unit 1B launch integration still depends on the complete Game Design release producer under `AR-1.4`, `AR-1.5` and `AR-3.2`. The owner-reference prerequisite preserves independently generated opaque release identity and exact canonical tenant/Version provenance; neither derives from private identifiers. Exact `cec29b3fcad147be44dd37b1d47381fecd0d8dac` [CI37224206898](https://github.com/benhook1013/FireMUD/actions/runs/37224206898) executed all six canonical Version and five immutable release-identity PostgreSQL methods without skips, failures or errors; aggregate CI failed elsewhere. These cases supersede the earlier missing source fixtures and overlong schema-name failure below, not the missing whole-release producer. Game Logic's required full-version manifest/provenance and dedicated ability-schema evidence remain unavailable, so no complete source-qualified release or successful launch may be manufactured. Retained World content still needs its own audited association; private key equality or Account's manifest is not World authority. Initial launch and admission remain denied until the complete owner and authenticated consumer proof executes. + +The ordinary-asset producer replaces tenant-wide selection and process-local recovery with V37 owner-qualified Draft mappings and immutable actual-byte snapshots, including a proved empty set. V38 freezes complete ordered artifact/manifest candidate evidence before external writes; conditional content-addressed export verifies exact bytes, type and length, while ambiguity remains PENDING. Checked artifact epoch CAS and immutable release readback do not authorize shared-object deletion or complete Version lifecycle/purge fencing. Exact `9789b12fc892d7187dc9268312d4a96010924345` [CI37233813567](https://github.com/benhook1013/FireMUD/actions/runs/37233813567) executed all 15 required asset and five release-identity PostgreSQL cases cleanly, superseding the earlier insert/fixture failures. Its two publication transaction failures exposed diagnostic overflow; forward V39 losslessly widens generated release/descriptor revisions and terminal diagnostics, with retained-row and exact failed-retry cases awaiting corrected PostgreSQL execution. V40 preserves the dedicated Game Logic ability digest in publish-attempt evidence, including NULL absence, separately from aggregate content. The corrected five-service check and five boot JARs pass locally: 475 Game Design and 1193 Automation unit cases execute cleanly; other service results are reused. All 93 Game Design PostgreSQL/composition and 88 Automation integration cases skip locally without Docker. Historical actual-MinIO exporter proof uses synthetic snapshot/candidate fixtures; the new PostgreSQL-to-real-MinIO composition case is separately required but not yet executed. Mocked S3, compiled or skipped tests are not provider/database execution. Public authenticated Draft/creator ingress, the normal rule/ability and derived-artifact producers, complete descriptor/release and World binding, Version/global reachability/purge fences, fresh image/deployment and approved live public delivery remain open; no runtime activation is authorized. The [asset-storage owner](../../architecture/microservices/game-design-service/asset-storage.md) owns the target contract. + +At exact `9789b12fc892d7187dc9268312d4a96010924345`, [CI37233813567](https://github.com/benhook1013/FireMUD/actions/runs/37233813567) executed all seven asset-snapshot, six export-candidate, two artifact-repository and five release-identity PostgreSQL cases with zero skips, failures or errors. Independent raw-XML parsing confirms those counts. The earlier source-built MinIO provider case at `80aefbf43b09854f472e491463f9ff2d41e4313e` passed with synthetic snapshot/candidate fixtures; it does not establish database-to-store composition. The current CI also exposed two publication transaction failures and misplaced later required-case checks after other selectors replaced their reports; aggregate CI is not green. Corrected transaction, composed PostgreSQL-to-MinIO and fresh application-image proof remain separate gates. Three PostgreSQL-through-physical-mTLS methods compose the source-qualified version read using the actual persisted repositories, transaction manager, owner producer, handler, peer interceptor and World client. They cover complete non-mutating readback, changed-source/foreign-version denial and a fresh lifecycle/epoch snapshot for a repeated read identity. Their authored-source fixtures are synthetic. At exact `cd7751371e999360091e6ed70c99d45acee88d76`, [CI37130036974](https://github.com/benhook1013/FireMUD/actions/runs/37130036974) was terminal `FAILURE`; independent raw-XML parsing and rehashing nevertheless verified all 11 focused suites clean, including these three methods, with 75 executed, 75 passed, and zero skips/errors/failures. The full local Game Design/World PostgreSQL suites still skip without Docker; this is a local limitation, not a runner skip. Automatic delivery, publication, canonical World writes and runtime activation remain separate open boundaries. @@ -38,7 +42,7 @@ The Gateway Java catalog now omits external Game Design asset and template write Game Design's script-patch and plugin transition implementation remains partial: design-time publication metadata and bounded local activation-preflight seams exist, but dedicated Game Logic ability-schema compatibility, tenant runtime readiness, exact instance pin/epoch propagation, rollout/rollback history, and end-to-end recovery proof remain absent or unproved. The ownership and lifecycle contracts for these gaps are recorded in [ADR 0103](../../architecture/decisions/adr-0103-single-authority-script-pins-with-exact-version-execution.md), [ADR 0106](../../architecture/decisions/adr-0106-epoch-fenced-script-rollback-without-routine-gameplay-pause.md), [ADR 0107](../../architecture/decisions/adr-0107-stage-aware-script-dead-letter-recovery.md), [ADR 0108](../../architecture/decisions/adr-0108-no-degraded-script-admission-without-authoritative-pin.md), [ADR 0109](../../architecture/decisions/adr-0109-game-session-owned-script-rollout-history.md), [ADR 0110](../../architecture/decisions/adr-0110-explicit-opt-in-schedule-continuity-across-script-transitions.md), [ADR 0111](../../architecture/decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md), and [ADR 0119](../../architecture/decisions/adr-0119-epoch-fenced-per-instance-plugin-activation.md). This tracker records only current implementation and proof status. -AR-1.5 full-version publication now reserves its Draft version and PENDING attempt together, keeps participant collection/export outside the final local transaction, and finalizes release bundle, Published version/artifact, verified baseline, and SUCCEEDED attempt atomically. A definite failure retains the candidate version and, only after exact readback confirms no release evidence, marks the attempt FAILED and any exported artifact FAILED; partial or committed release evidence remains PENDING for reconciliation. Same-request retries can still race during external participant/export work before the final game-row lock; no durable external-phase owner, private candidate namespace, or object-export deduplication was added in this bounded slice. Because export writes mutable tenant/version object keys, a late retry may overwrite bytes after another request has committed their release attestation; a failing retry can also mark the shared attempt failed or clean up keys while another exporter is active. The final local transaction alone does not prevent these external races. Focused and Docker-dependent proof of these paths is deferred to the main orchestrator; post-bundle failure reconciliation must continue to follow the asset-storage owner's exact readback/CAS rules. +AR-1.5 full-version publication reserves Draft/PENDING together, keeps owner participant collection and export outside finalization, and finalizes release bundle, Published Version/artifact, verified baseline and SUCCEEDED attempt atomically. The asset batch additionally commits and reads back STAGED intent and immutable candidate proof before conditional writes; exact retries cannot overwrite shared content-addressed bytes. A definite failure retains the candidate Version and requires exact no-release/no-unresolved-write proof. Ambiguous intent, external write, partial or committed release stays PENDING for reconciliation, without prefix cleanup. This does not supply the missing full participant/ability-schema or public origin authorities. Corrected cumulative transaction, race, lost-acknowledgement and PostgreSQL execution remain required; the final local transaction alone is not external-phase proof. The publication proof recorded in this tracker remains limited to local gate, release-bundle, participant-digest, and transaction-unit seams. V28 now corrects V13-inferred full-version publication state without deleting retained rows: focused source-shape proof covers the exact epoch-1 marker, exact tenant/version bundle correlation, preservation of bundled and script-only rows, and idempotent epoch/timestamp quarantine, while PostgreSQL retained-row execution remains outstanding. It does not prove the end-to-end Temporal activity-to-owner path, database rollback/ambiguous-commit recovery, or live workload-certificate admission. This migration correction is separate from the still-open arbitrary `CompareAndSetVersionState` transition gap recorded below. @@ -72,8 +76,8 @@ These links add decision provenance only; they do not change existing implementa | `EA-3.2` Creator authoring applications | `partial` | `audited` | [Frontend architecture](../../architecture/system-architecture-frontend.md); [creator journeys](../../product/user-journeys/creators.md); [world editing tools](../../architecture/microservices/game-design-service/world-editing-tools.md) | [App.tsx](../../../web-client/src/App.tsx); [GameEditor.tsx](../../../web-client/src/GameEditor.tsx); [ScriptEditor.tsx](../../../web-client/src/ScriptEditor.tsx); [GameDesignGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java) | [GameDesignGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java); [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md); [gameplay](./gameplay-rules-entities-and-effects.md); [player experience](./player-experience-commands-and-communication.md) | Partial: the [web-client README](../../../web-client/README.md) records a starter React surface and backend authoring APIs exist, but the designed creator application, accessible editor workflows, preview, conflict resolution, and focused frontend proof are absent. ADR 0124, ADR 0126, and ADR 0129 define the profile, scoped-proposal, and Draft-fence target behavior; implementation and focused proof remain absent. | | `AR-1.1` World, entity, rule, and content authoring | `partial` | `proven` for the typed revision-to-World mutation, authored help/command, and entity-template validation seams; complete world, entity, rule, and content authoring remains unproved. | [Game Design ownership](../../architecture/microservices/game-design-service/README.md); [world editing tools](../../architecture/microservices/game-design-service/world-editing-tools.md); [ability/action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [item and equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [GameAuthoredHelpTopicServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImpl.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql); [EntityTemplateReferenceServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityTemplateReferenceServiceImpl.java) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [GameAuthoredHelpTopicServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImplTest.java); [EntityTemplateReferenceServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityTemplateReferenceServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md) | Partial: typed revision-to-World mutation, authored help/commands, and entity template/runtime validation seams exist, but complete rule/action/effect catalogs and creator-facing authoring workflows are not implemented. Accepted procedural-generation decisions now define World-owned typed ingress and preview-bound replacement, but typed generation ingress, destructive plan protocol, and identity/reference proof remain incomplete. | | `AR-1.2` Procedural, LLM-assisted, and external authoring tools | `partial` | `proven` for bounded procedural generation and typed generation mutation seams; LLM-assisted authoring, typed generation ingress, 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 typed generation mutations exist. 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. Accepted procedural-generation decisions now define one World-owned engine, request-bounded replay, bounded persistence, previewed replacement, and sparse/full-grid semantics; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | -| `AR-1.3` Script, plugin, mod, and extension packaging | `partial` | `proven` only for signed plugin intake, script-patch request/reservation and conditional local finalization seams, and bounded local activation-preflight/control-plane seams; the composed script-patch path currently fails at the participant gate, so successful publication and readiness are not proved. 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); [VersionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.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); [VersionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.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` | `audited` | [Game Design asset storage](../../architecture/microservices/game-design-service/asset-storage.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); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.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) | [AssetExportServiceImplTest.java](../../../services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.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) | [platform operations](./platform-operations-and-delivery.md); [player experience](./player-experience-commands-and-communication.md) | Partial: export, artifact-state, manifest-hashing, repair, and purge seams exist, but the required fail-closed version-scoped publication gate is not implemented. The `version_asset` mapping table and its Draft-version authoring path are absent; `AssetExportServiceImpl` exports every tenant asset, and publication does not prove that only mapped assets were selected. The release bundle also lacks canonical target-commit, manifest-schema, and applicable artifact-digest fields. Release readiness cannot be claimed until the mapping/authoring path and guard exist with focused proof. Normalized asset/history and derived-artifact substrates plus complete creator asset UX remain absent. Accepted asset/publication decisions now define content-addressed bytes, fail-closed attestation, and version-scoped publication; version-scoped asset mapping and complete release-bundle digest fields remain incomplete. | +| `AR-1.3` Script, plugin, mod, and extension packaging | `partial` | `proven` only for signed plugin intake, script-patch request/reservation and conditional local finalization seams, and bounded local activation-preflight/control-plane seams; the composed script-patch path currently fails at the participant gate, so successful publication and readiness are not proved. 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); [VersionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.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); [VersionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.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 the candidate publication validator now uses the dedicated Game Logic-owned ability-schema carrier and rejects aggregate-only, absent or wrong-owner evidence; the normal source producer remains unavailable. 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` | `audited` | [Game Design asset storage](../../architecture/microservices/game-design-service/asset-storage.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); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.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) | [AssetExportServiceImplTest.java](../../../services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.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) | [platform operations](./platform-operations-and-delivery.md); [player experience](./player-experience-commands-and-communication.md) | Partial: the owner-local V37 mapping/frozen snapshots and V38 immutable candidates select exact Version bytes, persist manifest schema/artifact proof, and independently read evidence before conditional content-addressed writes. Physical purge remains denied pending shared reachability and owner-retention proof. Exact #2983 source-built MinIO proof executes successfully, but PostgreSQL execution exposed a missing insert readback and a stale historical-schema fixture; corrected PostgreSQL proof remains required. The authenticated public Draft authoring/creator gate, canonical target-commit and Game Logic ability inputs, derived-artifact producers, complete release/descriptor binding, approved public-origin readiness and full creator UX remain incomplete. Retained absence is not synthetic empty evidence, and no publication/launch activation or complete-release claim is authorized. | | `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` only for current revision/version publication, the fail-closed publish gate, and happy-path release-bundle and participant-digest seams; 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. | [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) | [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) | [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) | [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: revision/version publication and fail-closed gate seams exist, but participant tokens are synthetic, World emits schema 2 while the gate accepts schema 1, and the release bundle is still minimal, so actual same-commit attestation convergence is not established. Accepted publication, release, asset, and procedural-generation decisions now define the target authority chain; 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. | @@ -145,13 +149,13 @@ The broader authored-action model is not complete. The locked expansion boundary ### Publication, Temporal Workflows, and Release Attestation -Asset lifecycle status and proof remain partial: export is still tenant-wide and unscoped with only a process-local selection because durable `version_asset` mappings and `version_asset_export_item` snapshots are absent. Version-scoped readiness, lifecycle operation safety, and publication recovery 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); this tracker records the current status and proof gaps without repeating those owner contracts. +Asset lifecycle status and proof remain partial. The ordinary-byte producer now selects exact owner-qualified Draft mappings through durable V37 snapshot headers/items and freezes the complete V38 candidate before external writes. Empty selection is recorded, not inferred from missing evidence. Database and actual object-store execution for this batch remain required; complete derived-artifact readiness, authenticated creator admission and lifecycle operation safety are still open. 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); this tracker records the current status and proof gaps without repeating those owner contracts. Full-version and script-patch publication use the live durable `publish_attempt`/participant-observation framework. World emits schema `2`, which the gate supports; current participant observations still use synthetic scope tokens, and same-commit convergence with focused proof remains incomplete. End-to-end full-version publication remains blocked because the Game Logic full-version owner digest fails closed without owner-local manifest/provenance for the version's rule inputs; its implementation status is recorded in [Game Logic API Contracts](../../architecture/microservices/game-logic-service/api-contracts.md#implementation-status). The canonical digest and participant contracts are owned by [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity); this tracker records only those implementation/proof gaps. Retrospective 5B exit disposition: Schema's V2→V3→V4 ordering and fail-closed retained-row shapes do not establish PostgreSQL execution on retained V26/V28 Game Design rows or a mixed-binary rollout; those are migration and activation gates, with the applicable Automation/Game Design `Recreate` rendering and live rollback policy still requiring proof. Publication has a separate current safety boundary: Automation's tenant-wide digest cannot truthfully attest one requested version or one base-bound patch, and a patch notification must not be reported as successful when no affected-definition/zero-handler evidence was accepted. The section-exit successor fails these paths closed; exact version mapping, digest-schema migration, owner freeze/commit evidence, durable readiness/manifest handling, live mounted-certificate calls, and Temporal failure/retry proof remain an ordered Game Design/Automation/World/Entity publication successor before publication is activated. A selected script patch likewise remains unavailable for launch until Game Design proves the exact published `(tenantId, baseVersionId, scriptPatchVersion)` and Automation `READY` state, with Game Session consumer revalidation. These are not implemented claims from the local gates. -Successful full-version publish still writes only a minimal `published_release_bundle`; target commit, manifest-schema, applicable artifact-digest, and public tenant projections are absent. The bounded transaction seam now performs exact bundle/artifact/version readback and keeps an ambiguous attempt pending, but database-backed rollback, concurrent retry, and committed/absent/ambiguous recovery proof remain incomplete. `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); current rows and defaults are not full-convergence proof. +New ordinary-asset publication retains exact manifest schema and artifact-digest evidence in `published_release_bundle` and its read carrier. Retained absent evidence remains absent. Complete target-commit, dedicated ability-schema, derived-artifact and authenticated descriptor/release convergence are still open. The bounded transaction seam performs exact bundle/artifact/version readback and keeps ambiguous writes pending; scoped STAGED intents can resume the same immutable candidate without becoming deletion or terminal-failure authority. Database-backed rollback, concurrent retry and committed/absent/ambiguous recovery proof for the composed producer remain required. `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); these fields are not full-convergence proof. 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 composed `VersionServiceImpl` path currently stops at the real participant gate because Automation's patch digest response is `UNSUPPORTED_SCOPE`, classified as `PARTICIPANT_UNAVAILABLE`; focused proof confirms the known-no-dispatch failure cleanup and that no notification is sent. When successful participant observations are supplied, the later empty-`affectedScripts` client validation still rejects before RPC dispatch, but that is a conditional unit seam. A direct Automation request with an empty list is separately rejected with `INVALID_ARGUMENT` / `zero_handler_manifest_unverifiable` before readiness mutation. No patch remains published and no Automation readiness candidate is created; the target durable `FAILED` readiness receipt is not persisted. There is no successful readiness trigger/workflow for script-patch readiness, `onLoad`, rollout, or supersede. Gameplay-time script execution and tick handoff remain outside Temporal. @@ -159,9 +163,9 @@ Temporal publication authorization has a distinct Game Design gRPC workload iden ### Published Asset Lifecycle -Current status/evidence: Game Design owns publication and the `version_asset_artifact` proof read, but the live export remains tenant-wide with only a process-local selection because durable `version_asset` mappings and export-item snapshots are absent. Published/active repair and retired-version handling retain fail-closed drift, and version-scoped readiness is not proven. Focused asset export, attestation, and lifecycle proof remains partial. +Current status/evidence: Game Design owns publication and the `version_asset_artifact` proof read. The ordinary-byte producer uses persisted version-scoped mappings, immutable export snapshots and complete pre-write candidates instead of tenant-wide listings or process-local recovery. Published/active repair requires the original frozen evidence; retained incomplete and retired rows remain denied. Focused exporter tests simulate S3, while new PostgreSQL and actual MinIO cases require separate executed proof. This does not establish complete release readiness or a provisioned public delivery origin. -Lifecycle status/proof is also incomplete: artifact and Version epoch checks lack database CAS; tombstone eligibility and failed-candidate abandonment are not fully implemented; post-bundle publish-failure reconciliation and durable ADR 0048 operation identity are absent. The canonical state, transition, purge, repair, and reachability rules remain owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow) and the [Asset Store Runbook](../../architecture/system-architecture-asset-store-runbook.md#removing-published-versions); this tracker records only implementation status and proof gaps. +Lifecycle status/proof is also incomplete: artifact updates now use exact tenant/version/epoch CAS with checked affected-row counts and overflow denial, but Version lifecycle CAS and the shared publication/reachability fence remain open. Tombstone eligibility, failed-candidate abandonment and durable ADR 0048 destructive-operation identity are not fully implemented. Physical purge and failed-publication compensation are denied rather than deleting shared content-addressed bytes. The canonical state, transition, purge, repair, and reachability rules remain owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow) and the [Asset Store Runbook](../../architecture/system-architecture-asset-store-runbook.md#removing-published-versions); this tracker records only implementation status and proof gaps. ### Launch, Activation, Cutover, and Termination @@ -177,7 +181,7 @@ Session stop deletes admission state before driving world termination and only f ### Script Patch and Plugin Publication -Publication/readiness and runtime activation are separate. Game Design exposes `GetPublishedScriptPatchVersion` and, for plugins, upload-first `UploadPluginBundle`, `PublishPluginVersion`, `GetPublishedPluginVersion`, and tenant-scoped `ListPluginVersionStatuses`. Design-time publication reads are distinct from runtime `GetScriptPatchStatus` and `GetPluginStatus` readiness/activation reads; callers must join those views rather than invent a fused state. The effective script identity is `(tenantId, baseVersionId, scriptPatchVersion)`; any script-only publication `versionId` is separate publication metadata/history and must not replace the base version when checking compatibility. Current script-patch publication persists caller-supplied `baseVersionId` without same-tenant/state/release validation, while `GetPublishedScriptPatchVersion` and its digest lookup now require the exact tuple and one script-only row in retained `PUBLISHED`, `ACTIVE`, or `RETIRED` state for publication metadata; new Game Session pin admission remains independently `PUBLISHED`-only, with focused `VersionRepositoryTest` and `VersionServiceImplTest` proof of the filter and read paths. These read filters do not establish complete patch publication or launch readiness. Upload parses signed plugin ZIPs, enforces bounded intake limits, verifies allowlisted Ed25519 signatures, extracts immutable manifest metadata, stores raw bytes in Game Design object storage, and records `SIGNATURE_VERIFIED`; the current row and its corresponding `PluginVersionStatusChanged` event leave `statusReason` empty rather than recording a deterministic verification reason. The target contract still needs explicit reason semantics and canonical evidence tying the verified signature to the status transition. Publication requires the previously uploaded verified bundle, reuses its immutable metadata, fails closed on blocked component policy, exports `assetRefs[]` into a plugin-version distribution manifest, and marks older published versions for the same `pluginId` as `SUPERSEDED`; terminal `SUPERSEDED`/`REVOKED_DESIGN` rows are rejected before same-identity republish, with focused proof, while new-version rollback proof remains absent. The live compatibility check incorrectly compares `abilitySchemaDigest` with the published `AUTOMATION_SCRIPTING` aggregate participant digest; the canonical release contract requires a dedicated Game Logic-owned ability-schema attestation, so publication and activation compatibility remain incomplete until that field and consumer path converge. +Publication/readiness and runtime activation are separate. Game Design exposes `GetPublishedScriptPatchVersion` and, for plugins, upload-first `UploadPluginBundle`, `PublishPluginVersion`, `GetPublishedPluginVersion`, and tenant-scoped `ListPluginVersionStatuses`. Design-time publication reads are distinct from runtime `GetScriptPatchStatus` and `GetPluginStatus` readiness/activation reads; callers must join those views rather than invent a fused state. The effective script identity is `(tenantId, baseVersionId, scriptPatchVersion)`; any script-only publication `versionId` is separate publication metadata/history and must not replace the base version when checking compatibility. Current script-patch publication persists caller-supplied `baseVersionId` without same-tenant/state/release validation, while `GetPublishedScriptPatchVersion` and its digest lookup now require the exact tuple and one script-only row in retained `PUBLISHED`, `ACTIVE`, or `RETIRED` state for publication metadata; new Game Session pin admission remains independently `PUBLISHED`-only, with focused `VersionRepositoryTest` and `VersionServiceImplTest` proof of the filter and read paths. These read filters do not establish complete patch publication or launch readiness. Upload parses signed plugin ZIPs, enforces bounded intake limits, verifies allowlisted Ed25519 signatures, extracts immutable manifest metadata, stores raw bytes in Game Design object storage, and records `SIGNATURE_VERIFIED`; the current row and its corresponding `PluginVersionStatusChanged` event leave `statusReason` empty rather than recording a deterministic verification reason. The target contract still needs explicit reason semantics and canonical evidence tying the verified signature to the status transition. Publication requires the previously uploaded verified bundle, reuses its immutable metadata, fails closed on blocked component policy, exports `assetRefs[]` into a plugin-version distribution manifest, and marks older published versions for the same `pluginId` as `SUPERSEDED`; terminal `SUPERSEDED`/`REVOKED_DESIGN` rows are rejected before same-identity republish, with focused proof, while new-version rollback proof remains absent. The candidate compatibility check now compares the dedicated `GAME_LOGIC` participant `abilitySchemaDigest` with the requested plugin value. Missing or wrong-owner evidence is denied without mutation; a genuine mismatch against complete supported owner evidence preserves the design-time validation-failure contract. Unit carrier/readback and negative comparison proof do not establish the normal rule/ability-schema source producer or complete activation compatibility. Design-time revoke is explicit through `RevokePluginVersion`. Upload verification, validation failure, publication, supersede, and revoke append durable tenant-scoped `PluginVersionStatusChanged`-equivalent rows exposed through `ListPluginVersionStatusEvents`, separate from instance-scoped runtime activation events. Runtime `SetPluginActiveVersion` consumes publication status, current Game Session runtime-instance metadata, immutable release participant digests, the authoritative built-in command-alias registry, and pinned script-patch bindings. It fails closed on non-`PUBLISHED` status, base-version or ability-schema mismatch, revoked signer metadata, blocked or missing component-policy decisions, unsupported built-in command aliases, or instance binding conflicts before mutating runtime state. Report-only component-policy decisions remain activatable. diff --git a/dev-tools/hosted/preview/resolve-preview-image-tag.sh b/dev-tools/hosted/preview/resolve-preview-image-tag.sh index f9d00f5fd6..442eb9e33c 100644 --- a/dev-tools/hosted/preview/resolve-preview-image-tag.sh +++ b/dev-tools/hosted/preview/resolve-preview-image-tag.sh @@ -33,7 +33,7 @@ runtime_relevant() { .github/workflows/runtime-images.yml | .github/workflows/publish-pr-runtime-images.yml | .github/workflows/smoke.yml | .github/workflows/smoke-full.yml | .dockerignore) return 0 ;; - .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/*) + .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/* | dev-tools/minio/*) return 0 ;; config/python/smoke-requirements.txt | config/python/smoke-requirements.in | \ diff --git a/dev-tools/minio/build-and-smoke-images.sh b/dev-tools/minio/build-and-smoke-images.sh index 417259ce59..8637c3c966 100644 --- a/dev-tools/minio/build-and-smoke-images.sh +++ b/dev-tools/minio/build-and-smoke-images.sh @@ -142,8 +142,8 @@ payload = { "client": {"image": client_image, "imageId": client_image_id, "tagObject": "835afd0a86e9a3ed396b8162eabc98243c342e5f", "sourceCommit": "fdb36acbb1d793b6cca622a55e6292f0d52309f0"}, - "builder": "golang:1.21.13-bookworm@sha256:c6a5b9308b3f3095e8fde83c8bf4d68bd101fce606c1a0a1394522542509dda9", - "runtime": "alpine:3.22.1@sha256:4bcff63911fcb4448bd4fdacec207030997caf25e9bea4045fa6c8c44de311d1", + "builder": "golang:1.27.1-bookworm@sha256:69a7b9788769bec032d238959b61854e9ae87f57be9029ec04e9885fabf99195", + "runtime": "alpine:3.24.2@sha256:294b683cb724975bec92580e1e685676bd4b50bda910ddb8c51d4cabeaec77e6", } Path(output).write_text(json.dumps(payload, sort_keys=True, separators=(",", ":")) + "\n", encoding="utf-8") PY diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index fdb265d732..3bf11d75f7 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -41,6 +41,18 @@ if script.index("github.rest.pulls.get") > script.index("github.paginate(github. raise SystemExit("validation-summary must verify the current PR before listing comments") PY +python3 - "$ROOT_DIR/.github/workflows/ci.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["validation-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + script_b64="$({ python3 - "$CI_WORKFLOW" <<'PY' import base64 diff --git a/dev-tools/tests/gradle-proof-tooling-contract.sh b/dev-tools/tests/gradle-proof-tooling-contract.sh index 04fefc18a0..492371b364 100644 --- a/dev-tools/tests/gradle-proof-tooling-contract.sh +++ b/dev-tools/tests/gradle-proof-tooling-contract.sh @@ -308,6 +308,24 @@ STORAGE_CASES = ( f"{STORAGE_SUITE}#migrationWaitsForConcurrentWriterThenRejectsItsCommittedEvidence()", ) CHECK_STEP = "🧪 Run Gradle Checks" +GAME_DESIGN_OWNER_STEP = "Run complete Game Design owner component PostgreSQL proof" +GAME_TENANT_CREATION_STEP = "Verify Game Design fresh tenant creation PostgreSQL proof" +GAME_AUTHORED_WORLD_SOURCE_STEP = "Verify Game Design authored-world source PostgreSQL proof" +GAME_DESIGN_CAPTURE_STEP = "Capture Game Design owner component proof before later test selectors" +GAME_DESIGN_LATER_SELECTOR_STEP = "Run Game Design authored-source launch descriptor PostgreSQL and socket mTLS proof" +GAME_TENANT_CREATION_SUITE = "integration.net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepositoryIntegrationTest" +GAME_TENANT_CREATION_CASES = ( + f"{GAME_TENANT_CREATION_SUITE}#createCandidateExactRetryReturnsCommittedReceiptWithoutSecondGameWrite()", + f"{GAME_TENANT_CREATION_SUITE}#concurrentDuplicateCreationRequestsConvergeOnOneUuidAndReceipt()", + f"{GAME_TENANT_CREATION_SUITE}#runtimeIdentityLookupReadsOnlyExactNewAndRetainedGameDesignRows()", +) +GAME_AUTHORED_WORLD_SOURCE_SUITE = "integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepositoryIntegrationTest" +GAME_AUTHORED_WORLD_SOURCE_CASES = ( + f"{GAME_AUTHORED_WORLD_SOURCE_SUITE}#registersAndReadsExactFreshAndRetainedV29ToV30Sources()", + f"{GAME_AUTHORED_WORLD_SOURCE_SUITE}#failedOwnerCommitRollsBackBothTenantSelectorAndWorldSource()", + f"{GAME_AUTHORED_WORLD_SOURCE_SUITE}#concurrentExactRegistrationRetriesReturnOnePersistedReceipt()", + f"{GAME_AUTHORED_WORLD_SOURCE_SUITE}#concurrentDifferentTenantsCannotClaimTheSameTenantSlug()", +) def require(condition: bool, message: str) -> None: @@ -323,6 +341,7 @@ def find_step(document, name): def validate(document) -> None: + steps = document["jobs"]["build-and-test"]["steps"] check = find_step(document, CHECK_STEP) check_run = check.get("run") require(isinstance(check_run, str), "Gradle check step has no run script") @@ -360,6 +379,45 @@ def validate(document) -> None: require(run.count(case) == 1, f"{name} must require exactly one execution of {case}") require(re.search(rf"(?m)^\s*{re.escape(service)}\s*$", run) is not None, f"{name} targets the wrong service") + owner = find_step(document, GAME_DESIGN_OWNER_STEP) + tenant_creation = find_step(document, GAME_TENANT_CREATION_STEP) + authored_source = find_step(document, GAME_AUTHORED_WORLD_SOURCE_STEP) + capture = find_step(document, GAME_DESIGN_CAPTURE_STEP) + later_selector = find_step(document, GAME_DESIGN_LATER_SELECTOR_STEP) + owner_index = steps.index(owner) + tenant_index = steps.index(tenant_creation) + source_index = steps.index(authored_source) + capture_index = steps.index(capture) + later_selector_index = steps.index(later_selector) + require( + (tenant_index, source_index, capture_index) + == (owner_index + 1, owner_index + 2, owner_index + 3), + "Game Design fresh tenant and authored-source proof checks must immediately follow the owner component proof", + ) + require(capture_index < later_selector_index, "Game Design owner component reports must be captured before later test selectors") + for proof, suite, cases in ( + (tenant_creation, GAME_TENANT_CREATION_SUITE, GAME_TENANT_CREATION_CASES), + (authored_source, GAME_AUTHORED_WORLD_SOURCE_SUITE, GAME_AUTHORED_WORLD_SOURCE_CASES), + ): + require( + proof.get("if") == "${{ !cancelled() && matrix.module == 'game-design-service' }}", + f"{proof['name']} must run for Game Design unless cancelled", + ) + require("continue-on-error" not in proof, f"{proof['name']} must remain fail-closed") + run = proof.get("run") + require(isinstance(run, str), f"{proof['name']} has no run script") + require("bash dev-tools/validation/inspect-test-results.sh" in run, f"{proof['name']} must use the existing inspector") + require(re.search(r"(?m)^\s*--strict\s*\\?$", run) is not None, f"{proof['name']} must require strict inspection") + require(run.count(f"--require-suite {suite}") == 1, f"{proof['name']} must require exactly one suite") + for case in cases: + require(run.count(case) == 1, f"{proof['name']} must require exactly one execution of {case}") + require(re.search(r"(?m)^\s*game-design-service\s*$", run) is not None, f"{proof['name']} targets the wrong service") + require( + capture.get("if") == "${{ always() && matrix.module == 'game-design-service' }}", + "Game Design owner component reports must still be captured after an earlier proof failure", + ) + require(capture.get("uses", "").startswith("actions/upload-artifact@"), "Game Design owner component reports must use artifact capture") + validate(workflow) @@ -408,6 +466,20 @@ mutation_must_fail( lambda doc: replace_run(doc, CHECK_STEP, "--no-configuration-cache", ""), ) + +def move_step_after(document, name: str, anchor_name: str) -> None: + steps = document["jobs"]["build-and-test"]["steps"] + step = find_step(document, name) + anchor = find_step(document, anchor_name) + steps.remove(step) + steps.insert(steps.index(anchor) + 1, step) + + +mutation_must_fail( + "Game Design proof moved after a later Gradle selector", + lambda doc: move_step_after(doc, GAME_TENANT_CREATION_STEP, GAME_DESIGN_LATER_SELECTOR_STEP), +) + print("CI UUID migration proof workflow contract checks passed") PY diff --git a/dev-tools/tests/minio-pr-smoke-bootstrap-contract.sh b/dev-tools/tests/minio-pr-smoke-bootstrap-contract.sh index 2c64a1e82a..5b1a36450b 100644 --- a/dev-tools/tests/minio-pr-smoke-bootstrap-contract.sh +++ b/dev-tools/tests/minio-pr-smoke-bootstrap-contract.sh @@ -84,7 +84,21 @@ require_contains "$classifier" 'changed_paths="$(git diff --name-only "$BASE_SHA require_contains "$classifier" '"$BASE_REF" == main || "$BASE_REF" == develop' require_contains "$classifier" 'docker/minio/*|dev-tools/minio/*) has_source_change=true' require_contains "$classifier" '.github/workflows/build-trusted-minio-source-images.yml) has_workflow_change=true' -require_contains "$classifier" 'if [[ "$has_source_change" == true && "$has_workflow_change" == false ]]; then' +require_count "$trusted_builder" 'services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationMinioPostgresIntegrationTest.java' 3 +require_contains "$classifier" 'if [[ "$has_source_change" == true && "$has_workflow_change" == false && "$has_asset_export_change" == false ]]; then' +require_contains "$classifier" 'has_asset_export_change=true' +require_contains "$build_job" 'Prove Game Design asset export against source-built MinIO' +require_contains "$build_job" './gradlew --rerun-tasks' +require_contains "$build_job" ':game-design-service:test' +require_contains "$build_job" '--tests '\''net.firedevops.firemud.gamedesign.service.AssetExportServiceMinioIntegrationTest'\''' +require_contains "$build_job" ':game-design-service:integrationTest' +require_contains "$build_job" "--tests 'net.firedevops.firemud.gamedesign.service.VersionAssetPublicationMinioPostgresIntegrationTest'" +require_contains "$build_job" '--require-suite net.firedevops.firemud.gamedesign.service.VersionAssetPublicationMinioPostgresIntegrationTest' +require_contains "$build_job" '--require-case '\''net.firedevops.firemud.gamedesign.service.AssetExportServiceMinioIntegrationTest#publishesConditionallyReadsBackExactBytesAndRecoversCommittedPutAgainstMinio()'\''' +require_contains "$build_job" '--require-case '\''net.firedevops.firemud.gamedesign.service.VersionAssetPublicationMinioPostgresIntegrationTest#composesPostgresSnapshotAndCandidateWithMinioBeforeWriteAndRetriesAfterLostAcknowledgement()'\''' +require_contains "$build_job" 'container_created=false' +require_contains "$build_job" 'if [[ "$container_created" == true ]]; then' +require_contains "$build_job" 'build/test-results/integrationTest/*VersionAssetPublicationMinioPostgresIntegrationTest*.xml' require_contains "$classifier" 'should_build=false' require_contains "$build_job" 'needs: classify' require_contains "$build_job" "if: needs.classify.outputs.should_build == 'true'" diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 926cb684a4..fd063f377b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -498,6 +498,89 @@ grep -Fq "name: \${{ github.event_name == 'pull_request' && github.event.action tmp_dir="$(mktemp -d)" trap 'rm -rf "$tmp_dir"' EXIT + +# The Smoke consumer must outlive its producer and still terminate fail closed. +smoke_clock_fixture="$tmp_dir/smoke-clock.js" +python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' +from pathlib import Path +import re +import sys +import yaml + +root = Path(sys.argv[1]) +smoke = yaml.load((root / ".github/workflows/smoke.yml").read_text(), Loader=yaml.BaseLoader) +producer = yaml.load((root / ".github/workflows/runtime-images.yml").read_text(), Loader=yaml.BaseLoader) +job = smoke["jobs"]["smoke-gate"] +script = next(step["with"]["script"] for step in job["steps"] if step.get("name") == "Track full-stack smoke result from Build Runtime Images") +producer_minutes = int(re.search(r"const producerTimeoutMinutes = ([0-9]+);", script)[1]) +overhead_minutes = int(re.search(r"const prerequisiteAndQueueAllowanceMinutes = ([0-9]+);", script)[1]) +if producer_minutes != int(producer["jobs"]["pr-local-smoke"]["timeout-minutes"]): + raise SystemExit("Smoke polling producer budget must match the actual full-stack producer timeout") +if overhead_minutes != 45 or int(job["timeout-minutes"]) < producer_minutes + overhead_minutes + 5: + raise SystemExit("Smoke polling must retain bounded scheduling overhead and five-minute job margin") +if "const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000;" not in script: + raise SystemExit("Smoke polling deadline must use the checked producer and overhead authorities") +Path(sys.argv[2]).write_text(script) +PY + +node - "$smoke_clock_fixture" <<'NODE' +const assert = require("node:assert/strict"); +const script = require("node:fs").readFileSync(process.argv[2], "utf8"); +const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40); +const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; +const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, + payload: { pull_request: { number: 42, head: { sha: head }, base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; +const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); +async function scenario(outcome, completedAtMinutes) { + let now = 1000; + const start = now; + const failures = []; + const listRuns = async () => {}, listJobs = async () => {}; + const github = { rest: { + pulls: { get: async () => ({ data: { state: "open", head: { sha: head }, base: { ref: "develop", sha: base }, merge_commit_sha: merge } }) }, + repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, + actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs }, + }, paginate: async (method, input) => { + assert.equal(method, listJobs); + assert.equal(input.run_id, 42); + return [{ name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", + steps: [{ name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success" }] }]; + } }; + github.paginate.iterator = async function* (method, input) { + assert.equal(method, listRuns); + assert.equal(input.workflow_id, "runtime-images.yml"); + if (input.event === "repository_dispatch") { yield { data: [] }; return; } + assert.equal(input.head_sha, head); + const complete = now - start >= completedAtMinutes * 60 * 1000; + yield { data: [{ id: 42, event: "pull_request", head_sha: head, display_title: title, pull_requests: [], + status: complete ? "completed" : "in_progress", conclusion: complete ? outcome : null }] }; + }; + const core = { info: () => {}, warning: () => {}, setFailed: message => failures.push(message) }; + const clock = { now: () => now, parse: Date.parse }; + const sleep = (callback, duration) => { now += duration; queueMicrotask(callback); }; + await execute(github, context, core, clock, sleep); + return { failures, minutes: (now - start) / 60000 }; +} +(async () => { + const success = await scenario("success", 30); + assert.deepEqual(success.failures, [], "exact producer success after 25 minutes must be admitted"); + assert.equal(success.minutes, 30); + const failed = await scenario("failure", 30); + assert.equal(failed.failures.length, 1); + assert.match(failed.failures[0], /did not complete successfully/); + assert.equal(failed.minutes, 30, "terminal failure must stop polling promptly"); + const cancelled = await scenario("cancelled", 0); + assert.equal(cancelled.failures.length, 1); + assert.match(cancelled.failures[0], /cancelled/i); + assert.ok(cancelled.minutes <= 5.25, "cancelled source without an exact replacement remains bounded"); + const deadline = await scenario("success", Infinity); + assert.equal(deadline.failures.length, 1); + assert.match(deadline.failures[0], /Timed out waiting for the exact/); + assert.equal(deadline.minutes, 90, "active producers cannot escape the total deadline"); + console.log("Smoke clock contract passed: late success, prompt failure, bounded cancellation and deadline"); +})().catch(error => { console.error(error); process.exitCode = 1; }); +NODE + cat >"$tmp_dir/gh" <<'EOF' #!/usr/bin/env bash set -euo pipefail diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index e27cbf79e0..affc4ae136 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -334,6 +334,44 @@ for path in "$ci_path" "$security_path" "$smoke_path"; do require_contains "$path" 'types: [opened, synchronize, reopened, edited]' done +# Optional native-PR comments cannot delay cancellation or require fork/bot write tokens. +python3 - "$ROOT_DIR" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +root = Path(sys.argv[1]) +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +for filename, jobs in { + "ci.yml": ("validation-summary",), + "security.yml": ("security-summary",), + "smoke.yml": ("smoke-summary-pending", "smoke-summary"), +}.items(): + workflow = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) + for job in jobs: + condition = workflow["jobs"][job]["if"] + if condition != expected: + raise SystemExit(f"{filename}/{job} must retain the cancellation, trust and substantive-event condition") + def eligible(cancelled=False, event="pull_request", head_repo="example/repo", actor="contributor", action="synchronize", base_ref=None): + expression = condition[3:-3].replace("!cancelled()", str(not cancelled)) + values = { + "github.event.pull_request.head.repo.full_name": head_repo, + "github.event.changes.base.ref": base_ref, + "github.event_name": event, + "github.repository": "example/repo", + "github.actor": actor, + "github.event.action": action, + } + for key, value in values.items(): + expression = expression.replace(key, repr(value)) + return eval(expression.replace("&&", "and").replace("||", "or").replace("null", "None"), {"__builtins__": {}}) + if not eligible() or not eligible(action="edited", base_ref="develop"): + raise SystemExit(f"{job} must report ordinary results and base retargets") + for arguments in ({"cancelled": True}, {"head_repo": "fork/repo"}, {"actor": "dependabot[bot]"}, {"action": "edited"}, {"event": "push"}): + if eligible(**arguments): + raise SystemExit(f"{job} permits an ineligible comment mutation: {arguments}") +PYTHON + # Metadata-only edits get distinct optional summary contexts; substantive events # retain each summary's canonical name. # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. @@ -1503,6 +1541,15 @@ runtime_service = "services/account-service/src/Main.java" assert run_scope([controller_service]) == {"run_smoke_full": "false"} assert run_scope([controller_smoke_script]) == {"run_smoke_full": "false"} +# Source-built MinIO helpers must require runtime proof even when no Dockerfile changes. +root = Path(sys.argv[1]).resolve().parents[2] +preview_resolver = (root / "dev-tools/hosted/preview/resolve-preview-image-tag.sh").read_text() +preview_predicate = preview_resolver[preview_resolver.index("runtime_relevant() {"):preview_resolver.index('\nif [[ -n "${pr_number}"')] +for helper in ("dev-tools/minio/base_image_refs.py", "dev-tools/minio/build-and-smoke-images.sh"): + assert run_scope([helper]) == {"run_smoke_full": "true"}, helper + preview = subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", helper], check=False) + assert preview.returncode == 0, helper +assert subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", "design/example.md"], check=False).returncode != 0 assert run_scope([runtime_service]) == {"run_smoke_full": "true"} assert run_scope([controller_service, runtime_service]) == {"run_smoke_full": "true"} PY @@ -1973,6 +2020,7 @@ const scripts = JSON.parse(process.env.SMOKE_SUMMARY_SCRIPTS); const context = { repo: { owner: "example", repo: "firemud" }, issue: { number: 42 }, + payload: { pull_request: { head: { sha: "h" }, base: { ref: "develop", sha: "b" } } }, }; async function checkSummary(jobName, script) { @@ -2005,13 +2053,16 @@ async function checkSummary(jobName, script) { created_at: "2026-08-01T00:00:00Z", }, ]; - const calls = { paginate: [], operations: [], creates: [] }; + const calls = { paginate: [], operations: [], creates: [], bodies: [] }; + let currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + let readError = null; const listComments = async () => undefined; const github = { rest: { + pulls: { get: async () => { if (readError) throw readError; return { data: currentPullRequest }; } }, issues: { listComments, - updateComment: async ({ comment_id }) => calls.operations.push(`update:${comment_id}`), + updateComment: async ({ comment_id, body }) => { calls.operations.push(`update:${comment_id}`); calls.bodies.push(body); }, deleteComment: async ({ comment_id }) => calls.operations.push(`delete:${comment_id}`), createComment: async (request) => calls.creates.push(request), }, @@ -2025,8 +2076,24 @@ async function checkSummary(jobName, script) { process.env.CHANGES_RESULT = "success"; process.env.RUN_SMOKE_FULL = "true"; process.env.SMOKE_GATE_RESULT = "success"; - const run = new Function("github", "context", `return (async () => {\n${script}\n})()`); - await run(github, context); + const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); + const core = { info: () => {} }; + for (const changed of [ + { state: "closed" }, { head: { sha: "new" } }, + { base: { ref: "main", sha: "b" } }, { base: { ref: "develop", sha: "new" } }, + ]) { + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request), ...changed }; + await run(github, context, core); + assert.deepEqual(calls.paginate, [], `${jobName} must not list stale comments`); + assert.deepEqual(calls.operations, [], `${jobName} must not mutate stale comments`); + assert.deepEqual(calls.creates, [], `${jobName} must not create stale comments`); + } + readError = new Error("PR guard unavailable"); + await assert.rejects(run(github, context, core), /PR guard unavailable/); + assert.deepEqual(calls.paginate, [], `${jobName} guard errors must fail closed`); + readError = null; + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + await run(github, context, core); assert.equal(calls.paginate.length, 1, `${jobName} must paginate once`); assert.equal(calls.paginate[0].method, listComments, `${jobName} must paginate issue comments`); @@ -2037,6 +2104,10 @@ async function checkSummary(jobName, script) { `${jobName} must update the oldest bot summary before deleting later duplicates`, ); assert.deepEqual(calls.creates, [], `${jobName} must not create another summary`); + process.env.CHANGES_RESULT = "failure"; + process.env.SMOKE_GATE_RESULT = "failure"; + await run(github, context, core); + assert.ok(calls.bodies.at(-1).includes("failure"), `${jobName} must report failed dependencies`); } (async () => { diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 1bbb114fab..c8a2009a3c 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -159,7 +159,7 @@ cat > "$artifact_dir/pr-runtime-provenance.json" < "$fixture_dir/source-run.json" < "$fixture_dir/pull-request.json" <&2 + exit 1 + fi + python3 - "$fixture_dir/source-run.json" "$source_title" <<'PY' +import json +import sys +from pathlib import Path +p = Path(sys.argv[1]); data = json.loads(p.read_text()); data["name"] = "Build Runtime Images"; data["display_title"] = sys.argv[2]; p.write_text(json.dumps(data)) +PY +done run_validation grep -Fxq "IMAGE_TAG=pr-merge-$merge_sha" "$fixture_dir/github-env" grep -Fxq "PR_RUNTIME_ARTIFACT_DIR=$artifact_dir" "$fixture_dir/github-env" diff --git a/dev-tools/tests/security-summary-contract.sh b/dev-tools/tests/security-summary-contract.sh index 1164ed55ee..56120dc56b 100644 --- a/dev-tools/tests/security-summary-contract.sh +++ b/dev-tools/tests/security-summary-contract.sh @@ -15,6 +15,18 @@ grep -Fq 'currentPullRequest.head.sha !== expectedHeadSha' "$workflow" grep -Fq 'currentPullRequest.base.ref !== expectedBaseRef' "$workflow" grep -Fq 'currentPullRequest.base.sha !== expectedBaseSha' "$workflow" +python3 - "$repo_root/.github/workflows/security.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["security-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + test_root="$(mktemp -d)" trap 'rm -rf -- "$test_root"' EXIT script_path="$test_root/security-summary.js" @@ -164,4 +176,43 @@ run(github, context, core).then(async () => { }); NODE +# Execute the checked-in scanner step using the explicit Actions Bash shell. +# The fake scanner and reports stay in one disposable directory; no scan/network occurs. +python3 - "$workflow" "$repo_root/config/security/trivy.yaml" <<'PYTHON' +from pathlib import Path +import os +import subprocess +import sys +import tempfile +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +steps = workflow["jobs"]["trivy-scan"]["steps"] +scanner = next(step for step in steps if step.get("name") == "🔍 Run Trivy and Save Report") +upload = next(step for step in steps if step.get("name") == "📤 Upload Trivy Report") +if scanner.get("shell") != "bash" or upload.get("if") != "always()": + raise SystemExit("Trivy must use explicit pipefail Bash and retain always-uploaded reports") +settings = yaml.safe_load(Path(sys.argv[2]).read_text()) +if settings.get("exit-code") != 1 or settings.get("severity") != ["CRITICAL", "HIGH"] or settings.get("ignore-unfixed") is not True: + raise SystemExit("Trivy failure policy and filters must remain intact") +with tempfile.TemporaryDirectory(prefix="firemud-trivy-pipeline-") as directory: + root = Path(directory) + scanner_path = root / "trivy" + scanner_path.write_text('#!/bin/sh\nprintf "scanner-result-%s\\n" "$FAKE_TRIVY_EXIT"\nexit "$FAKE_TRIVY_EXIT"\n') + scanner_path.chmod(0o755) + for exit_status in (0, 1, 2): + environment = dict(os.environ, PATH=str(root) + os.pathsep + os.environ["PATH"], FAKE_TRIVY_EXIT=str(exit_status)) + # actions/runner explicit shell:bash -> bash --noprofile --norc -e -o pipefail {0}. + script = root / "step.sh" + script.write_text(scanner["run"]) + result = subprocess.run(["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", str(script)], cwd=root, env=environment, capture_output=True, text=True) + if result.returncode != exit_status: + raise SystemExit(f"Trivy exit {exit_status} was masked: {result.returncode}") + if (root / "trivy-report.txt").read_text() != f"scanner-result-{exit_status}\n": + raise SystemExit("tee must retain the report even when the scanner fails") + if ("::endgroup::" in result.stdout) != (exit_status == 0): + raise SystemExit("Failed scanner pipelines must stop the step") +print("Trivy pipeline contract passed: scanner success/vulnerability/error with reports retained") +PYTHON + echo "security summary contract passed" diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 14165090c5..17edc16a3a 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -262,7 +262,7 @@ const context = { payload: { workflow_run: { event: "pull_request", - name: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + name: "CodeQL Analysis", path: ".github/workflows/codeql.yml", head_sha: headSha, head_branch: "feature", @@ -273,7 +273,7 @@ const context = { }; const core = { info: () => {} }; const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); -run(github, context, core).then(() => { +run(github, context, core).then(async () => { if (calls.paginate.length !== 4) throw new Error(`expected four paginated calls, got ${calls.paginate.length}`); if (!calls.paginate.every(({ input }) => input.per_page === 100)) throw new Error("all API listings must request page size 100"); if (calls.updated.length !== 1 || calls.updated[0].comment_id !== 2) throw new Error("oldest bot summary was not updated"); @@ -281,6 +281,12 @@ run(github, context, core).then(() => { if (calls.created.length !== 0) throw new Error("existing bot summary should be updated"); if (!calls.updated[0].body.includes("❌ Static analysis checks failed")) throw new Error("new failure was masked by the older success"); if (!calls.updated[0].body.includes("CodeQL gate: `failure`")) throw new Error("latest CodeQL gate result was not selected"); + context.payload.workflow_run.name = "Forged workflow name"; + await run(github, context, core); + if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + throw new Error("unrelated source names must not query runs or alter comments"); + } + context.payload.workflow_run.name = "CodeQL Analysis"; currentHeadSha = "d".repeat(40); return run(github, context, core).then(() => { if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { @@ -316,6 +322,7 @@ run(github, context, core).then(() => { calls.deleted.length = 0; calls.updated.length = 0; calls.created.length = 0; + context.payload.workflow_run.name = `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`; deleteStatus = 404; return run(github, context, core).then(() => { if (calls.deleted.length !== 1 || calls.deleted[0] !== 3) { diff --git a/docker/minio/README.md b/docker/minio/README.md index 81766a56f6..8a547f36e3 100644 --- a/docker/minio/README.md +++ b/docker/minio/README.md @@ -1,8 +1,8 @@ # Trusted MinIO Source Images -The MinIO server and client images are built from upstream's GitHub-verified annotated release tags and pinned peeled source commits. The build checks both the remote tag object and resolved commit before compilation, uses the pinned Go 1.21.13 builder and Alpine runtime digests, and leaves each upstream `go.sum` read-only during compilation. +The MinIO server and client images are built from upstream's GitHub-verified annotated release tags and pinned peeled source commits. The build checks both the remote tag object and resolved commit before compilation, uses the pinned Go 1.27.1 builder (`golang:1.27.1-bookworm@sha256:69a7b9788769bec032d238959b61854e9ae87f57be9029ec04e9885fabf99195`) and Alpine 3.24.2 runtime (`alpine:3.24.2@sha256:294b683cb724975bec92580e1e685676bd4b50bda910ddb8c51d4cabeaec77e6`) images, and leaves each upstream `go.sum` read-only during compilation. -Pull request builds receive only `contents: read`. They build both images locally, verify server health, create the `firemud-assets` bucket with `mc`, and verify its anonymous policy is private. Successful develop-branch builds upload the exact smoke-tested images and image IDs. A separate `workflow_run` publisher checks that the source run was a successful push to the repository's `develop` default branch, validates the source commits and image IDs, then publishes those exact image bytes and attests each pushed digest. +Pull request builds receive only `contents: read`. They build both images locally, verify server health, create the `firemud-assets` bucket with `mc`, and verify its anonymous policy is private. The pinned-source build workflow also runs a focused Game Design AWS SDK exporter proof against a separate ephemeral server from the same locally built MinIO server image; its run-owned bucket is created and removed by the test. Successful develop-branch builds upload the exact smoke-tested images and image IDs. A separate `workflow_run` publisher checks that the source run was a successful push to the repository's `develop` default branch, validates the source commits and image IDs, then publishes those exact image bytes and attests each pushed digest. The publisher summary contains the immutable GHCR references. Runtime manifests and Compose configuration should use those `name@sha256:...` references. The packages must be public for the publisher's anonymous post-push pull check; it fails with the required GitHub Packages visibility action if either package is private. This PR's full-stack Smoke builds and uses the pinned sources locally, without pulling the published packages. diff --git a/protos/game-design/v1/game_design_service.proto b/protos/game-design/v1/game_design_service.proto index 8d50710d63..63a04c8581 100644 --- a/protos/game-design/v1/game_design_service.proto +++ b/protos/game-design/v1/game_design_service.proto @@ -563,6 +563,17 @@ message PublishedReleaseBundle { string published_release_bundle_ref = 17; string canonical_tenant_id = 18; string canonical_version_id = 19; + optional int32 manifest_schema_version = 20; + repeated PublishedArtifactDigest artifact_digests = 21; +} + +message PublishedArtifactDigest { + string usage_key = 1; + string artifact_kind = 2; + string immutable_object_key = 3; + string content_digest = 4; + string content_type = 5; + int32 artifact_schema_version = 6; } message LaunchDescriptor { @@ -655,6 +666,7 @@ message ParticipantDigest { string applied_commit_id = 3; string content_digest = 4; int32 digest_schema_version = 5; + optional string ability_schema_digest = 6; } enum VersionLifecycleState { diff --git a/protos/game-logic/v1/game_logic_service.proto b/protos/game-logic/v1/game_logic_service.proto index 78c2086459..23a9e583ba 100644 --- a/protos/game-logic/v1/game_logic_service.proto +++ b/protos/game-logic/v1/game_logic_service.proto @@ -274,4 +274,5 @@ message GetDraftDesignDigestResponse { string script_patch_version = 8; } string base_version_id = 9; + optional string ability_schema_digest = 10; } diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/PluginRuntimeStateServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/PluginRuntimeStateServiceImpl.java index e0255ffd99..07e442cf5e 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/PluginRuntimeStateServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/PluginRuntimeStateServiceImpl.java @@ -44,7 +44,7 @@ @Service public class PluginRuntimeStateServiceImpl implements PluginRuntimeStateService { private static final Logger logger = LoggerFactory.getLogger(PluginRuntimeStateServiceImpl.class); - private static final String PARTICIPANT_KEY_AUTOMATION_SCRIPTING = "AUTOMATION_SCRIPTING"; + private static final String PARTICIPANT_KEY_GAME_LOGIC = "GAME_LOGIC"; private static final String ACTOR_POLICY_RECONCILER = "automation-scripting-policy-reconciler"; private static final String DEFAULT_DISABLED_REASON = "not_activated"; private static final String OPERATION_ACTIVATE = "ACTIVATE"; @@ -411,21 +411,44 @@ private void requireAbilitySchemaMatch( throw new IllegalArgumentException( "GAME_INSTANCE_RUNTIME_UNAVAILABLE: " + releaseBundle.getError().getMessage()); } - ParticipantDigest automationDigest = + if (releaseBundle.getBundle().getVersionId() != runtimeVersionId + || releaseBundle.getBundle().getIsScriptOnly()) { + throw abilitySchemaEvidenceUnavailable(); + } + if (releaseBundle.getBundle().getParticipantDigestsList().stream() + .anyMatch( + participant -> + !PARTICIPANT_KEY_GAME_LOGIC.equals(participant.getParticipantKey()) + && participant.hasAbilitySchemaDigest())) { + throw abilitySchemaEvidenceUnavailable(); + } + List ownerEvidence = releaseBundle.getBundle().getParticipantDigestsList().stream() - .filter( - digest -> PARTICIPANT_KEY_AUTOMATION_SCRIPTING.equals(digest.getParticipantKey())) - .findFirst() - .orElseThrow( - () -> - new IllegalArgumentException( - "PLUGIN_ABILITY_SCHEMA_MISMATCH: runtime ability schema digest is unavailable")); - if (!automationDigest.getContentDigest().equals(pluginAbilitySchemaDigest)) { + .filter(digest -> PARTICIPANT_KEY_GAME_LOGIC.equals(digest.getParticipantKey())) + .toList(); + if (ownerEvidence.size() != 1) { + throw abilitySchemaEvidenceUnavailable(); + } + ParticipantDigest digest = ownerEvidence.get(0); + if (!Long.toString(runtimeVersionId).equals(digest.getScopeValue()) + || digest.getDigestSchemaVersion() != 1 + || digest.getAppliedCommitId().isBlank() + || digest.getContentDigest().isBlank() + || !digest.hasAbilitySchemaDigest() + || digest.getAbilitySchemaDigest().isBlank()) { + throw abilitySchemaEvidenceUnavailable(); + } + if (!digest.getAbilitySchemaDigest().equals(pluginAbilitySchemaDigest)) { throw new IllegalArgumentException( "PLUGIN_ABILITY_SCHEMA_MISMATCH: plugin ability schema digest does not match runtime version"); } } + private static IllegalArgumentException abilitySchemaEvidenceUnavailable() { + return new IllegalArgumentException( + "PLUGIN_ABILITY_SCHEMA_MISMATCH: runtime ability schema digest is unavailable"); + } + @Override @Transactional public boolean disable(PluginStateCommand command) { diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImpl.java index a8a8c4d2f1..74769cf17f 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImpl.java @@ -64,7 +64,7 @@ static final class ReplayIdempotencyConflictException extends RuntimeException { } private static final Logger LOGGER = LoggerFactory.getLogger(ScriptWorkItemServiceImpl.class); - private static final String PARTICIPANT_KEY_AUTOMATION_SCRIPTING = "AUTOMATION_SCRIPTING"; + private static final String PARTICIPANT_KEY_GAME_LOGIC = "GAME_LOGIC"; private static final String STATUS_PENDING_EVALUATION = "PENDING_EVALUATION"; private static final String STATUS_EVALUATING = "EVALUATING"; private static final String STATUS_CANCELED = "CANCELED"; @@ -1292,15 +1292,41 @@ private PublicationMetadata publicationMetadata( return new PublicationMetadata(baseVersionId, "", publication); } String abilitySchemaDigest = - releaseBundleResponse.getBundle().getParticipantDigestsList().stream() - .filter( - digest -> PARTICIPANT_KEY_AUTOMATION_SCRIPTING.equals(digest.getParticipantKey())) - .map(ParticipantDigest::getContentDigest) - .findFirst() - .orElse(""); + readAbilitySchemaDigest(releaseBundleResponse.getBundle(), baseVersionId); return new PublicationMetadata(baseVersionId, abilitySchemaDigest, publication); } + private static String readAbilitySchemaDigest( + net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle bundle, long versionId) { + if (bundle.getVersionId() != versionId || bundle.getIsScriptOnly()) { + return ""; + } + if (bundle.getParticipantDigestsList().stream() + .anyMatch( + digest -> + !PARTICIPANT_KEY_GAME_LOGIC.equals(digest.getParticipantKey()) + && digest.hasAbilitySchemaDigest())) { + return ""; + } + List ownerEvidence = + bundle.getParticipantDigestsList().stream() + .filter(digest -> PARTICIPANT_KEY_GAME_LOGIC.equals(digest.getParticipantKey())) + .toList(); + if (ownerEvidence.size() != 1) { + return ""; + } + ParticipantDigest digest = ownerEvidence.get(0); + if (!Long.toString(versionId).equals(digest.getScopeValue()) + || digest.getDigestSchemaVersion() != 1 + || digest.getAppliedCommitId().isBlank() + || digest.getContentDigest().isBlank() + || !digest.hasAbilitySchemaDigest() + || digest.getAbilitySchemaDigest().isBlank()) { + return ""; + } + return digest.getAbilitySchemaDigest(); + } + private PluginRuntimeStateService.PluginPublicationLink pluginPublicationLink( String tenantId, String pluginId, String pluginVersionId) { if (blankToEmpty(pluginId).isBlank() || blankToEmpty(pluginVersionId).isBlank()) { diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginRuntimeStateServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginRuntimeStateServiceImplTest.java index 79a210edf8..889ffca7ce 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginRuntimeStateServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginRuntimeStateServiceImplTest.java @@ -196,8 +196,12 @@ void createsRuntimeActivationState() { .setVersionId(7L) .addParticipantDigests( ParticipantDigest.newBuilder() - .setParticipantKey("AUTOMATION_SCRIPTING") - .setContentDigest("ability-1") + .setParticipantKey("GAME_LOGIC") + .setScopeValue("7") + .setAppliedCommitId("commit-7") + .setDigestSchemaVersion(1) + .setContentDigest("content-7") + .setAbilitySchemaDigest("ability-1") .build()) .build()) .build()); @@ -590,8 +594,12 @@ void alreadyEnabledActivationStoresReceiptWithoutChangingRuntimeState() { .setVersionId(7L) .addParticipantDigests( ParticipantDigest.newBuilder() - .setParticipantKey("AUTOMATION_SCRIPTING") - .setContentDigest("ability-1") + .setParticipantKey("GAME_LOGIC") + .setScopeValue("7") + .setAppliedCommitId("commit-7") + .setDigestSchemaVersion(1) + .setContentDigest("content-7") + .setAbilitySchemaDigest("ability-1") .build()) .build()) .build()); @@ -1309,8 +1317,12 @@ void rejectsActivationWhenBaseVersionDoesNotMatchRuntime() { .setVersionId(7L) .addParticipantDigests( ParticipantDigest.newBuilder() - .setParticipantKey("AUTOMATION_SCRIPTING") - .setContentDigest("ability-1") + .setParticipantKey("GAME_LOGIC") + .setScopeValue("7") + .setAppliedCommitId("commit-7") + .setDigestSchemaVersion(1) + .setContentDigest("content-7") + .setAbilitySchemaDigest("ability-1") .build()) .build()) .build()); @@ -1427,8 +1439,12 @@ void rejectsActivationWhenAbilitySchemaDigestDoesNotMatchRuntimeVersion() { .setVersionId(7L) .addParticipantDigests( ParticipantDigest.newBuilder() - .setParticipantKey("AUTOMATION_SCRIPTING") - .setContentDigest("ability-runtime") + .setParticipantKey("GAME_LOGIC") + .setScopeValue("7") + .setAppliedCommitId("commit-7") + .setDigestSchemaVersion(1) + .setContentDigest("content-7") + .setAbilitySchemaDigest("ability-runtime") .build()) .build()) .build()); @@ -1450,6 +1466,118 @@ void rejectsActivationWhenAbilitySchemaDigestDoesNotMatchRuntimeVersion() { "PLUGIN_ABILITY_SCHEMA_MISMATCH: plugin ability schema digest does not match runtime version"); } + @Test + void rejectsMalformedAbilitySchemaEvidenceBeforeRuntimeMutation() { + ParticipantDigest valid = abilitySchemaParticipant("GAME_LOGIC", "7", "commit-7", 1, true); + ParticipantDigest wrongOwner = + abilitySchemaParticipant("AUTOMATION_SCRIPTING", "7", "commit-7", 1, true); + ParticipantDigest wrongScope = abilitySchemaParticipant("GAME_LOGIC", "8", "commit-7", 1, true); + ParticipantDigest missingCommit = abilitySchemaParticipant("GAME_LOGIC", "7", "", 1, true); + ParticipantDigest unsupportedSchema = + abilitySchemaParticipant("GAME_LOGIC", "7", "commit-7", 2, true); + ParticipantDigest missingAbility = + abilitySchemaParticipant("GAME_LOGIC", "7", "commit-7", 1, false); + + for (List evidence : + List.of( + List.of(), + List.of(wrongOwner), + List.of(valid, wrongOwner), + List.of(valid, valid), + List.of(wrongScope), + List.of(missingCommit), + List.of(unsupportedSchema), + List.of(missingAbility))) { + assertActivationRejectedWithoutMutation(evidence); + } + assertActivationRejectedWithoutMutation(List.of(valid), 8L, false); + assertActivationRejectedWithoutMutation(List.of(valid), 7L, true); + } + + private static void assertActivationRejectedWithoutMutation( + List participantDigests) { + assertActivationRejectedWithoutMutation(participantDigests, 7L, false); + } + + private static void assertActivationRejectedWithoutMutation( + List participantDigests, long releaseVersionId, boolean scriptOnly) { + PluginRuntimeStateRepository repository = Mockito.mock(PluginRuntimeStateRepository.class); + PluginRuntimeEventRepository eventRepository = Mockito.mock(PluginRuntimeEventRepository.class); + GameDesignControlPlaneClient gameDesignClient = + Mockito.mock(GameDesignControlPlaneClient.class); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + ScriptScheduleInstanceService scheduleService = + Mockito.mock(ScriptScheduleInstanceService.class); + PluginActivationPreflightService preflightService = + Mockito.mock(PluginActivationPreflightService.class); + when(gameDesignClient.getPublishedPluginVersion("1", "plugin-1", "plugin-v1")) + .thenReturn( + publishedPluginVersion( + PluginComponentPolicyDecision.PLUGIN_COMPONENT_POLICY_DECISION_ALLOWED, false)); + GetGameInstanceRuntimeStateResponse runtimeState = + GetGameInstanceRuntimeStateResponse.newBuilder() + .setRuntimeState( + GameInstanceRuntimeState.newBuilder() + .setTenantId("1") + .setGameInstanceId("game-1") + .setRegionId("region-7") + .setRegionEpoch(12L) + .setRuntimeVersionId("7") + .setStatus("RUNNING") + .build()) + .build(); + when(gameSessionClient.getGameInstanceRuntimeState("1", "game-1", "")).thenReturn(runtimeState); + when(gameSessionClient.getGameInstanceRuntimeState("1", "game-1", "region-7")) + .thenReturn(runtimeState); + PublishedReleaseBundle.Builder releaseBundle = + PublishedReleaseBundle.newBuilder() + .setVersionId(releaseVersionId) + .setIsScriptOnly(scriptOnly); + participantDigests.forEach(releaseBundle::addParticipantDigests); + when(gameDesignClient.getPublishedReleaseBundle("1", 7L)) + .thenReturn( + GetPublishedReleaseBundleResponse.newBuilder().setBundle(releaseBundle).build()); + PluginRuntimeStateService service = + new PluginRuntimeStateServiceImpl( + repository, + eventRepository, + gameDesignClient, + gameSessionClient, + scheduleService, + preflightService, + null); + + assertThatThrownBy( + () -> + service.setActiveVersion( + new PluginRuntimeStateService.ActivationCommand( + "1", "game-1", "plugin-1", "plugin-v1", "req-1", "admin", "activation"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("PLUGIN_ABILITY_SCHEMA_MISMATCH: runtime ability schema digest is unavailable"); + Mockito.verify(repository, Mockito.never()).save(Mockito.any()); + Mockito.verifyNoInteractions(eventRepository, scheduleService, preflightService); + } + + private static ParticipantDigest abilitySchemaParticipant( + String participantKey, + String scopeValue, + String appliedCommitId, + int digestSchemaVersion, + boolean includeAbilitySchemaDigest) { + ParticipantDigest.Builder digest = + ParticipantDigest.newBuilder() + .setParticipantKey(participantKey) + .setScopeValue(scopeValue) + .setAppliedCommitId(appliedCommitId) + .setDigestSchemaVersion(digestSchemaVersion) + .setContentDigest("content-" + scopeValue); + if (includeAbilitySchemaDigest) { + digest.setAbilitySchemaDigest("ability-1"); + } + return digest.build(); + } + @Test void reconciliationDisablesActivePluginWhenSignerIsRevoked() { PluginRuntimeState active = activePluginState(); @@ -2202,8 +2330,12 @@ void activationAlreadyAppliedFromFreshRequestIsMutationFree() { .setVersionId(7L) .addParticipantDigests( ParticipantDigest.newBuilder() - .setParticipantKey("AUTOMATION_SCRIPTING") - .setContentDigest("ability-1") + .setParticipantKey("GAME_LOGIC") + .setScopeValue("7") + .setAppliedCommitId("commit-7") + .setDigestSchemaVersion(1) + .setContentDigest("content-7") + .setAbilitySchemaDigest("ability-1") .build()) .build()) .build()); diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImplTest.java index ae0417495d..18274d69ca 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImplTest.java @@ -535,10 +535,15 @@ private static GameDesignControlPlaneClient gameDesignClient() { GetPublishedReleaseBundleResponse.newBuilder() .setBundle( PublishedReleaseBundle.newBuilder() + .setVersionId(7L) .addParticipantDigests( ParticipantDigest.newBuilder() - .setParticipantKey("AUTOMATION_SCRIPTING") - .setContentDigest("ability-1") + .setParticipantKey("GAME_LOGIC") + .setScopeValue("7") + .setAppliedCommitId("commit-7") + .setDigestSchemaVersion(1) + .setContentDigest("content-7") + .setAbilitySchemaDigest("ability-1") .build()) .build()) .build()); @@ -2003,6 +2008,56 @@ void summarizesPatchStatusFromReadinessProjection() { verify(gameDesignControlPlaneClient).getPublishedScriptPatchVersion("1", 7L, "patch-1"); } + @Test + void patchStatusDoesNotUseAutomationParticipantDigestAsAbilitySchemaEvidence() { + ScriptPatchReadinessProjectionService readinessProjectionService = + Mockito.mock(ScriptPatchReadinessProjectionService.class); + when(readinessProjectionService.getProjection("1", "patch-1")) + .thenReturn( + Optional.of( + new ScriptPatchReadinessProjectionService.ReadinessStatusSummary( + "1", + "patch-1", + 7L, + ScriptPatchStatus.SCRIPT_PATCH_STATUS_READY, + "ready_for_tenant", + "", + 200L))); + GameDesignControlPlaneClient gameDesignControlPlaneClient = gameDesignClient(); + when(gameDesignControlPlaneClient.getPublishedReleaseBundle("1", 7L)) + .thenReturn( + GetPublishedReleaseBundleResponse.newBuilder() + .setBundle( + PublishedReleaseBundle.newBuilder() + .setVersionId(7L) + .addParticipantDigests( + ParticipantDigest.newBuilder() + .setParticipantKey("AUTOMATION_SCRIPTING") + .setContentDigest("aggregate-content-digest") + .build()) + .build()) + .build()); + ScriptWorkItemService service = + service( + Mockito.mock(ScriptWorkItemRepository.class), + Mockito.mock(ScriptEventAuditRepository.class), + ingressAuditRepository(), + Mockito.mock(ScriptHandoffEventRepository.class), + outboxProperties(), + admissionStateService(), + Mockito.mock(ScriptPatchPinProjectionService.class), + rolloutProjectionService(), + Mockito.mock(PluginRuntimeStateService.class), + gameDesignControlPlaneClient, + readinessProjectionService); + + Optional status = + service.getPatchStatus("1", "patch-1"); + + assertThat(status).isPresent(); + assertThat(status.get().abilitySchemaDigest()).isEmpty(); + } + @Test void listsPatchStatusesWithFilters() { ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); @@ -3287,10 +3342,15 @@ void listDeadLettersUsesTheWorkItemsRetainedPatchBase() { GetPublishedReleaseBundleResponse.newBuilder() .setBundle( PublishedReleaseBundle.newBuilder() + .setVersionId(11L) .addParticipantDigests( ParticipantDigest.newBuilder() - .setParticipantKey("AUTOMATION_SCRIPTING") - .setContentDigest("ability-1") + .setParticipantKey("GAME_LOGIC") + .setScopeValue("11") + .setAppliedCommitId("commit-11") + .setDigestSchemaVersion(1) + .setContentDigest("content-11") + .setAbilitySchemaDigest("ability-1") .build()) .build()) .build()); 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..85f3db1929 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 @@ -85,9 +85,11 @@ public PublishParticipantDigestDto getDraftDesignDigestForVersion( return new PublishParticipantDigestDto( "GAME_LOGIC", response.getVersionId(), + null, response.getAppliedCommitId(), response.getContentDigest(), response.getDigestSchemaVersion(), + response.hasAbilitySchemaDigest() ? response.getAbilitySchemaDigest() : null, null, null); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/AssetStoreProperties.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/AssetStoreProperties.java index dadeac19cc..0138e93803 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/AssetStoreProperties.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/AssetStoreProperties.java @@ -1,6 +1,5 @@ package net.firedevops.firemud.gamedesign.config; -import jakarta.validation.constraints.Min; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; @@ -9,14 +8,10 @@ @Validated @ConfigurationProperties(prefix = "asset.store") public class AssetStoreProperties { - private static final int DEFAULT_FROZEN_SNAPSHOT_CACHE_MAX_ENTRIES = 256; - private String endpoint; + private String publicBaseUrl; private String bucket; private String region; private String accessKey; private String secretKey; - - @Min(1) - private int frozenSnapshotCacheMaxEntries = DEFAULT_FROZEN_SNAPSHOT_CACHE_MAX_ENTRIES; } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java index 7ac0ba3aaf..3410cbc032 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java @@ -124,10 +124,12 @@ public void run(ApplicationArguments args) { bundle = publishedReleaseBundleRepository.save(bundle); } - VersionAssetArtifact artifact = - versionAssetArtifactRepository - .findByTenantIdAndVersionId(DEMO_TENANT_ID, versionId) - .orElseGet(VersionAssetArtifact::new); + if (versionAssetArtifactRepository + .findByTenantIdAndVersionId(DEMO_TENANT_ID, versionId) + .isPresent()) { + return; + } + VersionAssetArtifact artifact = new VersionAssetArtifact(); artifact.setTenantId(DEMO_TENANT_ID); artifact.setVersionId(versionId); artifact.setExportedVersionNumber(version.getVersionNumber()); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishParticipantDigestDto.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishParticipantDigestDto.java index 8a4f73b3ba..5b44c7f491 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishParticipantDigestDto.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishParticipantDigestDto.java @@ -7,8 +7,30 @@ public record PublishParticipantDigestDto( String appliedCommitId, String contentDigest, Integer digestSchemaVersion, + String abilitySchemaDigest, String errorCode, String errorMessage) { + public PublishParticipantDigestDto( + String participantKey, + String scopeValue, + Long baseVersionId, + String appliedCommitId, + String contentDigest, + Integer digestSchemaVersion, + String errorCode, + String errorMessage) { + this( + participantKey, + scopeValue, + baseVersionId, + appliedCommitId, + contentDigest, + digestSchemaVersion, + null, + errorCode, + errorMessage); + } + /** * Preserve the full-version construction shape while the typed patch scope is introduced. * Full-version digests have no base version and therefore keep this field null. @@ -28,6 +50,7 @@ public PublishParticipantDigestDto( appliedCommitId, contentDigest, digestSchemaVersion, + null, errorCode, errorMessage); } 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 578c29d67a..1358c92f51 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java @@ -3,6 +3,7 @@ import java.time.LocalDateTime; import java.util.List; import java.util.UUID; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; public record PublishedReleaseBundleDto( Long id, @@ -21,12 +22,19 @@ public record PublishedReleaseBundleDto( LocalDateTime publishedAt, UUID canonicalTenantId, UUID canonicalVersionId, - String publishedReleaseBundleRef) { + String publishedReleaseBundleRef, + Integer manifestSchemaVersion, + List artifactDigests) { public PublishedReleaseBundleDto { requiredManifestAssetKeys = List.copyOf(requiredManifestAssetKeys == null ? List.of() : requiredManifestAssetKeys); participantDigests = List.copyOf(participantDigests == null ? List.of() : participantDigests); commandDefinitions = List.copyOf(commandDefinitions == null ? List.of() : commandDefinitions); + if ((manifestSchemaVersion == null) != (artifactDigests == null)) { + throw new IllegalArgumentException( + "Manifest schema and artifact proof must be present together"); + } + artifactDigests = artifactDigests == null ? null : List.copyOf(artifactDigests); } public PublishedReleaseBundleDto( @@ -45,7 +53,9 @@ public PublishedReleaseBundleDto( LocalDateTime publishedAt, UUID canonicalTenantId, UUID canonicalVersionId, - String publishedReleaseBundleRef) { + String publishedReleaseBundleRef, + Integer manifestSchemaVersion, + List artifactDigests) { this( id, tenantId, @@ -63,6 +73,8 @@ public PublishedReleaseBundleDto( publishedAt, canonicalTenantId, canonicalVersionId, - publishedReleaseBundleRef); + publishedReleaseBundleRef, + manifestSchemaVersion, + artifactDigests); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishAttemptParticipantDigest.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishAttemptParticipantDigest.java index 9dea77906a..c7d8e715f3 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishAttemptParticipantDigest.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishAttemptParticipantDigest.java @@ -13,6 +13,7 @@ public class PublishAttemptParticipantDigest { private Long baseVersionId; private String appliedCommitId; private String contentDigest; + private String abilitySchemaDigest; private Integer digestSchemaVersion; private String errorCode; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishedReleaseBundle.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishedReleaseBundle.java index 110d6cea4e..c22a7635e9 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishedReleaseBundle.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishedReleaseBundle.java @@ -16,6 +16,8 @@ public class PublishedReleaseBundle { private String attestationSchemaVersion; private String publishWorkflowId; private String manifestHash; + private Integer manifestSchemaVersion; + private String artifactDigestsJson; private String generationConfigRevision; private String requiredManifestAssetKeysJson; private String participantDigestsJson = "[]"; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/VersionAssetArtifact.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/VersionAssetArtifact.java index 0d026b3526..90ad7a65a2 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/VersionAssetArtifact.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/VersionAssetArtifact.java @@ -17,5 +17,9 @@ public class VersionAssetArtifact { private String lastErrorCode; private String lastErrorMessage; private String exportedManifestAssetKeysJson = "[]"; + private Integer manifestSchemaVersion; + private String artifactDigestsJson; + private String publishedObjectProofsJson; + private Long candidateSnapshotVersionId; private LocalDateTime updatedAt = LocalDateTime.now(); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/model/PublishGateFailureCode.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/model/PublishGateFailureCode.java index 7062b7542a..a9407c4502 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/model/PublishGateFailureCode.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/model/PublishGateFailureCode.java @@ -7,6 +7,8 @@ public enum PublishGateFailureCode { UNSUPPORTED_DIGEST_SCHEMA, MISSING_CONTENT_DIGEST, MISSING_APPLIED_COMMIT, + MISSING_ABILITY_SCHEMA_DIGEST, + ABILITY_SCHEMA_DIGEST_OWNER_MISMATCH, APPLIED_COMMIT_MISMATCH, RECORDED_SCOPE_MISMATCH, RECORDED_DIGEST_SCHEMA_MISMATCH, diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAssetRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAssetRepository.java index 5fb4ca04b7..99fe91853d 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAssetRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAssetRepository.java @@ -50,8 +50,11 @@ public GameAsset save(GameAsset asset) { .set(CONTENT_TYPE, asset.getContentType()) .set(DATA, asset.getData()) .set(CREATED_AT, createdAt) - .returning() + .returning(ID, TENANT_ID, FILE_NAME, CONTENT_TYPE, DATA, CREATED_AT) .fetchOne(); + if (record == null) { + throw new IllegalStateException("Inserted game asset could not be read back"); + } return toEntity(record); } dsl.update(TABLE_REF) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptParticipantDigestRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptParticipantDigestRepository.java index 743a4abbe7..7f8b528cc8 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptParticipantDigestRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptParticipantDigestRepository.java @@ -2,6 +2,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.LocalDateTime; +import java.util.List; import net.firedevops.firemud.gamedesign.entity.PublishAttemptParticipantDigest; import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; import org.jooq.DSLContext; @@ -30,6 +31,8 @@ public class PublishAttemptParticipantDigestRepository { DSL.field(DSL.name("applied_commit_id"), String.class); private static final Field CONTENT_DIGEST = DSL.field(DSL.name("content_digest"), String.class); + private static final Field ABILITY_SCHEMA_DIGEST = + DSL.field(DSL.name("ability_schema_digest"), String.class); private static final Field DIGEST_SCHEMA_VERSION = DSL.field(DSL.name("digest_schema_version"), Integer.class); private static final Field ERROR_CODE = DSL.field(DSL.name("error_code"), String.class); @@ -56,11 +59,24 @@ public PublishAttemptParticipantDigest save(PublishAttemptParticipantDigest dige .set(BASE_VERSION_ID, digest.getBaseVersionId()) .set(APPLIED_COMMIT_ID, digest.getAppliedCommitId()) .set(CONTENT_DIGEST, digest.getContentDigest()) + .set(ABILITY_SCHEMA_DIGEST, digest.getAbilitySchemaDigest()) .set(DIGEST_SCHEMA_VERSION, digest.getDigestSchemaVersion()) .set(ERROR_CODE, digest.getErrorCode()) .set(ERROR_MESSAGE, digest.getErrorMessage()) .set(OBSERVED_AT, observedAt) - .returning() + .returning( + ID, + PUBLISH_ATTEMPT_ID, + PARTICIPANT_KEY, + SCOPE_VALUE, + BASE_VERSION_ID, + APPLIED_COMMIT_ID, + CONTENT_DIGEST, + ABILITY_SCHEMA_DIGEST, + DIGEST_SCHEMA_VERSION, + ERROR_CODE, + ERROR_MESSAGE, + OBSERVED_AT) .fetchOne(); return toEntity(record); } @@ -71,6 +87,7 @@ public PublishAttemptParticipantDigest save(PublishAttemptParticipantDigest dige .set(BASE_VERSION_ID, digest.getBaseVersionId()) .set(APPLIED_COMMIT_ID, digest.getAppliedCommitId()) .set(CONTENT_DIGEST, digest.getContentDigest()) + .set(ABILITY_SCHEMA_DIGEST, digest.getAbilitySchemaDigest()) .set(DIGEST_SCHEMA_VERSION, digest.getDigestSchemaVersion()) .set(ERROR_CODE, digest.getErrorCode()) .set(ERROR_MESSAGE, digest.getErrorMessage()) @@ -80,6 +97,26 @@ public PublishAttemptParticipantDigest save(PublishAttemptParticipantDigest dige return digest; } + public List findByPublishAttemptId(Long publishAttemptId) { + return dsl.select( + ID, + PUBLISH_ATTEMPT_ID, + PARTICIPANT_KEY, + SCOPE_VALUE, + BASE_VERSION_ID, + APPLIED_COMMIT_ID, + CONTENT_DIGEST, + ABILITY_SCHEMA_DIGEST, + DIGEST_SCHEMA_VERSION, + ERROR_CODE, + ERROR_MESSAGE, + OBSERVED_AT) + .from(TABLE_REF) + .where(PUBLISH_ATTEMPT_ID.eq(publishAttemptId)) + .orderBy(ID.asc()) + .fetch(this::toEntity); + } + public void deleteByPublishAttemptId(Long publishAttemptId) { dsl.deleteFrom(TABLE_REF).where(PUBLISH_ATTEMPT_ID.eq(publishAttemptId)).execute(); } @@ -98,6 +135,7 @@ private PublishAttemptParticipantDigest toEntity(Record record) { digest.setBaseVersionId(record.get(BASE_VERSION_ID)); digest.setAppliedCommitId(record.get(APPLIED_COMMIT_ID)); digest.setContentDigest(record.get(CONTENT_DIGEST)); + digest.setAbilitySchemaDigest(record.get(ABILITY_SCHEMA_DIGEST)); digest.setDigestSchemaVersion(record.get(DIGEST_SCHEMA_VERSION)); digest.setErrorCode(record.get(ERROR_CODE)); digest.setErrorMessage(record.get(ERROR_MESSAGE)); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java index 51c60a2779..cb187e11ef 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java @@ -116,8 +116,25 @@ public PublishAttempt save(PublishAttempt attempt) { .set(FAILURE_MESSAGE, attempt.getFailureMessage()) .set(CREATED_AT, JooqPersistenceSupport.toTimestamp(createdAt)) .set(COMPLETED_AT, JooqPersistenceSupport.toTimestamp(attempt.getCompletedAt())) - .returning() + .returning( + ID, + TENANT_ID, + PUBLISH_WORKFLOW_ID, + PUBLISH_TYPE, + STATUS, + VERSION_ID, + VERSION_NUMBER, + SCRIPT_PATCH_VERSION, + BASE_VERSION_ID, + REQUEST_DIGEST, + FAILURE_CODE, + FAILURE_MESSAGE, + CREATED_AT, + COMPLETED_AT) .fetchOne(); + if (record == null) { + throw new IllegalStateException("Publish attempt insert did not return its persisted row"); + } return toEntity(record); } dsl.update(PUBLISH_ATTEMPT_TABLE) 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 68cf5a2407..e14f94b78c 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 @@ -40,6 +40,10 @@ public class PublishedReleaseBundleRepository { DSL.field(DSL.name("publish_workflow_id"), String.class); private static final Field MANIFEST_HASH = DSL.field(DSL.name("manifest_hash"), String.class); + private static final Field MANIFEST_SCHEMA_VERSION = + DSL.field(DSL.name("manifest_schema_version"), Integer.class); + private static final Field ARTIFACT_DIGESTS_JSON = + DSL.field(DSL.name("artifact_digests_json"), String.class); private static final Field GENERATION_CONFIG_REVISION = DSL.field(DSL.name("generation_config_revision"), String.class); private static final Field REQUIRED_MANIFEST_ASSET_KEYS_JSON = @@ -131,6 +135,8 @@ private PublishedReleaseBundle insertNewBundle( .set(ATTESTATION_SCHEMA_VERSION, bundle.getAttestationSchemaVersion()) .set(PUBLISH_WORKFLOW_ID, bundle.getPublishWorkflowId()) .set(MANIFEST_HASH, bundle.getManifestHash()) + .set(MANIFEST_SCHEMA_VERSION, bundle.getManifestSchemaVersion()) + .set(ARTIFACT_DIGESTS_JSON, bundle.getArtifactDigestsJson()) .set(GENERATION_CONFIG_REVISION, bundle.getGenerationConfigRevision()) .set(REQUIRED_MANIFEST_ASSET_KEYS_JSON, bundle.getRequiredManifestAssetKeysJson()) .set(PARTICIPANT_DIGESTS_JSON, bundle.getParticipantDigestsJson()) @@ -210,6 +216,15 @@ private void verifyPersistedSource( || !Objects.equals(persisted.getVersionId(), requested.getVersionId()) || !Objects.equals(persisted.getCanonicalTenantId(), source.canonicalTenantId()) || !Objects.equals(persisted.getCanonicalVersionId(), source.canonicalVersionId()) + || !Objects.equals(persisted.getManifestHash(), requested.getManifestHash()) + || !Objects.equals( + persisted.getManifestSchemaVersion(), requested.getManifestSchemaVersion()) + || !Objects.equals(persisted.getArtifactDigestsJson(), requested.getArtifactDigestsJson()) + || !Objects.equals( + persisted.getRequiredManifestAssetKeysJson(), + requested.getRequiredManifestAssetKeysJson()) + || !Objects.equals( + persisted.getParticipantDigestsJson(), requested.getParticipantDigestsJson()) || !Objects.equals(persisted.getPublishedReleaseBundleRef(), publishedReleaseBundleRef)) { throw new IllegalStateException( "Published release bundle readback does not match its source identity and owner reference"); @@ -235,6 +250,8 @@ private PublishedReleaseBundle toEntity(Record record) { bundle.setAttestationSchemaVersion(record.get(ATTESTATION_SCHEMA_VERSION)); bundle.setPublishWorkflowId(record.get(PUBLISH_WORKFLOW_ID)); bundle.setManifestHash(record.get(MANIFEST_HASH)); + bundle.setManifestSchemaVersion(record.get(MANIFEST_SCHEMA_VERSION)); + bundle.setArtifactDigestsJson(record.get(ARTIFACT_DIGESTS_JSON)); bundle.setGenerationConfigRevision(record.get(GENERATION_CONFIG_REVISION)); bundle.setRequiredManifestAssetKeysJson(record.get(REQUIRED_MANIFEST_ASSET_KEYS_JSON)); bundle.setParticipantDigestsJson(record.get(PARTICIPANT_DIGESTS_JSON)); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepository.java index c92f1271b1..049fb6fb61 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepository.java @@ -40,6 +40,14 @@ public class VersionAssetArtifactRepository { DSL.field(DSL.name("exported_manifest_asset_keys_json"), String.class); private static final Field UPDATED_AT = DSL.field(DSL.name("updated_at"), Timestamp.class); + private static final Field MANIFEST_SCHEMA_VERSION = + DSL.field(DSL.name("manifest_schema_version"), Integer.class); + private static final Field ARTIFACT_DIGESTS_JSON = + DSL.field(DSL.name("artifact_digests_json"), String.class); + private static final Field PUBLISHED_OBJECT_PROOFS_JSON = + DSL.field(DSL.name("published_object_proofs_json"), String.class); + private static final Field CANDIDATE_SNAPSHOT_VERSION_ID = + DSL.field(DSL.name("candidate_snapshot_version_id"), Long.class); private final DSLContext dsl; @@ -56,6 +64,15 @@ public Optional findByTenantIdAndVersionId( .fetchOne(this::toEntity)); } + public Optional findByTenantIdAndVersionIdForUpdate( + String tenantId, Long versionId) { + return Optional.ofNullable( + dsl.selectFrom(TABLE_REF) + .where(TENANT_ID.eq(tenantId).and(VERSION_ID.eq(versionId))) + .forUpdate() + .fetchOne(this::toEntity)); + } + public VersionAssetArtifact save(VersionAssetArtifact artifact) { LocalDateTime updatedAt = artifact.getUpdatedAt() == null ? LocalDateTime.now() : artifact.getUpdatedAt(); @@ -72,6 +89,10 @@ public VersionAssetArtifact save(VersionAssetArtifact artifact) { .set(LAST_ERROR_CODE, artifact.getLastErrorCode()) .set(LAST_ERROR_MESSAGE, artifact.getLastErrorMessage()) .set(EXPORTED_MANIFEST_ASSET_KEYS_JSON, artifact.getExportedManifestAssetKeysJson()) + .set(MANIFEST_SCHEMA_VERSION, artifact.getManifestSchemaVersion()) + .set(ARTIFACT_DIGESTS_JSON, artifact.getArtifactDigestsJson()) + .set(PUBLISHED_OBJECT_PROOFS_JSON, artifact.getPublishedObjectProofsJson()) + .set(CANDIDATE_SNAPSHOT_VERSION_ID, artifact.getCandidateSnapshotVersionId()) .set(UPDATED_AT, JooqPersistenceSupport.toTimestamp(updatedAt)) .returning(ID) .fetchOne(); @@ -84,20 +105,35 @@ public VersionAssetArtifact save(VersionAssetArtifact artifact) { .orElseThrow( () -> new IllegalStateException("VERSION_ASSET_ARTIFACT_INSERT_READBACK_FAILED")); } - dsl.update(TABLE_REF) - .set(TENANT_ID, artifact.getTenantId()) - .set(VERSION_ID, artifact.getVersionId()) - .set(EXPORTED_VERSION_NUMBER, artifact.getExportedVersionNumber()) - .set(ARTIFACT_STATE, artifact.getArtifactState().name()) - .set(STATE_EPOCH, artifact.getStateEpoch()) - .set(MANIFEST_HASH, artifact.getManifestHash()) - .set(LAST_WORKFLOW_ID, artifact.getLastWorkflowId()) - .set(LAST_ERROR_CODE, artifact.getLastErrorCode()) - .set(LAST_ERROR_MESSAGE, artifact.getLastErrorMessage()) - .set(EXPORTED_MANIFEST_ASSET_KEYS_JSON, artifact.getExportedManifestAssetKeysJson()) - .set(UPDATED_AT, JooqPersistenceSupport.toTimestamp(updatedAt)) - .where(ID.eq(artifact.getId())) - .execute(); + if (artifact.getStateEpoch() <= 0) { + throw new IllegalStateException("ASSET_ARTIFACT_STATE_CONFLICT"); + } + int updated = + dsl.update(TABLE_REF) + .set(TENANT_ID, artifact.getTenantId()) + .set(VERSION_ID, artifact.getVersionId()) + .set(EXPORTED_VERSION_NUMBER, artifact.getExportedVersionNumber()) + .set(ARTIFACT_STATE, artifact.getArtifactState().name()) + .set(STATE_EPOCH, artifact.getStateEpoch()) + .set(MANIFEST_HASH, artifact.getManifestHash()) + .set(LAST_WORKFLOW_ID, artifact.getLastWorkflowId()) + .set(LAST_ERROR_CODE, artifact.getLastErrorCode()) + .set(LAST_ERROR_MESSAGE, artifact.getLastErrorMessage()) + .set(EXPORTED_MANIFEST_ASSET_KEYS_JSON, artifact.getExportedManifestAssetKeysJson()) + .set(MANIFEST_SCHEMA_VERSION, artifact.getManifestSchemaVersion()) + .set(ARTIFACT_DIGESTS_JSON, artifact.getArtifactDigestsJson()) + .set(PUBLISHED_OBJECT_PROOFS_JSON, artifact.getPublishedObjectProofsJson()) + .set(CANDIDATE_SNAPSHOT_VERSION_ID, artifact.getCandidateSnapshotVersionId()) + .set(UPDATED_AT, JooqPersistenceSupport.toTimestamp(updatedAt)) + .where( + ID.eq(artifact.getId()) + .and(TENANT_ID.eq(artifact.getTenantId())) + .and(VERSION_ID.eq(artifact.getVersionId())) + .and(STATE_EPOCH.eq(artifact.getStateEpoch() - 1))) + .execute(); + if (updated != 1) { + throw new IllegalStateException("ASSET_ARTIFACT_STATE_CONFLICT"); + } return findByTenantIdAndVersionId(artifact.getTenantId(), artifact.getVersionId()) .orElseThrow(); } @@ -120,6 +156,10 @@ private VersionAssetArtifact toEntity(Record record) { artifact.setLastErrorCode(record.get(LAST_ERROR_CODE)); artifact.setLastErrorMessage(record.get(LAST_ERROR_MESSAGE)); artifact.setExportedManifestAssetKeysJson(record.get(EXPORTED_MANIFEST_ASSET_KEYS_JSON)); + artifact.setManifestSchemaVersion(record.get(MANIFEST_SCHEMA_VERSION)); + artifact.setArtifactDigestsJson(record.get(ARTIFACT_DIGESTS_JSON)); + artifact.setPublishedObjectProofsJson(record.get(PUBLISHED_OBJECT_PROOFS_JSON)); + artifact.setCandidateSnapshotVersionId(record.get(CANDIDATE_SNAPSHOT_VERSION_ID)); artifact.setUpdatedAt(JooqPersistenceSupport.toLocalDateTime(record.get(UPDATED_AT))); return artifact; } 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 new file mode 100644 index 0000000000..ed7bdad80f --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java @@ -0,0 +1,570 @@ +package net.firedevops.firemud.gamedesign.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; + +/** Owner-local persistence boundary for Draft asset mappings and durable export snapshots. */ +@Repository +@SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Spring rejects a missing DSLContext before publication; this repository has no finalizer") +public class VersionAssetPublicationRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Comparator UTF8_BYTE_ORDER = + VersionAssetPublicationRepository::compareUtf8; + + private final DSLContext dsl; + + public VersionAssetPublicationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Associates an ordinary source asset with an exact tenant-owned Draft Version. Numeric ids in + * this method are private Game Design owner keys and are not public identity aliases. + */ + public void associateDraftAsset(String tenantId, long versionId, long assetId, String usageType) { + requireTenantId(tenantId); + if (versionId <= 0 || assetId <= 0) { + throw new IllegalArgumentException("Version and asset owner keys must be positive"); + } + + VersionRow version = + lockVersionByTenantAndId(tenantId, versionId) + .orElseThrow(() -> new IllegalStateException("Exact tenant Version row was not found")); + qualifyVersion(version); + requireDraft(version); + requireNoSnapshot(tenantId, versionId); + + AssetRow asset = + findAssetForUpdate(tenantId, assetId) + .orElseThrow( + () -> new IllegalStateException("Exact tenant game asset row was not found")); + validateUsageKey(asset.fileName()); + + Record existing = + dsl.fetchOne( + "SELECT usage_key, usage_type FROM version_asset " + + "WHERE tenant_id = ? AND version_id = ? AND asset_id = ?", + tenantId, + versionId, + assetId); + if (existing != null) { + if (Objects.equals(existing.get("usage_key", String.class), asset.fileName()) + && Objects.equals(existing.get("usage_type", String.class), usageType)) { + return; + } + throw new IllegalStateException("Conflicting Version asset association already exists"); + } + + Record usageCollision = + dsl.fetchOne( + "SELECT asset_id FROM version_asset " + + "WHERE tenant_id = ? AND version_id = ? AND usage_key = ?", + tenantId, + versionId, + asset.fileName()); + if (usageCollision != null) { + throw new IllegalStateException("Version asset usage key is already mapped to another asset"); + } + + dsl.execute( + "INSERT INTO version_asset " + + "(tenant_id, version_id, asset_id, usage_key, usage_type) VALUES (?, ?, ?, ?, ?)", + tenantId, + versionId, + assetId, + asset.fileName(), + usageType); + } + + /** + * Freezes the current exact Draft mapping set or reads an earlier frozen snapshot. The caller + * must hold a transaction because the Version lock serializes mapping writes with first freeze. + */ + public ExportSnapshot freezeOrReadSnapshot(String tenantId, int versionNumber) { + requireTenantId(tenantId); + if (versionNumber <= 0) { + throw new IllegalArgumentException("Version number must be positive"); + } + VersionRow version = + lockVersionByTenantAndVersionNumber(tenantId, versionNumber) + .orElseThrow(() -> new IllegalStateException("Exact tenant Version was not found")); + qualifyVersion(version); + + if (hasSnapshot(tenantId, version.id())) { + return readSnapshot(version); + } + requireDraft(version); + + List selected = lockMappedSourceAssets(tenantId, version.id()); + selected.sort(Comparator.comparing(asset -> asset.usageKey(), UTF8_BYTE_ORDER)); + Set usageKeys = new HashSet<>(); + Set assetIds = new HashSet<>(); + List prepared = new ArrayList<>(selected.size()); + for (SourceAsset source : selected) { + validateUsageKey(source.usageKey()); + if (source.assetId() == null) { + throw new IllegalStateException("Version asset source row identity is missing"); + } + if (!Objects.equals(source.usageKey(), source.fileName())) { + throw new IllegalStateException( + "Version asset usage key no longer matches its source file name"); + } + if (!usageKeys.add(source.usageKey()) || !assetIds.add(source.assetId())) { + throw new IllegalStateException( + "Version asset mapping contains a duplicate source or usage key"); + } + byte[] bytes = requireBytes(source.bytes()); + prepared.add( + new PreparedAsset( + source.usageKey(), + source.assetId(), + requireContentType(source.contentType()), + bytes, + digest(bytes))); + } + + for (PreparedAsset asset : prepared) { + dsl.execute( + "INSERT INTO version_asset_export_item " + + "(tenant_id, version_id, usage_key, asset_id, content_type, content_hash, byte_size) " + + "VALUES (?, ?, ?, ?, ?, ?, ?)", + tenantId, + version.id(), + asset.usageKey(), + asset.assetId(), + asset.contentType(), + asset.contentDigest(), + (long) asset.bytes().length); + } + dsl.execute( + "INSERT INTO version_asset_export_snapshot " + + "(tenant_id, version_id, canonical_tenant_id, canonical_version_id, version_number, " + + "captured_version_state_epoch, item_count) VALUES (?, ?, ?, ?, ?, ?, ?)", + tenantId, + version.id(), + version.canonicalTenantId(), + version.canonicalVersionId(), + version.versionNumber(), + version.stateEpoch(), + prepared.size()); + + return readSnapshot(version); + } + + /** + * Reads only an already committed owner-local snapshot; absence is never interpreted as empty. + */ + public ExportSnapshot readFrozenSnapshot(String tenantId, int versionNumber) { + requireTenantId(tenantId); + if (versionNumber <= 0) { + throw new IllegalArgumentException("Version number must be positive"); + } + VersionRow version = + readVersionByTenantAndVersionNumber(tenantId, versionNumber) + .orElseThrow(() -> new IllegalStateException("Exact tenant Version was not found")); + qualifyVersion(version); + return readSnapshot(version); + } + + private ExportSnapshot readSnapshot(VersionRow version) { + Record header = + dsl.fetchOne( + "SELECT canonical_tenant_id, canonical_version_id, version_number, " + + "captured_version_state_epoch, item_count " + + "FROM version_asset_export_snapshot WHERE tenant_id = ? AND version_id = ?", + version.tenantId(), + version.id()); + if (header == null) { + throw new IllegalStateException("No durable frozen Version asset snapshot exists"); + } + + UUID canonicalTenantId = header.get("canonical_tenant_id", UUID.class); + UUID canonicalVersionId = header.get("canonical_version_id", UUID.class); + Integer storedVersionNumber = header.get("version_number", Integer.class); + Long capturedEpoch = header.get("captured_version_state_epoch", Long.class); + Integer itemCount = header.get("item_count", Integer.class); + if (!Objects.equals(canonicalTenantId, version.canonicalTenantId()) + || !Objects.equals(canonicalVersionId, version.canonicalVersionId()) + || !Objects.equals(storedVersionNumber, version.versionNumber()) + || capturedEpoch == null + || capturedEpoch <= 0 + || version.stateEpoch() < capturedEpoch + || itemCount == null + || itemCount < 0) { + throw new IllegalStateException("Frozen Version asset snapshot identity is inconsistent"); + } + + long mappingCount = + Optional.ofNullable( + dsl.fetchOne( + "SELECT count(*) AS item_count FROM version_asset " + + "WHERE tenant_id = ? AND version_id = ?", + version.tenantId(), + version.id())) + .map(row -> row.get("item_count", Long.class)) + .orElse(0L); + if (mappingCount != itemCount.longValue()) { + throw new IllegalStateException( + "Frozen snapshot no longer matches its complete Version mapping set"); + } + + List rows = + dsl.fetch( + "SELECT i.usage_key AS snapshot_usage_key, i.asset_id AS snapshot_asset_id, " + + "i.content_type AS snapshot_content_type, i.content_hash AS snapshot_content_hash, " + + "i.byte_size AS snapshot_byte_size, va.usage_key AS mapping_usage_key, " + + "va.asset_id AS mapping_asset_id, ga.id AS source_asset_id, " + + "ga.tenant_id AS source_tenant_id, ga.file_name AS source_file_name, " + + "ga.content_type AS source_content_type, ga.data AS source_data " + + "FROM version_asset_export_item i " + + "LEFT JOIN version_asset va ON va.tenant_id = i.tenant_id " + + "AND va.version_id = i.version_id AND va.asset_id = i.asset_id " + + "AND va.usage_key = i.usage_key " + + "LEFT JOIN game_assets ga ON ga.tenant_id = i.tenant_id AND ga.id = i.asset_id " + + "WHERE i.tenant_id = ? AND i.version_id = ?", + version.tenantId(), + version.id()); + if (rows.size() != itemCount) { + throw new IllegalStateException("Frozen Version asset snapshot is incomplete"); + } + + List items = new ArrayList<>(rows.size()); + Set usageKeys = new HashSet<>(); + Set assetIds = new HashSet<>(); + for (Record row : rows) { + String usageKey = row.get("snapshot_usage_key", String.class); + Long snapshotAssetId = row.get("snapshot_asset_id", Long.class); + String snapshotType = row.get("snapshot_content_type", String.class); + String snapshotDigest = row.get("snapshot_content_hash", String.class); + Long snapshotSize = row.get("snapshot_byte_size", Long.class); + Long mappingAssetId = row.get("mapping_asset_id", Long.class); + String mappingUsageKey = row.get("mapping_usage_key", String.class); + Long sourceAssetId = row.get("source_asset_id", Long.class); + String sourceTenantId = row.get("source_tenant_id", String.class); + String sourceFileName = row.get("source_file_name", String.class); + String sourceType = row.get("source_content_type", String.class); + byte[] sourceData = row.get("source_data", byte[].class); + + validateUsageKey(usageKey); + requireContentType(sourceType); + if (snapshotAssetId == null + || snapshotType == null + || snapshotDigest == null + || snapshotSize == null + || !snapshotAssetId.equals(mappingAssetId) + || !Objects.equals(usageKey, mappingUsageKey) + || !snapshotAssetId.equals(sourceAssetId) + || !Objects.equals(version.tenantId(), sourceTenantId) + || !Objects.equals(usageKey, sourceFileName) + || !Objects.equals(snapshotType, sourceType) + || sourceData == null + || snapshotSize != sourceData.length + || !snapshotDigest.equals(digest(sourceData))) { + throw new IllegalStateException( + "Frozen Version asset source bytes or mapping failed verification"); + } + if (!usageKeys.add(usageKey) || !assetIds.add(snapshotAssetId)) { + throw new IllegalStateException( + "Frozen Version asset snapshot contains duplicate keys or sources"); + } + items.add( + new AssetSelection(usageKey, snapshotAssetId, sourceData, sourceType, snapshotDigest)); + } + items.sort(Comparator.comparing(AssetSelection::usageKey, UTF8_BYTE_ORDER)); + + return new ExportSnapshot( + version.tenantId(), + version.id(), + storedVersionNumber, + capturedEpoch, + canonicalTenantId, + canonicalVersionId, + items); + } + + private List lockMappedSourceAssets(String tenantId, long versionId) { + return dsl.fetch( + "SELECT va.usage_key, va.asset_id, ga.file_name, ga.content_type, ga.data " + + "FROM version_asset va " + + "JOIN game_assets ga ON ga.tenant_id = va.tenant_id AND ga.id = va.asset_id " + + "AND ga.file_name = va.usage_key " + + "WHERE va.tenant_id = ? AND va.version_id = ? " + + "ORDER BY va.asset_id FOR UPDATE OF ga", + tenantId, + versionId) + .map( + row -> + new SourceAsset( + row.get("usage_key", String.class), + row.get("asset_id", Long.class), + row.get("file_name", String.class), + row.get("content_type", String.class), + row.get("data", byte[].class))); + } + + private Optional findAssetForUpdate(String tenantId, long assetId) { + Record row = + dsl.fetchOne( + "SELECT file_name FROM game_assets WHERE tenant_id = ? AND id = ? FOR UPDATE", + tenantId, + assetId); + if (row == null) { + return Optional.empty(); + } + return Optional.of(new AssetRow(row.get("file_name", String.class))); + } + + private Optional lockVersionByTenantAndId(String tenantId, long versionId) { + return readVersion( + "SELECT id, tenant_id, version_number, version_state, version_state_epoch, " + + "canonical_tenant_id, canonical_version_id, identity_source_game_row_id, " + + "identity_source_game_tenant_key, identity_source_provenance_kind " + + "FROM version WHERE tenant_id = ? AND id = ? FOR UPDATE", + tenantId, + versionId); + } + + private Optional lockVersionByTenantAndVersionNumber( + String tenantId, int versionNumber) { + return readVersion( + "SELECT id, tenant_id, version_number, version_state, version_state_epoch, " + + "canonical_tenant_id, canonical_version_id, identity_source_game_row_id, " + + "identity_source_game_tenant_key, identity_source_provenance_kind " + + "FROM version WHERE tenant_id = ? AND version_number = ? FOR UPDATE", + tenantId, + versionNumber); + } + + private Optional readVersionByTenantAndVersionNumber( + String tenantId, int versionNumber) { + return readVersion( + "SELECT id, tenant_id, version_number, version_state, version_state_epoch, " + + "canonical_tenant_id, canonical_version_id, identity_source_game_row_id, " + + "identity_source_game_tenant_key, identity_source_provenance_kind " + + "FROM version WHERE tenant_id = ? AND version_number = ?", + tenantId, + versionNumber); + } + + private Optional readVersion(String sql, Object first, Object second) { + Record row = dsl.fetchOne(sql, first, second); + if (row == null) { + return Optional.empty(); + } + return Optional.of( + new VersionRow( + row.get("id", Long.class), + row.get("tenant_id", String.class), + row.get("version_number", Integer.class), + row.get("version_state", String.class), + row.get("version_state_epoch", Long.class), + row.get("canonical_tenant_id", UUID.class), + row.get("canonical_version_id", UUID.class), + row.get("identity_source_game_row_id", Long.class), + row.get("identity_source_game_tenant_key", String.class), + row.get("identity_source_provenance_kind", String.class))); + } + + private void qualifyVersion(VersionRow version) { + if (version.id() == null + || version.id() <= 0 + || version.tenantId() == null + || version.versionNumber() == null + || version.versionNumber() <= 0 + || version.stateEpoch() == null + || version.stateEpoch() <= 0 + || version.canonicalTenantId() == null + || version.canonicalVersionId() == null + || NIL_UUID.equals(version.canonicalTenantId()) + || NIL_UUID.equals(version.canonicalVersionId()) + || version.identitySourceGameRowId() == null + || version.identitySourceGameRowId() <= 0 + || !Objects.equals(version.tenantId(), version.identitySourceGameTenantKey()) + || !("NEW_GAME_ROW".equals(version.identitySourceProvenanceKind()) + || "RETAINED_GAME_V30".equals(version.identitySourceProvenanceKind()))) { + throw new IllegalStateException("Version lacks a complete canonical owner identity"); + } + Record game = + dsl.fetchOne( + "SELECT id, tenant_id, canonical_tenant_id, tenant_identity_provenance_kind, " + + "tenant_identity_source_game_id, tenant_identity_source_legacy_tenant_id " + + "FROM game WHERE id = ? AND tenant_id = ?", + version.identitySourceGameRowId(), + version.identitySourceGameTenantKey()); + if (game == null + || !Objects.equals(game.get("canonical_tenant_id", UUID.class), version.canonicalTenantId()) + || !Objects.equals( + game.get("tenant_identity_provenance_kind", String.class), + version.identitySourceProvenanceKind()) + || !Objects.equals( + game.get("tenant_identity_source_game_id", Long.class), game.get("id", Long.class)) + || !Objects.equals( + game.get("tenant_identity_source_legacy_tenant_id", String.class), + version.tenantId())) { + throw new IllegalStateException( + "Version canonical identity does not match its exact source Game row"); + } + if (version.state() == null) { + throw new IllegalStateException("Version has an unexpected lifecycle state"); + } + try { + net.firedevops.firemud.gamedesign.model.VersionLifecycleState.valueOf(version.state()); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("Version has an unexpected lifecycle state", exception); + } + } + + private void requireDraft(VersionRow version) { + if (!"DRAFT".equals(version.state())) { + throw new IllegalStateException( + "Version asset mappings and first freeze require a Draft Version"); + } + } + + private void requireNoSnapshot(String tenantId, long versionId) { + if (hasSnapshot(tenantId, versionId)) { + throw new IllegalStateException( + "Version asset mappings are frozen by the durable export snapshot"); + } + } + + private boolean hasSnapshot(String tenantId, long versionId) { + return dsl.fetchOne( + "SELECT 1 FROM version_asset_export_snapshot WHERE tenant_id = ? AND version_id = ?", + tenantId, + versionId) + != null; + } + + private static void requireTenantId(String tenantId) { + if (tenantId == null || tenantId.isBlank()) { + throw new IllegalArgumentException("Owner-local tenant key is required"); + } + } + + private static void validateUsageKey(String usageKey) { + if (usageKey == null || usageKey.isBlank()) { + throw new IllegalStateException("Asset source file name cannot be a blank usage key"); + } + if ("manifest.json".equals(usageKey)) { + throw new IllegalStateException( + "Asset source file name collides with the reserved manifest.json key"); + } + } + + private static String requireContentType(String contentType) { + if (contentType == null || contentType.isBlank()) { + throw new IllegalStateException("Asset source content type is missing"); + } + return contentType; + } + + private static byte[] requireBytes(byte[] bytes) { + if (bytes == null) { + throw new IllegalStateException("Asset source bytes are missing"); + } + return bytes.clone(); + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is not available", exception); + } + } + + private static int compareUtf8(String left, String right) { + byte[] leftBytes = left.getBytes(StandardCharsets.UTF_8); + byte[] rightBytes = right.getBytes(StandardCharsets.UTF_8); + int commonLength = Math.min(leftBytes.length, rightBytes.length); + for (int index = 0; index < commonLength; index++) { + int compared = + Integer.compare( + Byte.toUnsignedInt(leftBytes[index]), Byte.toUnsignedInt(rightBytes[index])); + if (compared != 0) { + return compared; + } + } + return Integer.compare(leftBytes.length, rightBytes.length); + } + + private record VersionRow( + Long id, + String tenantId, + Integer versionNumber, + String state, + Long stateEpoch, + UUID canonicalTenantId, + UUID canonicalVersionId, + Long identitySourceGameRowId, + String identitySourceGameTenantKey, + String identitySourceProvenanceKind) {} + + private record AssetRow(String fileName) {} + + private record SourceAsset( + String usageKey, Long assetId, String fileName, String contentType, byte[] bytes) {} + + private record PreparedAsset( + String usageKey, long assetId, String contentType, byte[] bytes, String contentDigest) {} + + /** + * A defensive byte selection persisted in the immutable per-Version export projection. The + * numeric asset id is a private Game Design owner key, not an external identifier. + */ + public record AssetSelection( + String usageKey, long assetId, byte[] bytes, String contentType, String contentDigest) { + public AssetSelection { + Objects.requireNonNull(usageKey, "usageKey"); + Objects.requireNonNull(bytes, "bytes"); + Objects.requireNonNull(contentType, "contentType"); + Objects.requireNonNull(contentDigest, "contentDigest"); + bytes = bytes.clone(); + } + + @Override + public byte[] bytes() { + return bytes.clone(); + } + } + + /** + * Complete owner-local immutable readback for a frozen Version asset selection. Its tenant, + * Version, and asset numeric ids remain private owner keys; canonical UUIDs are read from + * persisted provenance and do not alias those keys. + */ + public record ExportSnapshot( + String tenantId, + long versionId, + int versionNumber, + long capturedVersionStateEpoch, + UUID canonicalTenantId, + UUID canonicalVersionId, + List items) { + public ExportSnapshot { + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(canonicalVersionId, "canonicalVersionId"); + items = List.copyOf(Objects.requireNonNull(items, "items")); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/AssetExportOutcomePendingException.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/AssetExportOutcomePendingException.java new file mode 100644 index 0000000000..3708b6563b --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/AssetExportOutcomePendingException.java @@ -0,0 +1,16 @@ +package net.firedevops.firemud.gamedesign.service; + +/** + * Indicates that an immutable object write may have committed but exact readback is unavailable. + */ +public final class AssetExportOutcomePendingException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + public AssetExportOutcomePendingException(String message, Throwable cause) { + super("ASSET_EXPORT_OUTCOME_PENDING: " + message, cause); + } + + public AssetExportOutcomePendingException(String message) { + super("ASSET_EXPORT_OUTCOME_PENDING: " + message); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/ExportedAssetManifest.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/ExportedAssetManifest.java index 8408f36f1c..6980356347 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/ExportedAssetManifest.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/ExportedAssetManifest.java @@ -1,15 +1,38 @@ package net.firedevops.firemud.gamedesign.service; import java.util.List; +import java.util.Objects; -public record ExportedAssetManifest(String manifestHash, List requiredManifestAssetKeys) { +/** Immutable result of constructing and verifying a version-scoped asset manifest. */ +public record ExportedAssetManifest( + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests) { public ExportedAssetManifest { - requiredManifestAssetKeys = - requiredManifestAssetKeys == null ? List.of() : List.copyOf(requiredManifestAssetKeys); - } + if (manifestHash == null || !manifestHash.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException( + "manifestHash must be a sha256-prefixed lowercase SHA-256 digest"); + } + if (manifestSchemaVersion <= 0) { + throw new IllegalArgumentException("manifestSchemaVersion must be positive"); + } + requiredManifestAssetKeys = List.copyOf(Objects.requireNonNull(requiredManifestAssetKeys)); + artifactDigests = List.copyOf(Objects.requireNonNull(artifactDigests)); - @Override - public List requiredManifestAssetKeys() { - return requiredManifestAssetKeys; + List digestUsageKeys = + artifactDigests.stream().map(PublishedArtifactDigest::usageKey).toList(); + if (!requiredManifestAssetKeys.equals(digestUsageKeys)) { + throw new IllegalArgumentException( + "required manifest keys must exactly match the ordered artifact digest usage keys"); + } + for (int index = 1; index < requiredManifestAssetKeys.size(); index++) { + if (PublishedArtifactDigest.compareUsageKeysUtf8( + requiredManifestAssetKeys.get(index - 1), requiredManifestAssetKeys.get(index)) + >= 0) { + throw new IllegalArgumentException( + "manifest asset keys must be unique and in UTF-8 byte order"); + } + } } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedArtifactDigest.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedArtifactDigest.java new file mode 100644 index 0000000000..515197a302 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedArtifactDigest.java @@ -0,0 +1,62 @@ +package net.firedevops.firemud.gamedesign.service; + +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.StandardCharsets; +import java.util.Objects; + +/** Mandatory actual-byte proof for one immutable published asset object. */ +public record PublishedArtifactDigest( + String usageKey, + String artifactKind, + String immutableObjectKey, + String contentDigest, + String contentType, + int artifactSchemaVersion) { + private static final String SHA256_PREFIX = "sha256:"; + + public PublishedArtifactDigest { + requireCanonicalText(usageKey, "usageKey"); + requireCanonicalText(artifactKind, "artifactKind"); + requireCanonicalText(contentType, "contentType"); + if (artifactSchemaVersion <= 0) { + throw new IllegalArgumentException("artifactSchemaVersion must be positive"); + } + if (contentDigest == null || !contentDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException( + "contentDigest must be a sha256-prefixed lowercase SHA-256 digest"); + } + String expectedObjectKey = + "artifacts/sha256/" + contentDigest.substring(SHA256_PREFIX.length()); + if (!Objects.equals(expectedObjectKey, immutableObjectKey)) { + throw new IllegalArgumentException("immutableObjectKey must address contentDigest"); + } + } + + public static int compareUsageKeysUtf8(String left, String right) { + byte[] leftBytes = left.getBytes(StandardCharsets.UTF_8); + byte[] rightBytes = right.getBytes(StandardCharsets.UTF_8); + int commonLength = Math.min(leftBytes.length, rightBytes.length); + for (int index = 0; index < commonLength; index++) { + int comparison = Byte.compareUnsigned(leftBytes[index], rightBytes[index]); + if (comparison != 0) { + return comparison; + } + } + return Integer.compare(leftBytes.length, rightBytes.length); + } + + private static void requireCanonicalText(String value, String fieldName) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(fieldName + " must be nonblank"); + } + if (value.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException(fieldName + " must not contain control characters"); + } + try { + StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(value)); + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException(fieldName + " must be valid UTF-8 text", exception); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetArtifactService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetArtifactService.java index 53f1c7aadb..bcd9c1ddc9 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetArtifactService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetArtifactService.java @@ -10,6 +10,16 @@ public interface VersionAssetArtifactService { Optional findState(String tenantId, long versionId); + VersionAssetArtifactStateDto stageExport( + String tenantId, long versionId, int versionNumber, String workflowId); + + /** + * Returns the recorded export candidate, or {@code null} when an exact initial STAGED intent has + * not recorded candidate evidence yet. Missing artifacts and malformed or partial evidence are + * errors. + */ + ExportedAssetManifest getExportCandidate(String tenantId, long versionId); + VersionAssetArtifactStateDto markExportedUnattested( String tenantId, long versionId, diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetExportCandidateService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetExportCandidateService.java new file mode 100644 index 0000000000..225c69b46a --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetExportCandidateService.java @@ -0,0 +1,9 @@ +package net.firedevops.firemud.gamedesign.service; + +/** Owner-local immutable candidate evidence committed before any external byte write. */ +public interface VersionAssetExportCandidateService { + ExportedAssetManifest recordExportCandidate( + String tenantId, int versionNumber, ExportedAssetManifest candidate); + + ExportedAssetManifest readExportCandidate(String tenantId, int versionNumber); +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationService.java new file mode 100644 index 0000000000..94c555ffa5 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationService.java @@ -0,0 +1,18 @@ +package net.firedevops.firemud.gamedesign.service; + +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; + +/** Owner-local authoring and durable-readback operations for ordinary Version assets. */ +public interface VersionAssetPublicationService { + /** + * Adds an exact source row to a caller-tenant Draft Version mapping. The tenant string and + * numeric Version/asset ids are private owner keys, not external UUID identity aliases. + */ + void associateDraftAsset(String tenantId, long versionId, long assetId, String usageType); + + /** Freezes the Draft mapping set once, or returns an earlier frozen selection after readback. */ + ExportSnapshot freezeOrReadSnapshot(String tenantId, int versionNumber); + + /** Independently reads and verifies an already committed durable selection. */ + ExportSnapshot readFrozenSnapshot(String tenantId, int versionNumber); +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java index fd21101b9d..05e2c48a38 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java @@ -2,217 +2,516 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.micrometer.core.annotation.Timed; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashSet; import java.util.List; -import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; import net.firedevops.firemud.gamedesign.config.AssetStoreProperties; -import net.firedevops.firemud.gamedesign.entity.GameAsset; -import net.firedevops.firemud.gamedesign.entity.Version; -import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; -import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; -import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.AssetSelection; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; +import net.firedevops.firemud.gamedesign.service.AssetExportOutcomePendingException; import net.firedevops.firemud.gamedesign.service.AssetExportService; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.service.VersionAssetExportCandidateService; +import net.firedevops.firemud.gamedesign.service.VersionAssetPublicationService; import org.springframework.stereotype.Service; +import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.services.s3.model.PutObjectRequest; -import tools.jackson.databind.ObjectMapper; @Service @SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Injected collaborators remain internal service dependencies") + value = "CT_CONSTRUCTOR_THROW", + justification = + "Spring rejects missing collaborators before publication; this bean has no finalizer") public class AssetExportServiceImpl implements AssetExportService { private static final String ASSET_USAGE_KEY_COLLISION = "ASSET_USAGE_KEY_COLLISION"; - private static final String EXPORT_SNAPSHOT_CAPACITY = "EXPORT_SNAPSHOT_CAPACITY"; - private static final String MANIFEST_OBJECT_KEY = "manifest.json"; - private static final String REPAIR_VERSION_SCOPE_UNAVAILABLE = "REPAIR_VERSION_SCOPE_UNAVAILABLE"; + private static final String SNAPSHOT_UNAVAILABLE = "VERSION_ASSET_SNAPSHOT_UNAVAILABLE"; + private static final String SNAPSHOT_MISMATCH = "VERSION_ASSET_SNAPSHOT_MISMATCH"; + private static final String SNAPSHOT_INVALID = "VERSION_ASSET_SNAPSHOT_INVALID"; + private static final String SOURCE_BYTES_MISMATCH = "ASSET_SOURCE_BYTES_MISMATCH"; + private static final String PUBLIC_BASE_URL_INVALID = "ASSET_STORE_PUBLIC_BASE_URL_INVALID"; + private static final String IMMUTABLE_OBJECT_CONFLICT = "IMMUTABLE_OBJECT_CONFLICT"; + private static final String MANIFEST_CONTENT_TYPE = "application/json"; + private static final String MANIFEST_OBJECT_ROOT = "manifests/sha256/"; + private static final String ARTIFACT_OBJECT_ROOT = "artifacts/sha256/"; + private static final UUID NIL_UUID = new UUID(0L, 0L); - private final GameAssetRepository repository; - private final VersionRepository versionRepository; - private final Map frozenSnapshots; + private static final Comparator USAGE_KEY_ORDER = + (left, right) -> + PublishedArtifactDigest.compareUsageKeysUtf8(left.usageKey(), right.usageKey()); + + private final VersionAssetPublicationService publicationService; + + private final VersionAssetExportCandidateService candidateService; @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "S3Client is thread-safe") private final S3Client s3Client; private final AssetStoreProperties properties; - private final ObjectMapper objectMapper; public AssetExportServiceImpl( - GameAssetRepository repository, + VersionAssetPublicationService publicationService, + VersionAssetExportCandidateService candidateService, S3Client s3Client, - AssetStoreProperties properties, - ObjectMapper objectMapper, - VersionRepository versionRepository) { - this.repository = repository; - this.versionRepository = versionRepository; - this.s3Client = s3Client; - this.properties = copyProperties(properties); - this.objectMapper = objectMapper; - this.frozenSnapshots = Collections.synchronizedMap(new LinkedHashMap<>(16, 0.75f, true)); + AssetStoreProperties properties) { + this.publicationService = Objects.requireNonNull(publicationService); + this.candidateService = Objects.requireNonNull(candidateService); + this.s3Client = Objects.requireNonNull(s3Client); + this.properties = copyProperties(Objects.requireNonNull(properties)); } private static AssetStoreProperties copyProperties(AssetStoreProperties source) { AssetStoreProperties copy = new AssetStoreProperties(); copy.setEndpoint(source.getEndpoint()); + copy.setPublicBaseUrl(source.getPublicBaseUrl()); copy.setBucket(source.getBucket()); copy.setRegion(source.getRegion()); copy.setAccessKey(source.getAccessKey()); copy.setSecretKey(source.getSecretKey()); - copy.setFrozenSnapshotCacheMaxEntries(source.getFrozenSnapshotCacheMaxEntries()); return copy; } @Override @Timed("gamedesign.asset.export") - public ExportedAssetManifest exportAssets(String tenantId, int version) { - VersionResolution resolution = resolveVersionScope(tenantId, version); - FrozenAssetSnapshot snapshot = resolveSnapshot(resolution.scope(), resolution.versionState()); - String prefix = tenantId + "/" + version + "/"; - Map manifest = new LinkedHashMap<>(); - ArrayList requiredManifestAssetKeys = new ArrayList<>(); - for (FrozenAsset asset : snapshot.assets()) { - String key = prefix + asset.fileName(); + public ExportedAssetManifest exportAssets(String tenantId, int versionNumber) { + if (tenantId == null || tenantId.isBlank() || versionNumber <= 0) { + throw new IllegalArgumentException("VERSION_ASSET_SNAPSHOT_INVALID: invalid requested scope"); + } + requireObjectStoreBucket(); + + ExportSnapshot frozen = publicationService.freezeOrReadSnapshot(tenantId, versionNumber); + if (frozen == null) { + throw new IllegalStateException(SNAPSHOT_UNAVAILABLE); + } + ExportSnapshot independentlyRead = + publicationService.readFrozenSnapshot(tenantId, versionNumber); + if (independentlyRead == null) { + throw new IllegalStateException(SNAPSHOT_UNAVAILABLE); + } + requireSameSnapshot(frozen, independentlyRead); + List selections = validateAndOrderSnapshot(frozen, tenantId, versionNumber); + + String publicBaseUrl = requireApprovedPublicBaseUrl(); + List artifacts = + selections.stream() + .map( + selection -> prepareArtifact(selection, publicBaseUrl, frozen.canonicalVersionId())) + .toList(); + byte[] manifestBytes = serializeManifest(artifacts); + String manifestHash = "sha256:" + sha256Hex(manifestBytes); + String manifestObjectKey = MANIFEST_OBJECT_ROOT + manifestHash.substring("sha256:".length()); + + List artifactDigests = + artifacts.stream().map(PreparedArtifact::digest).toList(); + List requiredManifestAssetKeys = + artifactDigests.stream().map(PublishedArtifactDigest::usageKey).toList(); + ExportedAssetManifest candidate = + new ExportedAssetManifest(manifestHash, 1, requiredManifestAssetKeys, artifactDigests); + + requireDurableCandidate(tenantId, versionNumber, candidate); + + // Candidate metadata and object proofs are durable before any private object write. + // This producer does not transition lifecycle state or expose a release. + for (PreparedArtifact artifact : artifacts) { + writeAndVerifyImmutableObject( + artifact.digest().immutableObjectKey(), + artifact.bytes(), + artifact.digest().contentType()); + } + writeAndVerifyImmutableObject(manifestObjectKey, manifestBytes, MANIFEST_CONTENT_TYPE); + return candidate; + } + + private void requireDurableCandidate( + String tenantId, int versionNumber, ExportedAssetManifest candidate) { + ExportedAssetManifest recorded; + try { + recorded = candidateService.recordExportCandidate(tenantId, versionNumber, candidate); + } catch (RuntimeException exception) { + throw candidateFailure("record", exception); + } + requireCandidateMatch("record", candidate, recorded); + + ExportedAssetManifest independentlyRead; + try { + independentlyRead = candidateService.readExportCandidate(tenantId, versionNumber); + } catch (RuntimeException exception) { + throw candidateFailure("read", exception); + } + requireCandidateMatch("read", candidate, independentlyRead); + } + + private RuntimeException candidateFailure(String operation, RuntimeException cause) { + if (isCandidateConflict(cause)) { + return cause; + } + return new AssetExportOutcomePendingException( + "export candidate " + operation + " outcome is unresolved", cause); + } + + private void requireCandidateMatch( + String operation, ExportedAssetManifest expected, ExportedAssetManifest actual) { + if (actual == null) { + throw new AssetExportOutcomePendingException( + "export candidate " + operation + " readback is missing"); + } + if (!expected.equals(actual)) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_CONFLICT"); + } + } + + private static boolean isCandidateConflict(RuntimeException exception) { + for (Throwable current = exception; current != null; current = current.getCause()) { + if ("ASSET_EXPORT_CANDIDATE_CONFLICT".equals(current.getMessage())) { + return true; + } + } + return false; + } + + private List validateAndOrderSnapshot( + ExportSnapshot snapshot, String requestedTenantId, int requestedVersionNumber) { + if (!Objects.equals(requestedTenantId, snapshot.tenantId()) + || requestedVersionNumber != snapshot.versionNumber() + || snapshot.versionId() <= 0 + || snapshot.capturedVersionStateEpoch() <= 0 + || !isCanonicalUuid(snapshot.canonicalTenantId()) + || !isCanonicalUuid(snapshot.canonicalVersionId()) + || snapshot.items() == null) { + throw new IllegalStateException(SNAPSHOT_INVALID + ": incomplete or out-of-scope snapshot"); + } + + Set usageKeys = new HashSet<>(); + Set sourceAssetIds = new HashSet<>(); + ArrayList ordered = new ArrayList<>(snapshot.items().size()); + for (AssetSelection selection : snapshot.items()) { + if (selection == null) { + throw new IllegalStateException(SNAPSHOT_INVALID + ": null selection"); + } + String usageKey = selection.usageKey(); + if (usageKey == null || usageKey.isBlank()) { + throw new IllegalStateException(ASSET_USAGE_KEY_COLLISION); + } + requireCanonicalText(usageKey, "usageKey"); + if ("manifest.json".equals(usageKey) || !usageKeys.add(usageKey)) { + throw new IllegalStateException(ASSET_USAGE_KEY_COLLISION); + } + if (selection.assetId() <= 0 + || selection.bytes() == null + || selection.contentType() == null + || selection.contentType().isBlank() + || !selection.contentType().equals(selection.contentType().trim()) + || selection.contentType().contains("\r") + || selection.contentType().contains("\n")) { + throw new IllegalStateException(SNAPSHOT_INVALID + ": incomplete source asset identity"); + } + if (!sourceAssetIds.add(selection.assetId())) { + throw new IllegalStateException(SNAPSHOT_INVALID + ": duplicate source asset identity"); + } + requireCanonicalText(selection.contentType(), "contentType"); + requireCanonicalText(selection.contentDigest(), "contentDigest"); + String actualDigest = "sha256:" + sha256Hex(selection.bytes()); + if (!actualDigest.equals(selection.contentDigest())) { + throw new IllegalStateException(SOURCE_BYTES_MISMATCH); + } + ordered.add(selection); + } + ordered.sort(USAGE_KEY_ORDER); + return List.copyOf(ordered); + } + + private static boolean isCanonicalUuid(UUID value) { + return value != null && !NIL_UUID.equals(value); + } + + private void requireObjectStoreBucket() { + if (properties.getBucket() == null || properties.getBucket().isBlank()) { + throw new IllegalStateException("ASSET_STORE_BUCKET_INVALID"); + } + } + + private static void requireCanonicalText(String value, String fieldName) { + if (value == null || value.isBlank()) { + throw new IllegalStateException(SNAPSHOT_INVALID + ": " + fieldName + " is blank"); + } + if (value.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalStateException( + SNAPSHOT_INVALID + ": " + fieldName + " has control characters"); + } + try { + StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(value)); + } catch (CharacterCodingException exception) { + throw new IllegalStateException( + SNAPSHOT_INVALID + ": " + fieldName + " is not valid UTF-8", exception); + } + } + + private void requireSameSnapshot(ExportSnapshot frozen, ExportSnapshot readback) { + boolean sameScope = + Objects.equals(frozen.tenantId(), readback.tenantId()) + && frozen.versionId() == readback.versionId() + && frozen.versionNumber() == readback.versionNumber() + && frozen.capturedVersionStateEpoch() == readback.capturedVersionStateEpoch() + && Objects.equals(frozen.canonicalTenantId(), readback.canonicalTenantId()) + && Objects.equals(frozen.canonicalVersionId(), readback.canonicalVersionId()); + if (!sameScope || frozen.items() == null || readback.items() == null) { + throw new IllegalStateException(SNAPSHOT_MISMATCH); + } + List frozenItems = frozen.items(); + List readbackItems = readback.items(); + if (frozenItems.size() != readbackItems.size()) { + throw new IllegalStateException(SNAPSHOT_MISMATCH); + } + for (int index = 0; index < frozenItems.size(); index++) { + AssetSelection left = frozenItems.get(index); + AssetSelection right = readbackItems.get(index); + if (left == null + || right == null + || !Objects.equals(left.usageKey(), right.usageKey()) + || left.assetId() != right.assetId() + || !Objects.equals(left.contentType(), right.contentType()) + || !Objects.equals(left.contentDigest(), right.contentDigest()) + || !Arrays.equals(left.bytes(), right.bytes())) { + throw new IllegalStateException(SNAPSHOT_MISMATCH); + } + } + } + + private PreparedArtifact prepareArtifact( + AssetSelection selection, String publicBaseUrl, UUID canonicalVersionId) { + byte[] bytes = selection.bytes(); + String contentHash = sha256Hex(bytes); + String digest = "sha256:" + contentHash; + String immutableObjectKey = ARTIFACT_OBJECT_ROOT + contentHash; + String url = publicBaseUrl + "/" + immutableObjectKey; + + PublishedArtifactDigest artifactDigest = + new PublishedArtifactDigest( + selection.usageKey(), "BINARY", immutableObjectKey, digest, selection.contentType(), 1); + return new PreparedArtifact(artifactDigest, bytes, canonicalVersionId, url); + } + + private static byte[] serializeManifest(List artifacts) { + StringBuilder manifest = new StringBuilder("{\"schemaVersion\":1,\"assets\":{"); + boolean first = true; + for (PreparedArtifact artifact : artifacts) { + if (!first) { + manifest.append(','); + } + first = false; + appendJsonString(manifest, artifact.digest().usageKey()); + manifest.append(":{"); + appendJsonField(manifest, "usageKey", artifact.digest().usageKey(), true); + appendJsonField(manifest, "artifactKind", artifact.digest().artifactKind(), false); + appendJsonField( + manifest, "immutableObjectKey", artifact.digest().immutableObjectKey(), false); + appendJsonField(manifest, "contentDigest", artifact.digest().contentDigest(), false); + appendJsonField(manifest, "contentType", artifact.digest().contentType(), false); + manifest + .append(",\"artifactSchemaVersion\":") + .append(artifact.digest().artifactSchemaVersion()); + appendJsonField(manifest, "producerService", "game-design-service", false); + appendJsonField(manifest, "versionId", artifact.manifestVersionId().toString(), false); + appendJsonField(manifest, "url", artifact.url(), false); + manifest.append('}'); + } + manifest.append("}}"); + return manifest.toString().getBytes(StandardCharsets.UTF_8); + } + + private static void appendJsonField( + StringBuilder json, String key, String value, boolean firstInObject) { + if (!firstInObject) { + json.append(','); + } + appendJsonString(json, key); + json.append(':'); + appendJsonString(json, value); + } + + private static void appendJsonString(StringBuilder json, String value) { + json.append('"'); + for (int offset = 0; offset < value.length(); ) { + int codePoint = value.codePointAt(offset); + switch (codePoint) { + case '"' -> json.append("\\\""); + case '\\' -> json.append("\\\\"); + case '\b' -> json.append("\\b"); + case '\f' -> json.append("\\f"); + case '\n' -> json.append("\\n"); + case '\r' -> json.append("\\r"); + case '\t' -> json.append("\\t"); + default -> { + if (codePoint < 0x20) { + json.append("\\u00"); + json.append(Character.forDigit((codePoint >>> 4) & 0xf, 16)); + json.append(Character.forDigit(codePoint & 0xf, 16)); + } else { + json.appendCodePoint(codePoint); + } + } + } + offset += Character.charCount(codePoint); + } + json.append('"'); + } + + private String requireApprovedPublicBaseUrl() { + String configured = properties.getPublicBaseUrl(); + try { + if (configured == null || configured.isBlank()) { + throw new IllegalArgumentException("missing public base URL"); + } + URI uri = new URI(configured); + String path = uri.getRawPath(); + if (!uri.isAbsolute() + || !"https".equalsIgnoreCase(uri.getScheme()) + || uri.getHost() == null + || uri.getPort() == 0 + || uri.getPort() > 65535 + || uri.getRawUserInfo() != null + || uri.getRawQuery() != null + || uri.getRawFragment() != null + || !("/assets".equals(path) || "/assets/".equals(path))) { + throw new IllegalArgumentException( + "public base URL must be an approved HTTPS /assets origin"); + } + rejectPrivateEndpointAlias(uri); + return "https://" + uri.getRawAuthority() + "/assets"; + } catch (URISyntaxException | IllegalArgumentException exception) { + throw new IllegalStateException(PUBLIC_BASE_URL_INVALID, exception); + } + } + + private void rejectPrivateEndpointAlias(URI publicUri) { + String endpoint = properties.getEndpoint(); + if (endpoint == null || endpoint.isBlank()) { + return; + } + try { + URI privateUri = new URI(endpoint); + if (normalizeHost(publicUri.getHost()).equals(normalizeHost(privateUri.getHost()))) { + throw new IllegalArgumentException( + "public base URL aliases the private object-store endpoint"); + } + } catch (URISyntaxException exception) { + throw new IllegalArgumentException("invalid private object-store endpoint", exception); + } + } + + private static String normalizeHost(String host) { + if (host == null) { + return ""; + } + String normalized = host.toLowerCase(java.util.Locale.ROOT); + return normalized.endsWith(".") ? normalized.substring(0, normalized.length() - 1) : normalized; + } + + private void writeAndVerifyImmutableObject(String key, byte[] bytes, String contentType) { + RuntimeException putFailure = null; + try { s3Client.putObject( PutObjectRequest.builder() .bucket(properties.getBucket()) .key(key) - .contentType(asset.contentType()) + .contentType(contentType) + .contentLength((long) bytes.length) + .ifNoneMatch("*") .build(), - RequestBody.fromBytes(asset.data())); - String url = properties.getEndpoint() + "/" + properties.getBucket() + "/" + key; - manifest.put(asset.fileName(), url); - requiredManifestAssetKeys.add(asset.fileName()); + RequestBody.fromBytes(bytes)); + } catch (RuntimeException exception) { + putFailure = exception; } + try { - String manifestJson = objectMapper.writeValueAsString(manifest); - s3Client.putObject( - PutObjectRequest.builder() - .bucket(properties.getBucket()) - .key(prefix + MANIFEST_OBJECT_KEY) - .contentType("application/json") - .build(), - RequestBody.fromString(manifestJson, StandardCharsets.UTF_8)); - requiredManifestAssetKeys.add(MANIFEST_OBJECT_KEY); - return new ExportedAssetManifest( - sha256(manifestJson), List.copyOf(requiredManifestAssetKeys)); - } catch (Exception e) { - throw new IllegalStateException("Failed to write manifest", e); - } - } - - private VersionResolution resolveVersionScope(String tenantId, int versionNumber) { - Version version = - versionRepository - .findByTenantIdAndVersionNumber(tenantId, versionNumber) - .orElseThrow(() -> new IllegalArgumentException(REPAIR_VERSION_SCOPE_UNAVAILABLE)); - return new VersionResolution( - new VersionScope(tenantId, version.getId(), versionNumber), version.getVersionState()); - } - - private FrozenAssetSnapshot resolveSnapshot( - VersionScope scope, VersionLifecycleState versionState) { - FrozenAssetSnapshot existing = frozenSnapshots.get(scope); - if (existing != null) { - return existing; - } - if (versionState == VersionLifecycleState.PUBLISHED - || versionState == VersionLifecycleState.ACTIVE) { - throw new IllegalStateException(REPAIR_VERSION_SCOPE_UNAVAILABLE); - } - FrozenAssetSnapshot candidate = freeze(repository.findByTenantId(scope.tenantId())); - synchronized (frozenSnapshots) { - FrozenAssetSnapshot concurrent = frozenSnapshots.get(scope); - if (concurrent != null) { - return concurrent; - } - VersionResolution current = resolveVersionScope(scope.tenantId(), scope.versionNumber()); - if (!scope.equals(current.scope()) - || current.versionState() == VersionLifecycleState.PUBLISHED - || current.versionState() == VersionLifecycleState.ACTIVE) { - throw new IllegalStateException(REPAIR_VERSION_SCOPE_UNAVAILABLE); - } - if (frozenSnapshots.size() >= properties.getFrozenSnapshotCacheMaxEntries()) { - throw new IllegalStateException(EXPORT_SNAPSHOT_CAPACITY); - } - frozenSnapshots.put(scope, candidate); - return candidate; - } - } - - private FrozenAssetSnapshot freeze(List assets) { - Map frozenByUsageKey = new LinkedHashMap<>(); - for (GameAsset asset : assets) { - byte[] data = asset.getData(); - FrozenAsset frozen = - new FrozenAsset( - asset.getId(), asset.getFileName(), asset.getContentType(), data, sha256(data)); - if (MANIFEST_OBJECT_KEY.equals(asset.getFileName()) - || frozenByUsageKey.putIfAbsent(asset.getFileName(), frozen) != null) { - throw new IllegalStateException(ASSET_USAGE_KEY_COLLISION); + verifyReadback(key, bytes, contentType); + } catch (ImmutableObjectConflictException conflict) { + if (putFailure != null) { + conflict.addSuppressed(putFailure); } + throw conflict; + } catch (RuntimeException readFailure) { + AssetExportOutcomePendingException pending = + new AssetExportOutcomePendingException( + "exact object readback is unavailable for " + key, readFailure); + if (putFailure != null) { + pending.addSuppressed(putFailure); + } + throw pending; } - return new FrozenAssetSnapshot(List.copyOf(frozenByUsageKey.values())); } - @Override - @Timed("gamedesign.asset.delete") - public void deleteExportedAssets(String tenantId, int version, List manifestAssetKeys) { - String prefix = tenantId + "/" + version + "/"; - for (String assetKey : new LinkedHashSet<>(manifestAssetKeys)) { - s3Client.deleteObject( - DeleteObjectRequest.builder() - .bucket(properties.getBucket()) - .key(prefix + assetKey) - .build()); + private void verifyReadback(String key, byte[] expectedBytes, String expectedContentType) { + ResponseBytes response = + s3Client.getObjectAsBytes( + GetObjectRequest.builder().bucket(properties.getBucket()).key(key).build()); + byte[] actualBytes = response.asByteArray(); + Long actualSize = response.response().contentLength(); + String actualContentType = response.response().contentType(); + if (actualSize == null + || actualSize.longValue() != expectedBytes.length + || !Objects.equals(expectedContentType, actualContentType) + || !Arrays.equals(expectedBytes, actualBytes) + || !sha256Hex(expectedBytes).equals(sha256Hex(actualBytes))) { + throw new ImmutableObjectConflictException(key); } } - private String sha256(String value) { - return sha256(value.getBytes(StandardCharsets.UTF_8)); + @Override + @Timed("gamedesign.asset.delete") + public void deleteExportedAssets(String tenantId, int version, List manifestAssetKeys) { + throw new IllegalStateException( + "CONTENT_ADDRESSED_PURGE_PROOF_REQUIRED: version-scoped deletion cannot select shared immutable objects"); } - private String sha256(byte[] value) { + private static String sha256Hex(byte[] value) { try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - byte[] bytes = digest.digest(value); - StringBuilder builder = new StringBuilder(bytes.length * 2); - for (byte current : bytes) { - builder.append(String.format("%02x", current)); + byte[] hash = MessageDigest.getInstance("SHA-256").digest(value); + StringBuilder result = new StringBuilder(hash.length * 2); + for (byte current : hash) { + result.append(Character.forDigit((current >>> 4) & 0xf, 16)); + result.append(Character.forDigit(current & 0xf, 16)); } - return builder.toString(); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalStateException("SHA-256 unavailable", ex); + return result.toString(); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 unavailable", exception); } } - private record VersionResolution(VersionScope scope, VersionLifecycleState versionState) {} - - private record VersionScope(String tenantId, Long versionId, int versionNumber) {} + private record PreparedArtifact( + PublishedArtifactDigest digest, byte[] bytes, UUID manifestVersionId, String url) { + private PreparedArtifact { + bytes = bytes.clone(); + } - private record FrozenAssetSnapshot(List assets) { - private FrozenAssetSnapshot { - assets = List.copyOf(assets); + @Override + public byte[] bytes() { + return bytes.clone(); } } - private record FrozenAsset( - Long sourceAssetId, String fileName, String contentType, byte[] data, String contentHash) { - private FrozenAsset { - data = data == null ? null : data.clone(); - } + private static final class ImmutableObjectConflictException extends IllegalStateException { + private static final long serialVersionUID = 1L; - @Override - public byte[] data() { - return data == null ? null : data.clone(); + private ImmutableObjectConflictException(String key) { + super( + IMMUTABLE_OBJECT_CONFLICT + ": existing object does not match requested bytes at " + key); } } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java index 8ebdc647c2..2abfb6542c 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java @@ -734,21 +734,29 @@ public void getPublishedReleaseBundle( .addAllParticipantDigests( bundle.participantDigests().stream() .map( - digest -> - net.firedevops.firemud.gamedesign.v1.ParticipantDigest.newBuilder() - .setParticipantKey(digest.participantKey()) - .setScopeValue(digest.scopeValue()) - .setAppliedCommitId( - digest.appliedCommitId() == null - ? "" - : digest.appliedCommitId()) - .setContentDigest( - digest.contentDigest() == null ? "" : digest.contentDigest()) - .setDigestSchemaVersion( - digest.digestSchemaVersion() == null - ? 0 - : digest.digestSchemaVersion()) - .build()) + digest -> { + var participantDigestBuilder = + net.firedevops.firemud.gamedesign.v1.ParticipantDigest.newBuilder() + .setParticipantKey(digest.participantKey()) + .setScopeValue(digest.scopeValue()) + .setAppliedCommitId( + digest.appliedCommitId() == null + ? "" + : digest.appliedCommitId()) + .setContentDigest( + digest.contentDigest() == null + ? "" + : digest.contentDigest()) + .setDigestSchemaVersion( + digest.digestSchemaVersion() == null + ? 0 + : digest.digestSchemaVersion()); + if (digest.abilitySchemaDigest() != null) { + participantDigestBuilder.setAbilitySchemaDigest( + digest.abilitySchemaDigest()); + } + return participantDigestBuilder.build(); + }) .toList()) .setGenerationConfigRevision(bundle.generationConfigRevision()) .setIsScriptOnly(bundle.scriptOnly()) @@ -763,6 +771,26 @@ public void getPublishedReleaseBundle( if (bundle.publishedReleaseBundleRef() != null) { bundleBuilder.setPublishedReleaseBundleRef(bundle.publishedReleaseBundleRef()); } + if (bundle.manifestSchemaVersion() != null) { + if (bundle.manifestSchemaVersion() != 1 || bundle.artifactDigests() == null) { + throw new IllegalStateException( + "SCHEMA_VERSION_UNSUPPORTED: manifest evidence is not readable"); + } + bundleBuilder.setManifestSchemaVersion(bundle.manifestSchemaVersion()); + bundleBuilder.addAllArtifactDigests( + bundle.artifactDigests().stream() + .map( + proof -> + net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest.newBuilder() + .setUsageKey(proof.usageKey()) + .setArtifactKind(proof.artifactKind()) + .setImmutableObjectKey(proof.immutableObjectKey()) + .setContentDigest(proof.contentDigest()) + .setContentType(proof.contentType()) + .setArtifactSchemaVersion(proof.artifactSchemaVersion()) + .build()) + .toList()); + } builder.setBundle(bundleBuilder.build()); } catch (AdminAuthorizationException ex) { builder.setError( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java index 84185929fa..a9ffb64b1d 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java @@ -177,6 +177,7 @@ private PublishAttemptParticipantDigest toEntity( entity.setBaseVersionId(digest.baseVersionId()); entity.setAppliedCommitId(digest.appliedCommitId()); entity.setContentDigest(digest.contentDigest()); + entity.setAbilitySchemaDigest(digest.abilitySchemaDigest()); entity.setDigestSchemaVersion(digest.digestSchemaVersion()); entity.setErrorCode(digest.errorCode()); entity.setErrorMessage(digest.errorMessage()); 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 3fc57daa8b..a6d8ed34b1 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 @@ -173,6 +173,23 @@ public void assertGatePassed( PublishGateFailureCode.APPLIED_COMMIT_MISMATCH, "publish gate failed: applied commit mismatch"); } + participantDigests.forEach( + digest -> { + if (!PublishParticipantKey.GAME_LOGIC.name().equals(digest.participantKey()) + && digest.abilitySchemaDigest() != null) { + throw new PublishGateFailureException( + PublishGateFailureCode.ABILITY_SCHEMA_DIGEST_OWNER_MISMATCH, + "publish gate failed: ability-schema digest was supplied by " + + digest.participantKey()); + } + if (!version.scriptOnly() + && PublishParticipantKey.GAME_LOGIC.name().equals(digest.participantKey()) + && (digest.abilitySchemaDigest() == null || digest.abilitySchemaDigest().isBlank())) { + throw new PublishGateFailureException( + PublishGateFailureCode.MISSING_ABILITY_SCHEMA_DIGEST, + "publish gate failed: missing dedicated ability-schema digest from GAME_LOGIC"); + } + }); } private PublishParticipantDigestDto observeFullVersionParticipant( 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 2ccccc8651..e21fe68126 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 @@ -34,6 +34,12 @@ static void requireSupportedSchemaForLaunch(PublishedReleaseBundleDto bundle) { static void requireExactRepairMatch( PublishedReleaseBundleDto bundle, ExportedAssetManifest exportedManifest) { requireSupportedSchemaForRead(bundle); + if (!Objects.equals(bundle.manifestSchemaVersion(), exportedManifest.manifestSchemaVersion()) + || !Objects.equals(bundle.artifactDigests(), exportedManifest.artifactDigests())) { + throw new IllegalStateException( + REPAIR_ATTESTATION_MISMATCH + + ": repair could not reproduce the attested artifact/schema proof"); + } if (!Objects.equals(bundle.manifestHash(), exportedManifest.manifestHash())) { throw new IllegalStateException( REPAIR_ATTESTATION_MISMATCH + ": repair could not reproduce the attested manifest hash"); 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 96e884a1c4..4abdc4165d 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 @@ -18,6 +18,7 @@ import net.firedevops.firemud.gamedesign.repository.RevisionRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -89,6 +90,9 @@ public PublishedReleaseBundleDto createFullVersionBundle( PublishedReleaseBundleContract.SUPPORTED_ATTESTATION_SCHEMA_VERSION); entity.setPublishWorkflowId(publishWorkflowId); entity.setManifestHash(exportedManifest.manifestHash()); + entity.setManifestSchemaVersion(exportedManifest.manifestSchemaVersion()); + entity.setArtifactDigestsJson( + objectMapper.writeValueAsString(exportedManifest.artifactDigests())); entity.setGenerationConfigRevision(generationConfigRevision); entity.setRequiredManifestAssetKeysJson( serializeKeys(exportedManifest.requiredManifestAssetKeys())); @@ -139,7 +143,15 @@ private PublishedReleaseBundleDto toDto(PublishedReleaseBundle entity) { entity.getPublishedAt(), entity.getCanonicalTenantId(), entity.getCanonicalVersionId(), - entity.getPublishedReleaseBundleRef()); + entity.getPublishedReleaseBundleRef(), + entity.getManifestSchemaVersion(), + entity.getArtifactDigestsJson() == null + ? null + : objectMapper.readValue( + entity.getArtifactDigestsJson(), + objectMapper + .getTypeFactory() + .constructCollectionType(List.class, PublishedArtifactDigest.class))); } private boolean isCanonicalNonNilUuid(UUID value) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java index 7b0ead7af9..de4d5716fd 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java @@ -24,9 +24,11 @@ import net.firedevops.firemud.gamedesign.repository.VersionTemplateRemapSetRepository; import net.firedevops.firemud.gamedesign.service.AssetExportService; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import tools.jackson.databind.ObjectMapper; @@ -79,6 +81,64 @@ public Optional findState(String tenantId, long ve return repository.findByTenantIdAndVersionId(tenantId, versionId).map(this::toDto); } + @Override + @Transactional(propagation = Propagation.REQUIRES_NEW) + public VersionAssetArtifactStateDto stageExport( + String tenantId, long versionId, int versionNumber, String workflowId) { + if (tenantId == null + || tenantId.isBlank() + || versionId <= 0 + || versionNumber <= 0 + || workflowId == null + || workflowId.isBlank() + || workflowId.length() > 1024) { + throw new IllegalArgumentException("Exact asset export scope and workflow are required"); + } + Version version = + versionRepository + .findByTenantIdAndIdForUpdate(tenantId, versionId) + .orElseThrow(() -> new IllegalArgumentException("version not found")); + if (version.getVersionState() != VersionLifecycleState.DRAFT + || !Objects.equals(version.getTenantId(), tenantId) + || !Objects.equals(version.getId(), versionId) + || version.getVersionNumber() != versionNumber + || version.getVersionStateEpoch() == null + || version.getVersionStateEpoch() <= 0 + || version.getCanonicalTenantId() == null + || version.getCanonicalTenantId().equals(new UUID(0L, 0L)) + || version.getCanonicalVersionId() == null + || version.getCanonicalVersionId().equals(new UUID(0L, 0L)) + || version.getIdentitySourceGameRowId() == null + || version.getIdentitySourceGameRowId() <= 0 + || !Objects.equals(version.getIdentitySourceGameTenantKey(), tenantId) + || version.getIdentitySourceProvenanceKind() == null + || !List.of("NEW_GAME_ROW", "RETAINED_GAME_V30") + .contains(version.getIdentitySourceProvenanceKind())) { + throw new IllegalStateException("ASSET_EXPORT_VERSION_CONFLICT"); + } + Optional stored = + repository.findByTenantIdAndVersionIdForUpdate(tenantId, versionId); + if (stored.isPresent()) { + VersionAssetArtifact artifact = stored.orElseThrow(); + if (!Objects.equals(workflowId, artifact.getLastWorkflowId()) + || artifact.getExportedVersionNumber() != versionNumber + || artifact.getStateEpoch() <= 0 + || (artifact.getArtifactState() != VersionAssetArtifactState.STAGED + && artifact.getArtifactState() != VersionAssetArtifactState.EXPORTED_UNATTESTED)) { + throw new IllegalStateException("ASSET_EXPORT_OPERATION_CONFLICT"); + } + return toDto(artifact); + } + VersionAssetArtifact artifact = new VersionAssetArtifact(); + artifact.setTenantId(tenantId); + artifact.setVersionId(versionId); + artifact.setExportedVersionNumber(versionNumber); + artifact.setArtifactState(VersionAssetArtifactState.STAGED); + artifact.setStateEpoch(1L); + artifact.setLastWorkflowId(workflowId); + return toDto(repository.save(artifact)); + } + @Override @Transactional public VersionAssetArtifactStateDto markExportedUnattested( @@ -87,10 +147,24 @@ public VersionAssetArtifactStateDto markExportedUnattested( int exportedVersionNumber, String workflowId, ExportedAssetManifest exportedManifest) { - VersionAssetArtifact artifact = findOrCreate(tenantId, versionId); + VersionAssetArtifact artifact = + repository + .findByTenantIdAndVersionIdForUpdate(tenantId, versionId) + .orElseThrow(() -> new IllegalStateException("ASSET_EXPORT_OPERATION_CONFLICT")); + if (!Objects.equals(workflowId, artifact.getLastWorkflowId()) + || artifact.getExportedVersionNumber() != exportedVersionNumber + || !Objects.equals(candidateOf(artifact), exportedManifest)) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_CONFLICT"); + } + if (artifact.getArtifactState() == VersionAssetArtifactState.EXPORTED_UNATTESTED) { + return toDto(artifact); + } + if (artifact.getArtifactState() != VersionAssetArtifactState.STAGED) { + throw new IllegalStateException("ASSET_ARTIFACT_STATE_CONFLICT"); + } artifact.setArtifactState(VersionAssetArtifactState.EXPORTED_UNATTESTED); artifact.setExportedVersionNumber(exportedVersionNumber); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setManifestHash(exportedManifest.manifestHash()); artifact.setLastWorkflowId(workflowId); artifact.setLastErrorCode(null); @@ -101,6 +175,23 @@ public VersionAssetArtifactStateDto markExportedUnattested( return toDto(repository.save(artifact)); } + @Override + @Transactional(readOnly = true) + public ExportedAssetManifest getExportCandidate(String tenantId, long versionId) { + if (tenantId == null || tenantId.isBlank() || versionId <= 0) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE"); + } + VersionAssetArtifact artifact = requireArtifact(tenantId, versionId); + if (!Objects.equals(tenantId, artifact.getTenantId()) + || !Objects.equals(versionId, artifact.getVersionId())) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE"); + } + if (isInitialStagedIntentWithoutCandidate(artifact)) { + return null; + } + return candidateOf(artifact); + } + @Override @Transactional public VersionAssetArtifactStateDto markPublished( @@ -118,7 +209,7 @@ public VersionAssetArtifactStateDto markPublished( throw new IllegalStateException("REPAIR_ATTESTATION_MISMATCH"); } artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setLastWorkflowId(workflowId); artifact.setLastErrorCode(null); artifact.setLastErrorMessage(null); @@ -139,8 +230,14 @@ public void markFailed( VersionAssetArtifact artifact = findOrCreate(tenantId, versionId); artifact.setArtifactState(VersionAssetArtifactState.FAILED); artifact.setExportedVersionNumber(exportedVersionNumber); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); - artifact.setManifestHash(exportedManifest == null ? null : exportedManifest.manifestHash()); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); + if (artifact.getManifestSchemaVersion() != null) { + if (exportedManifest != null && !Objects.equals(candidateOf(artifact), exportedManifest)) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_CONFLICT"); + } + } else { + artifact.setManifestHash(exportedManifest == null ? null : exportedManifest.manifestHash()); + } artifact.setLastWorkflowId(workflowId); artifact.setLastErrorCode(errorCode); artifact.setLastErrorMessage(errorMessage); @@ -163,7 +260,7 @@ public VersionAssetArtifactStateDto tombstoneVersionAssets( throw new IllegalStateException("VERSION_ASSET_NOT_DELETABLE"); } artifact.setArtifactState(VersionAssetArtifactState.TOMBSTONED); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setLastWorkflowId(tombstoneWorkflowId); artifact.setLastErrorCode(null); artifact.setLastErrorMessage(null); @@ -268,7 +365,7 @@ public VersionAssetPurgeWorkflowStatusDto beginPurgeVersionAssets( } String purgeWorkflowId = UUID.randomUUID().toString(); artifact.setArtifactState(VersionAssetArtifactState.PURGE_IN_PROGRESS); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setLastWorkflowId(purgeWorkflowId); artifact.setLastErrorCode(null); artifact.setLastErrorMessage(null); @@ -303,7 +400,7 @@ public VersionAssetPurgeWorkflowStatusDto finalizePurgeVersionAssets( artifact.getExportedVersionNumber(), deserializeKeys(artifact.getExportedManifestAssetKeysJson())); artifact.setArtifactState(VersionAssetArtifactState.PURGED); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setLastErrorCode(null); artifact.setLastErrorMessage(null); artifact.setUpdatedAt(LocalDateTime.now()); @@ -318,7 +415,7 @@ public VersionAssetPurgeWorkflowStatusDto finalizePurgeVersionAssets( return toWorkflowDto(workflow); } catch (RuntimeException ex) { artifact.setArtifactState(VersionAssetArtifactState.PURGE_FAILED); - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setLastErrorCode("PURGE_FINALIZATION_CONFLICT"); artifact.setLastErrorMessage(ex.getMessage()); artifact.setUpdatedAt(LocalDateTime.now()); @@ -363,11 +460,12 @@ public VersionAssetArtifactStateDto repairPublishedVersionAssets( artifact.setLastWorkflowId(repairWorkflowId); artifact.setLastErrorCode(ex.getMessage().split(":", 2)[0]); artifact.setLastErrorMessage(ex.getMessage().split(":", 2)[1].trim()); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setUpdatedAt(LocalDateTime.now()); repository.save(artifact); throw new IllegalStateException(artifact.getLastErrorCode()); } - artifact.setStateEpoch(artifact.getStateEpoch() + 1); + artifact.setStateEpoch(Math.addExact(artifact.getStateEpoch(), 1L)); artifact.setManifestHash(exported.manifestHash()); artifact.setLastWorkflowId(repairWorkflowId); artifact.setLastErrorCode(null); @@ -447,6 +545,53 @@ private String serializeKeys(List keys) { } } + private ExportedAssetManifest candidateOf(VersionAssetArtifact artifact) { + if (artifact.getManifestSchemaVersion() == null + || artifact.getArtifactDigestsJson() == null + || artifact.getPublishedObjectProofsJson() == null + || !Objects.equals(artifact.getCandidateSnapshotVersionId(), artifact.getVersionId())) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE"); + } + try { + List digests = + objectMapper.readValue( + artifact.getArtifactDigestsJson(), + objectMapper + .getTypeFactory() + .constructCollectionType(List.class, PublishedArtifactDigest.class)); + return new ExportedAssetManifest( + artifact.getManifestHash(), + artifact.getManifestSchemaVersion(), + deserializeKeys(artifact.getExportedManifestAssetKeysJson()), + digests); + } catch (Exception ex) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE", ex); + } + } + + private boolean isInitialStagedIntentWithoutCandidate(VersionAssetArtifact artifact) { + if (artifact.getArtifactState() != VersionAssetArtifactState.STAGED + || artifact.getStateEpoch() <= 0 + || artifact.getLastWorkflowId() == null + || artifact.getLastWorkflowId().isBlank() + || artifact.getManifestHash() != null + || artifact.getManifestSchemaVersion() != null + || artifact.getArtifactDigestsJson() != null + || artifact.getPublishedObjectProofsJson() != null + || artifact.getCandidateSnapshotVersionId() != null) { + return false; + } + String keysJson = artifact.getExportedManifestAssetKeysJson(); + if (keysJson == null || keysJson.isBlank()) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE"); + } + List keys = deserializeKeys(keysJson); + if (keys == null) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_UNAVAILABLE"); + } + return keys.isEmpty(); + } + private List deserializeKeys(String keysJson) { try { if (keysJson == null || keysJson.isBlank()) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java new file mode 100644 index 0000000000..b7478f5db3 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java @@ -0,0 +1,448 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Comparator; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; +import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.AssetSelection; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.service.VersionAssetExportCandidateService; +import net.firedevops.firemud.gamedesign.service.VersionAssetPublicationService; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.ObjectMapper; + +/** Commits exact candidate evidence before the exporter is allowed to write any object bytes. */ +@Service +public final class VersionAssetExportCandidateServiceImpl + implements VersionAssetExportCandidateService { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String CANDIDATE_CONFLICT = "ASSET_EXPORT_CANDIDATE_CONFLICT"; + private static final String CANDIDATE_NOT_FOUND = "ASSET_EXPORT_CANDIDATE_NOT_FOUND"; + private static final String MANIFEST_OBJECT_ROOT = "manifests/sha256/"; + private static final String ARTIFACT_OBJECT_ROOT = "artifacts/sha256/"; + private static final String MANIFEST_USAGE_KEY = "manifest.json"; + private static final String BINARY_ARTIFACT_KIND = "BINARY"; + private final VersionRepository versionRepository; + private final VersionAssetArtifactRepository artifactRepository; + private final VersionAssetPublicationService publicationService; + private final ObjectMapper objectMapper; + private final TransactionTemplate ownerWrite; + private final TransactionTemplate ownerRead; + + public VersionAssetExportCandidateServiceImpl( + VersionRepository versionRepository, + VersionAssetArtifactRepository artifactRepository, + VersionAssetPublicationService publicationService, + PlatformTransactionManager transactionManager, + ObjectMapper objectMapper) { + this.versionRepository = Objects.requireNonNull(versionRepository, "versionRepository"); + this.artifactRepository = Objects.requireNonNull(artifactRepository, "artifactRepository"); + this.publicationService = Objects.requireNonNull(publicationService, "publicationService"); + this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper"); + PlatformTransactionManager requiredTransactionManager = + Objects.requireNonNull(transactionManager, "transactionManager"); + + ownerWrite = new TransactionTemplate(requiredTransactionManager); + ownerWrite.setName("version-asset-export-candidate-write"); + ownerWrite.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerWrite.setTimeout(15); + + ownerRead = new TransactionTemplate(requiredTransactionManager); + ownerRead.setName("version-asset-export-candidate-readback"); + ownerRead.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerRead.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + ownerRead.setReadOnly(true); + ownerRead.setTimeout(15); + } + + @Override + public ExportedAssetManifest recordExportCandidate( + String tenantId, int versionNumber, ExportedAssetManifest candidate) { + requireScope(tenantId, versionNumber); + Objects.requireNonNull(candidate, "candidate"); + ExportedAssetManifest committed = + ownerWrite.execute(status -> recordInOwnerTransaction(tenantId, versionNumber, candidate)); + if (committed == null) { + throw new IllegalStateException("Export candidate transaction returned no proof"); + } + // TransactionTemplate returns only after commit. The caller performs its own independent + // readback before it is permitted to write any object-store bytes. + return committed; + } + + @Override + public ExportedAssetManifest readExportCandidate(String tenantId, int versionNumber) { + requireScope(tenantId, versionNumber); + ExportedAssetManifest result = + ownerRead.execute(status -> readInOwnerTransaction(tenantId, versionNumber)); + if (result == null) { + throw new IllegalStateException("Independent export candidate readback returned no proof"); + } + return result; + } + + private ExportedAssetManifest recordInOwnerTransaction( + String tenantId, int versionNumber, ExportedAssetManifest requested) { + Version initiallyFound = + versionRepository + .findByTenantIdAndVersionNumber(tenantId, versionNumber) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + if (initiallyFound.getId() == null || initiallyFound.getId() <= 0) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + Version version = + versionRepository + .findByTenantIdAndIdForUpdate(tenantId, initiallyFound.getId()) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + validateVersion(version, tenantId, versionNumber); + + VersionAssetArtifact artifact = + artifactRepository + .findByTenantIdAndVersionIdForUpdate(tenantId, version.getId()) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + validateArtifactScope(artifact, tenantId, version); + + ExportSnapshot snapshot = readAndValidateSnapshot(tenantId, versionNumber, version); + CandidateEvidence requestedEvidence = candidateEvidence(requested, snapshot); + if (hasAnyCandidateEvidence(artifact)) { + CandidateEvidence storedEvidence = storedEvidence(artifact, version, snapshot); + if (!sameCandidate(requested, storedEvidence.manifest()) + || !sameEvidence(requestedEvidence, storedEvidence)) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + return storedEvidence.manifest(); + } + + if (version.getVersionState() != VersionLifecycleState.DRAFT + || version.getVersionStateEpoch() == null + || version.getVersionStateEpoch() != snapshot.capturedVersionStateEpoch() + || artifact.getArtifactState() != VersionAssetArtifactState.STAGED + || artifact.getStateEpoch() <= 0 + || artifact.getLastWorkflowId() == null + || artifact.getLastWorkflowId().isBlank() + || artifact.getExportedVersionNumber() != versionNumber + || artifact.getManifestHash() != null + || !isEmptyKeysJson(artifact.getExportedManifestAssetKeysJson())) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + + long nextEpoch; + try { + nextEpoch = Math.addExact(artifact.getStateEpoch(), 1L); + } catch (ArithmeticException exception) { + throw new IllegalStateException(CANDIDATE_CONFLICT, exception); + } + artifact.setManifestHash(requested.manifestHash()); + artifact.setManifestSchemaVersion(requested.manifestSchemaVersion()); + artifact.setArtifactDigestsJson(serialize(requested.artifactDigests())); + artifact.setPublishedObjectProofsJson(serialize(requestedEvidence.objectProofs())); + artifact.setCandidateSnapshotVersionId(snapshot.versionId()); + artifact.setExportedManifestAssetKeysJson(serialize(requested.requiredManifestAssetKeys())); + artifact.setStateEpoch(nextEpoch); + + VersionAssetArtifact saved = artifactRepository.save(artifact); + CandidateEvidence readback = storedEvidence(saved, version, snapshot); + if (!sameEvidence(requestedEvidence, readback) + || !sameCandidate(requested, readback.manifest())) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + return readback.manifest(); + } + + private ExportedAssetManifest readInOwnerTransaction(String tenantId, int versionNumber) { + Version version = + versionRepository + .findByTenantIdAndVersionNumber(tenantId, versionNumber) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + validateVersion(version, tenantId, versionNumber); + VersionAssetArtifact artifact = + artifactRepository + .findByTenantIdAndVersionId(tenantId, version.getId()) + .orElseThrow(() -> new IllegalStateException(CANDIDATE_NOT_FOUND)); + validateArtifactScope(artifact, tenantId, version); + ExportSnapshot snapshot = readAndValidateSnapshot(tenantId, versionNumber, version); + if (!hasAnyCandidateEvidence(artifact)) { + throw new IllegalStateException(CANDIDATE_NOT_FOUND); + } + return storedEvidence(artifact, version, snapshot).manifest(); + } + + private ExportSnapshot readAndValidateSnapshot( + String tenantId, int versionNumber, Version version) { + ExportSnapshot snapshot = publicationService.readFrozenSnapshot(tenantId, versionNumber); + if (snapshot == null + || !Objects.equals(snapshot.tenantId(), tenantId) + || snapshot.versionId() != version.getId() + || snapshot.versionNumber() != versionNumber + || snapshot.capturedVersionStateEpoch() <= 0 + || version.getVersionStateEpoch() == null + || version.getVersionStateEpoch() < snapshot.capturedVersionStateEpoch() + || !Objects.equals(snapshot.canonicalTenantId(), version.getCanonicalTenantId()) + || !Objects.equals(snapshot.canonicalVersionId(), version.getCanonicalVersionId()) + || snapshot.items() == null) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + return snapshot; + } + + private CandidateEvidence storedEvidence( + VersionAssetArtifact artifact, Version version, ExportSnapshot snapshot) { + if (artifact.getManifestSchemaVersion() == null + || artifact.getManifestSchemaVersion() != 1 + || artifact.getArtifactDigestsJson() == null + || artifact.getPublishedObjectProofsJson() == null + || artifact.getCandidateSnapshotVersionId() == null + || !Objects.equals(artifact.getCandidateSnapshotVersionId(), version.getId()) + || artifact.getManifestHash() == null + || artifact.getExportedVersionNumber() != snapshot.versionNumber() + || artifact.getLastWorkflowId() == null + || artifact.getLastWorkflowId().isBlank() + || artifact.getStateEpoch() <= 0) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + + try { + List keys = + objectMapper.readValue( + requireJson(artifact.getExportedManifestAssetKeysJson()), + objectMapper.getTypeFactory().constructCollectionType(List.class, String.class)); + List digests = + objectMapper.readValue( + artifact.getArtifactDigestsJson(), + objectMapper + .getTypeFactory() + .constructCollectionType(List.class, PublishedArtifactDigest.class)); + List proofs = + objectMapper.readValue( + artifact.getPublishedObjectProofsJson(), + objectMapper.getTypeFactory().constructCollectionType(List.class, ObjectProof.class)); + ExportedAssetManifest manifest = + new ExportedAssetManifest( + artifact.getManifestHash(), artifact.getManifestSchemaVersion(), keys, digests); + CandidateEvidence verified = candidateEvidence(manifest, snapshot); + if (!Objects.equals(artifact.getArtifactDigestsJson(), serialize(digests)) + || !Objects.equals(artifact.getPublishedObjectProofsJson(), serialize(proofs)) + || !Objects.equals(artifact.getExportedManifestAssetKeysJson(), serialize(keys)) + || !Objects.equals(proofs, verified.objectProofs())) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + return verified; + } catch (RuntimeException exception) { + if (CANDIDATE_CONFLICT.equals(exception.getMessage())) { + throw exception; + } + throw new IllegalStateException(CANDIDATE_CONFLICT, exception); + } + } + + private CandidateEvidence candidateEvidence( + ExportedAssetManifest manifest, ExportSnapshot snapshot) { + if (manifest.manifestSchemaVersion() != 1 + || manifest.manifestHash() == null + || !manifest.manifestHash().matches("sha256:[0-9a-f]{64}") + || !Objects.equals( + manifest.requiredManifestAssetKeys(), + snapshot.items().stream().map(AssetSelection::usageKey).toList()) + || manifest.artifactDigests().size() != snapshot.items().size()) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + + Set usageKeys = new HashSet<>(); + Set assetIds = new HashSet<>(); + LinkedHashMap proofsByKey = new LinkedHashMap<>(); + for (int index = 0; index < snapshot.items().size(); index++) { + AssetSelection source = snapshot.items().get(index); + PublishedArtifactDigest digest = manifest.artifactDigests().get(index); + if (source == null + || digest == null + || source.usageKey() == null + || source.usageKey().isBlank() + || !isCanonicalText(source.usageKey()) + || MANIFEST_USAGE_KEY.equals(source.usageKey()) + || source.assetId() <= 0 + || source.bytes() == null + || source.contentType() == null + || source.contentType().isBlank() + || !source.contentType().equals(source.contentType().trim()) + || source.contentType().contains("\r") + || source.contentType().contains("\n") + || !isCanonicalText(source.contentType()) + || source.contentDigest() == null + || !source.contentDigest().matches("sha256:[0-9a-f]{64}") + || !source.contentDigest().equals(digest(source.bytes())) + || !usageKeys.add(source.usageKey()) + || !assetIds.add(source.assetId()) + || !Objects.equals(digest.usageKey(), source.usageKey()) + || !Objects.equals(digest.artifactKind(), BINARY_ARTIFACT_KIND) + || digest.artifactSchemaVersion() != 1 + || !Objects.equals(digest.contentType(), source.contentType()) + || !Objects.equals(digest.contentDigest(), source.contentDigest()) + || !Objects.equals( + digest.immutableObjectKey(), + ARTIFACT_OBJECT_ROOT + source.contentDigest().substring(7))) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + putProof(proofsByKey, digest.immutableObjectKey(), digest.contentDigest()); + } + + String manifestDigest = manifest.manifestHash(); + putProof( + proofsByKey, + MANIFEST_OBJECT_ROOT + manifestDigest.substring("sha256:".length()), + manifestDigest); + List objectProofs = + proofsByKey.values().stream() + .sorted(Comparator.comparing(ObjectProof::immutableObjectKey)) + .toList(); + return new CandidateEvidence(manifest, objectProofs); + } + + private void putProof( + LinkedHashMap proofsByKey, String objectKey, String contentDigest) { + ObjectProof proof = new ObjectProof(objectKey, contentDigest); + ObjectProof existing = proofsByKey.putIfAbsent(objectKey, proof); + if (existing != null && !existing.equals(proof)) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + } + + private void validateVersion(Version version, String tenantId, int versionNumber) { + if (version.getId() == null + || version.getId() <= 0 + || !Objects.equals(version.getTenantId(), tenantId) + || version.getVersionNumber() != versionNumber + || version.getVersionState() == null + || !(version.getVersionState() == VersionLifecycleState.DRAFT + || version.getVersionState() == VersionLifecycleState.PUBLISHED + || version.getVersionState() == VersionLifecycleState.ACTIVE) + || version.getVersionStateEpoch() == null + || version.getVersionStateEpoch() <= 0 + || !isCanonicalUuid(version.getCanonicalTenantId()) + || !isCanonicalUuid(version.getCanonicalVersionId()) + || version.getIdentitySourceGameRowId() == null + || version.getIdentitySourceGameRowId() <= 0 + || !Objects.equals(version.getIdentitySourceGameTenantKey(), tenantId) + || !("NEW_GAME_ROW".equals(version.getIdentitySourceProvenanceKind()) + || "RETAINED_GAME_V30".equals(version.getIdentitySourceProvenanceKind()))) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + } + + private void validateArtifactScope( + VersionAssetArtifact artifact, String tenantId, Version version) { + if (artifact.getId() == null + || artifact.getId() <= 0 + || !Objects.equals(artifact.getTenantId(), tenantId) + || !Objects.equals(artifact.getVersionId(), version.getId()) + || artifact.getArtifactState() == null + || !(artifact.getArtifactState() == VersionAssetArtifactState.STAGED + || artifact.getArtifactState() == VersionAssetArtifactState.EXPORTED_UNATTESTED + || artifact.getArtifactState() == VersionAssetArtifactState.PUBLISHED) + || artifact.getStateEpoch() <= 0) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + } + + private boolean hasAnyCandidateEvidence(VersionAssetArtifact artifact) { + return artifact.getManifestSchemaVersion() != null + || artifact.getArtifactDigestsJson() != null + || artifact.getPublishedObjectProofsJson() != null + || artifact.getCandidateSnapshotVersionId() != null; + } + + private boolean isEmptyKeysJson(String json) { + try { + List keys = + objectMapper.readValue( + requireJson(json), + objectMapper.getTypeFactory().constructCollectionType(List.class, String.class)); + return keys.isEmpty() && Objects.equals(json, serialize(keys)); + } catch (RuntimeException exception) { + throw new IllegalStateException(CANDIDATE_CONFLICT, exception); + } + } + + private static boolean sameCandidate(ExportedAssetManifest left, ExportedAssetManifest right) { + return Objects.equals(left, right); + } + + private static boolean sameEvidence(CandidateEvidence left, CandidateEvidence right) { + return sameCandidate(left.manifest(), right.manifest()) + && Objects.equals(left.objectProofs(), right.objectProofs()); + } + + private String serialize(Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (RuntimeException exception) { + throw new IllegalStateException(CANDIDATE_CONFLICT, exception); + } + } + + private static String requireJson(String json) { + if (json == null || json.isBlank()) { + throw new IllegalStateException(CANDIDATE_CONFLICT); + } + return json; + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static boolean isCanonicalUuid(UUID value) { + return value != null && !NIL_UUID.equals(value); + } + + private static boolean isCanonicalText(String value) { + if (value == null || value.codePoints().anyMatch(Character::isISOControl)) { + return false; + } + try { + StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(value)); + return true; + } catch (CharacterCodingException exception) { + return false; + } + } + + private static void requireScope(String tenantId, int versionNumber) { + if (tenantId == null || tenantId.isBlank() || versionNumber <= 0) { + throw new IllegalArgumentException("Exact tenant and Version number are required"); + } + } + + /** Exact immutable key/content-digest proof; candidate rows use camel-case record JSON fields. */ + private record ObjectProof(String immutableObjectKey, String contentDigest) {} + + private record CandidateEvidence(ExportedAssetManifest manifest, List objectProofs) { + private CandidateEvidence { + objectProofs = List.copyOf(objectProofs); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetPublicationServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetPublicationServiceImpl.java new file mode 100644 index 0000000000..cd7a2a21fe --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetPublicationServiceImpl.java @@ -0,0 +1,118 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.AssetSelection; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; +import net.firedevops.firemud.gamedesign.service.VersionAssetPublicationService; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** Commits durable Version asset selections independently before exposing verified readback. */ +@Service +public final class VersionAssetPublicationServiceImpl implements VersionAssetPublicationService { + private final VersionAssetPublicationRepository repository; + private final TransactionTemplate ownerWrite; + private final TransactionTemplate ownerRead; + + public VersionAssetPublicationServiceImpl( + PlatformTransactionManager transactionManager, VersionAssetPublicationRepository repository) { + this.repository = Objects.requireNonNull(repository, "repository"); + PlatformTransactionManager requiredTransactionManager = + Objects.requireNonNull(transactionManager, "transactionManager"); + this.ownerWrite = new TransactionTemplate(requiredTransactionManager); + this.ownerWrite.setName("version-asset-publication-write"); + this.ownerWrite.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerWrite.setTimeout(15); + + this.ownerRead = new TransactionTemplate(requiredTransactionManager); + this.ownerRead.setName("version-asset-publication-readback"); + this.ownerRead.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerRead.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + this.ownerRead.setReadOnly(true); + this.ownerRead.setTimeout(15); + } + + @Override + public void associateDraftAsset(String tenantId, long versionId, long assetId, String usageType) { + requireTenantId(tenantId); + if (versionId <= 0 || assetId <= 0) { + throw new IllegalArgumentException("Version and asset owner keys must be positive"); + } + ownerWrite.executeWithoutResult( + status -> repository.associateDraftAsset(tenantId, versionId, assetId, usageType)); + } + + @Override + public ExportSnapshot freezeOrReadSnapshot(String tenantId, int versionNumber) { + requireTenantId(tenantId); + if (versionNumber <= 0) { + throw new IllegalArgumentException("Version number must be positive"); + } + ExportSnapshot committed = + ownerWrite.execute(status -> repository.freezeOrReadSnapshot(tenantId, versionNumber)); + if (committed == null) { + throw new IllegalStateException("Version asset snapshot transaction returned no proof"); + } + + ExportSnapshot readback = readFrozenSnapshot(tenantId, versionNumber); + if (!sameSnapshot(committed, readback)) { + throw new IllegalStateException( + "Committed Version asset snapshot did not match independent readback"); + } + return readback; + } + + @Override + public ExportSnapshot readFrozenSnapshot(String tenantId, int versionNumber) { + requireTenantId(tenantId); + if (versionNumber <= 0) { + throw new IllegalArgumentException("Version number must be positive"); + } + ExportSnapshot result = + ownerRead.execute(status -> repository.readFrozenSnapshot(tenantId, versionNumber)); + if (result == null) { + throw new IllegalStateException( + "Independent Version asset snapshot readback returned no proof"); + } + return result; + } + + private static boolean sameSnapshot(ExportSnapshot left, ExportSnapshot right) { + if (!Objects.equals(left.tenantId(), right.tenantId()) + || left.versionId() != right.versionId() + || left.versionNumber() != right.versionNumber() + || left.capturedVersionStateEpoch() != right.capturedVersionStateEpoch() + || !Objects.equals(left.canonicalTenantId(), right.canonicalTenantId()) + || !Objects.equals(left.canonicalVersionId(), right.canonicalVersionId())) { + return false; + } + List leftItems = left.items(); + List rightItems = right.items(); + if (leftItems.size() != rightItems.size()) { + return false; + } + for (int index = 0; index < leftItems.size(); index++) { + AssetSelection leftItem = leftItems.get(index); + AssetSelection rightItem = rightItems.get(index); + if (!Objects.equals(leftItem.usageKey(), rightItem.usageKey()) + || leftItem.assetId() != rightItem.assetId() + || !Objects.equals(leftItem.contentType(), rightItem.contentType()) + || !Objects.equals(leftItem.contentDigest(), rightItem.contentDigest()) + || !Arrays.equals(leftItem.bytes(), rightItem.bytes())) { + return false; + } + } + return true; + } + + private static void requireTenantId(String tenantId) { + if (tenantId == null || tenantId.isBlank()) { + throw new IllegalArgumentException("Owner-local tenant key is required"); + } + } +} 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 22c3ff8913..5183b3849b 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 @@ -21,6 +21,7 @@ import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.AssetExportOutcomePendingException; import net.firedevops.firemud.gamedesign.service.AssetExportService; import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; @@ -166,11 +167,33 @@ public PublishWorkflowSnapshot reconcileFullVersionPublish(PublishWorkflowReques } catch (RuntimeException ex) { return failDefinitively(request, attempt, version, null, ex); } + if (existingPublication.isAbsent()) { + try { + VersionAssetArtifactStateDto staged = + versionAssetArtifactService.stageExport( + request.tenantId(), dto.id(), dto.versionNumber(), request.publishWorkflowId()); + VersionAssetArtifactStateDto stagedReadback = + versionAssetArtifactService + .findState(request.tenantId(), dto.id()) + .orElseThrow(() -> pendingReconciliation("asset export intent readback is absent")); + if (staged == null || !staged.equals(stagedReadback)) { + throw pendingReconciliation("asset export intent readback does not match its commit"); + } + verifyStagedIntent(request, attempt, version, stagedReadback); + } catch (RuntimeException ex) { + throw pendingReconciliation("asset export intent commit requires exact readback", ex); + } + } ExportedAssetManifest exportedManifest; try { exportedManifest = assetExportService.exportAssets(request.tenantId(), dto.versionNumber()); + } catch (AssetExportOutcomePendingException ex) { + throw pendingReconciliation( + "asset export outcome remains unresolved; retry exact request", ex); } catch (RuntimeException ex) { - return failDefinitively(request, attempt, version, null, ex); + // Export may have committed candidate evidence or earlier immutable objects before failing. + // A deterministic later conflict does not prove that every prior write is resolved. + throw pendingReconciliation("asset export requires exact candidate/write reconciliation", ex); } PublishWorkflowRequest effectiveRequest = request; @@ -321,7 +344,7 @@ private PublishWorkflowSnapshot finalizeFullVersion( generationConfigRevision, participantDigests); version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(version.getVersionStateEpoch() + 1L); + version.setVersionStateEpoch(Math.addExact(version.getVersionStateEpoch(), 1L)); version.setUpdatedAt(LocalDateTime.now()); versionRepository.save(version); versionAssetArtifactService.markPublished( @@ -460,13 +483,24 @@ private PublishWorkflowSnapshot failDefinitively( if (current.getStatus() != PublishAttemptStatus.PENDING) { throw pendingReconciliation("full-version attempt is no longer pending"); } + Version currentVersion = requireAttemptVersionForUpdate(current, request); PublicationReadback readback = readPublication(request, current); if (!readback.isAbsent()) { - throw pendingReconciliation( - "publication failure has committed or partial release evidence; reconciliation is required"); + if (!readback.isStagedNoRelease()) { + throw pendingReconciliation( + "publication failure has committed or partial release evidence; reconciliation is required"); + } + if (exportedManifest == null + || !Objects.equals(readback.candidate(), exportedManifest)) { + throw pendingReconciliation( + "staged asset writes remain unresolved; exact export readback is required"); + } } - Version currentVersion = requireAttemptVersion(current, request); if (exportedManifest != null) { + if (!readback.isStagedNoRelease()) { + throw pendingReconciliation( + "exported asset manifest lacks an exact staged intent readback"); + } versionAssetArtifactService.markFailed( request.tenantId(), currentVersion.getId(), @@ -490,7 +524,8 @@ private PublishWorkflowSnapshot failDefinitively( "full-version failure marking commit outcome is unknown; readback/reconciliation is required", ambiguousFailure); } - cleanupExportedAssets(request.tenantId(), version.getVersionNumber(), exportedManifest); + // Immutable candidate keys can be shared with another release. Retain them for the owner + // abandonment/reachability workflow; a failed publication is never deletion authority. return new PublishWorkflowSnapshot( attempt.getVersionId(), attempt.getVersionNumber(), @@ -653,7 +688,18 @@ private PublicationReadback readPublication( if (bundle == null && artifact == null && version.get().getVersionState() == VersionLifecycleState.DRAFT) { - return PublicationReadback.absent(); + return PublicationReadback.absent(version.get()); + } + if (bundle == null + && version.get().getVersionState() == VersionLifecycleState.DRAFT + && artifact != null) { + try { + ExportedAssetManifest candidate = + verifyStagedIntent(request, attempt, version.get(), artifact); + return PublicationReadback.stagedNoRelease(version.get(), artifact, candidate); + } catch (RuntimeException ex) { + return PublicationReadback.partial(); + } } if (bundle == null || artifact == null) { return PublicationReadback.partial(); @@ -671,6 +717,45 @@ private PublicationReadback readPublication( return PublicationReadback.complete(version.get(), bundle, artifact); } + private ExportedAssetManifest verifyStagedIntent( + PublishWorkflowRequest request, + PublishAttempt attempt, + Version version, + VersionAssetArtifactStateDto artifact) { + if (!Objects.equals(version.getTenantId(), request.tenantId()) + || !Objects.equals(version.getId(), attempt.getVersionId()) + || version.getVersionNumber() != attempt.getVersionNumber() + || version.getVersionState() != VersionLifecycleState.DRAFT + || version.getVersionStateEpoch() == null + || version.getVersionStateEpoch() <= 0 + || version.isScriptOnly() + || !Objects.equals(artifact.tenantId(), request.tenantId()) + || !Objects.equals(artifact.versionId(), attempt.getVersionId()) + || artifact.exportedVersionNumber() != attempt.getVersionNumber() + || !"STAGED".equals(artifact.artifactState()) + || artifact.stateEpoch() <= 0 + || !Objects.equals(artifact.lastWorkflowId(), request.publishWorkflowId())) { + throw new IllegalStateException("PUBLISH_ATTEMPT_STAGED_ARTIFACT_SCOPE_MISMATCH"); + } + + ExportedAssetManifest candidate = + versionAssetArtifactService.getExportCandidate(request.tenantId(), attempt.getVersionId()); + if (artifact.manifestHash() == null) { + if (!artifact.exportedManifestAssetKeys().isEmpty() || candidate != null) { + throw new IllegalStateException("PUBLISH_ATTEMPT_STAGED_CANDIDATE_MISMATCH"); + } + return null; + } + if (candidate == null + || candidate.manifestSchemaVersion() != 1 + || !Objects.equals(candidate.manifestHash(), artifact.manifestHash()) + || !Objects.equals( + candidate.requiredManifestAssetKeys(), artifact.exportedManifestAssetKeys())) { + throw new IllegalStateException("PUBLISH_ATTEMPT_STAGED_CANDIDATE_MISMATCH"); + } + return candidate; + } + private void requireExactBundleEvidence( PublishWorkflowRequest request, PublishAttempt attempt, @@ -701,6 +786,22 @@ private void requireExactArtifactEvidence( PublishAttempt attempt, PublishedReleaseBundleDto bundle, VersionAssetArtifactStateDto artifact) { + // Retained terminal history is not backfilled into a complete asset attestation. For a new + // proof-bearing bundle, recovery must compare every original artifact/schema field too. + if (bundle.manifestSchemaVersion() != null) { + ExportedAssetManifest expected = + new ExportedAssetManifest( + bundle.manifestHash(), + bundle.manifestSchemaVersion(), + bundle.requiredManifestAssetKeys(), + bundle.artifactDigests()); + if (!Objects.equals( + expected, + versionAssetArtifactService.getExportCandidate( + request.tenantId(), attempt.getVersionId()))) { + throw new IllegalStateException("PUBLISH_ATTEMPT_ARTIFACT_SCOPE_MISMATCH"); + } + } if (!Objects.equals(artifact.tenantId(), request.tenantId()) || !Objects.equals(artifact.versionId(), attempt.getVersionId()) || artifact.exportedVersionNumber() != attempt.getVersionNumber() @@ -751,18 +852,25 @@ private record PublicationReadback( ReadbackState state, Version version, PublishedReleaseBundleDto bundle, - VersionAssetArtifactStateDto artifact) { - private static PublicationReadback absent() { - return new PublicationReadback(ReadbackState.ABSENT, null, null, null); + VersionAssetArtifactStateDto artifact, + ExportedAssetManifest candidate) { + private static PublicationReadback absent(Version version) { + return new PublicationReadback(ReadbackState.ABSENT, version, null, null, null); } private static PublicationReadback partial() { - return new PublicationReadback(ReadbackState.PARTIAL, null, null, null); + return new PublicationReadback(ReadbackState.PARTIAL, null, null, null, null); + } + + private static PublicationReadback stagedNoRelease( + Version version, VersionAssetArtifactStateDto artifact, ExportedAssetManifest candidate) { + return new PublicationReadback( + ReadbackState.STAGED_NO_RELEASE, version, null, artifact, candidate); } private static PublicationReadback complete( Version version, PublishedReleaseBundleDto bundle, VersionAssetArtifactStateDto artifact) { - return new PublicationReadback(ReadbackState.COMPLETE, version, bundle, artifact); + return new PublicationReadback(ReadbackState.COMPLETE, version, bundle, artifact, null); } private boolean isAbsent() { @@ -773,6 +881,10 @@ private boolean isPartial() { return state == ReadbackState.PARTIAL; } + private boolean isStagedNoRelease() { + return state == ReadbackState.STAGED_NO_RELEASE; + } + private boolean isComplete() { return state == ReadbackState.COMPLETE; } @@ -780,6 +892,7 @@ private boolean isComplete() { private enum ReadbackState { ABSENT, + STAGED_NO_RELEASE, PARTIAL, COMPLETE } @@ -842,23 +955,6 @@ private RuntimeException publishFailure(String failureCode, String failureMessag : failureMessage); } - private void cleanupExportedAssets( - String tenantId, int versionNumber, ExportedAssetManifest exportedManifest) { - if (exportedManifest == null) { - return; - } - try { - assetExportService.deleteExportedAssets( - tenantId, versionNumber, exportedManifest.requiredManifestAssetKeys()); - } catch (RuntimeException cleanupEx) { - logger.warn( - "Failed cleanup of exported assets for tenant {} version {} after publish failure: {}", - tenantId, - versionNumber, - cleanupEx.getMessage()); - } - } - private Version requireTenantVersion(String tenantId, long versionId) { return versionRepository .findByTenantIdAndId(tenantId, versionId) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java index 364d940e1f..24e1aa9c90 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java @@ -664,10 +664,11 @@ && samePublication( PublishedReleaseBundleDto baseBundle = publishedReleaseBundleService.getPublishedReleaseBundle(tenantId, baseVersionId); PublishedReleaseBundleContract.requireSupportedSchemaForRead(baseBundle); - String expectedAbilitySchemaDigest = requiredAutomationAbilitySchemaDigest(baseBundle); + String expectedAbilitySchemaDigest = requiredGameLogicAbilitySchemaDigest(baseBundle); if (!expectedAbilitySchemaDigest.equals(abilitySchemaDigest)) { throw new IllegalArgumentException( - "VALIDATION_FAILED_DESIGN: abilitySchemaDigest does not match published release bundle"); + "VALIDATION_FAILED_DESIGN: abilitySchemaDigest does not match the published Game Logic " + + "release proof"); } PluginDistributionManifest exportedManifest = pluginBundleStorageService.exportPluginAssets( @@ -996,18 +997,42 @@ private void requireRequestedUploadMatchesStoredBundle( } } - private String requiredAutomationAbilitySchemaDigest(PublishedReleaseBundleDto bundle) { - return bundle.participantDigests().stream() - .filter( + private String requiredGameLogicAbilitySchemaDigest(PublishedReleaseBundleDto bundle) { + if (bundle.scriptOnly()) { + throw new IllegalArgumentException( + "INVALID_ARGUMENT: plugin base release must be a full-version attestation"); + } + if (bundle.participantDigests().stream() + .anyMatch( digest -> - PublishParticipantKey.AUTOMATION_SCRIPTING.name().equals(digest.participantKey())) - .map(PublishParticipantDigestDto::contentDigest) - .filter(digest -> digest != null && !digest.isBlank()) - .findFirst() - .orElseThrow( - () -> - new IllegalArgumentException( - "INVALID_ARGUMENT: published release bundle is missing the Automation ability-schema digest")); + !PublishParticipantKey.GAME_LOGIC.name().equals(digest.participantKey()) + && digest.abilitySchemaDigest() != null)) { + throw new IllegalArgumentException( + "INVALID_ARGUMENT: ability-schema digest is owned by a non-Game Logic participant"); + } + List gameLogicDigests = + bundle.participantDigests().stream() + .filter( + digest -> PublishParticipantKey.GAME_LOGIC.name().equals(digest.participantKey())) + .toList(); + if (gameLogicDigests.size() != 1) { + throw new IllegalArgumentException( + "INVALID_ARGUMENT: published release bundle is missing one exact Game Logic participant record"); + } + PublishParticipantDigestDto digest = gameLogicDigests.getFirst(); + if (!Objects.equals(String.valueOf(bundle.versionId()), digest.scopeValue()) + || digest.baseVersionId() != null + || digest.appliedCommitId() == null + || digest.appliedCommitId().isBlank() + || !Integer.valueOf(1).equals(digest.digestSchemaVersion()) + || digest.contentDigest() == null + || digest.contentDigest().isBlank() + || digest.abilitySchemaDigest() == null + || digest.abilitySchemaDigest().isBlank()) { + throw new IllegalArgumentException( + "INVALID_ARGUMENT: published release bundle is missing supported Game Logic ability-schema evidence"); + } + return digest.abilitySchemaDigest(); } private void markValidationFailed(PublishedPluginVersion entity, String statusReason) { diff --git a/services/game-design-service/src/main/resources/application.yml b/services/game-design-service/src/main/resources/application.yml index 9072adfc00..11eb2e498e 100644 --- a/services/game-design-service/src/main/resources/application.yml +++ b/services/game-design-service/src/main/resources/application.yml @@ -57,6 +57,15 @@ server: mime-types: application/json,application/xml,text/html,text/xml,text/plain min-response-size: 1024 +asset: + store: + endpoint: ${ASSET_STORE_ENDPOINT:} + public-base-url: ${ASSET_STORE_PUBLIC_BASE_URL:} + bucket: ${ASSET_STORE_BUCKET:} + region: ${ASSET_STORE_REGION:ap-southeast-2} + access-key: ${ASSET_STORE_ACCESS_KEY:} + secret-key: ${ASSET_STORE_SECRET_KEY:} + firemud: auth: http: diff --git a/services/game-design-service/src/main/resources/db/migration/V37__version_asset_export_snapshot.sql b/services/game-design-service/src/main/resources/db/migration/V37__version_asset_export_snapshot.sql new file mode 100644 index 0000000000..36656d1c58 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V37__version_asset_export_snapshot.sql @@ -0,0 +1,348 @@ +ALTER TABLE game + ADD CONSTRAINT uq_game_tenant_id_id UNIQUE (tenant_id, id); + +ALTER TABLE version + ADD CONSTRAINT uq_version_tenant_id_id UNIQUE (tenant_id, id); + +ALTER TABLE game_assets + ADD CONSTRAINT uq_game_assets_tenant_id_id UNIQUE (tenant_id, id), + ADD CONSTRAINT uq_game_assets_tenant_id_name UNIQUE (tenant_id, id, file_name); + +CREATE TABLE version_asset ( + tenant_id VARCHAR(36) NOT NULL, + version_id BIGINT NOT NULL, + asset_id BIGINT NOT NULL, + usage_key VARCHAR(255) NOT NULL, + usage_type VARCHAR(100), + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_version_asset PRIMARY KEY (tenant_id, version_id, asset_id), + CONSTRAINT uq_version_asset_usage UNIQUE (tenant_id, version_id, usage_key), + CONSTRAINT uq_version_asset_exact UNIQUE (tenant_id, version_id, asset_id, usage_key), + CONSTRAINT fk_version_asset_version FOREIGN KEY (tenant_id, version_id) + REFERENCES version (tenant_id, id) ON DELETE RESTRICT, + CONSTRAINT fk_version_asset_asset FOREIGN KEY (tenant_id, asset_id) + REFERENCES game_assets (tenant_id, id) ON DELETE RESTRICT, + CONSTRAINT fk_version_asset_asset_name FOREIGN KEY (tenant_id, asset_id, usage_key) + REFERENCES game_assets (tenant_id, id, file_name) ON DELETE RESTRICT, + CONSTRAINT chk_version_asset_usage_key CHECK (char_length(usage_key) > 0) +); + +CREATE TABLE version_asset_export_snapshot ( + tenant_id VARCHAR(36) NOT NULL, + version_id BIGINT NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + version_number INTEGER NOT NULL, + captured_version_state_epoch BIGINT NOT NULL, + item_count INTEGER NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_version_asset_export_snapshot PRIMARY KEY (tenant_id, version_id), + CONSTRAINT fk_version_asset_snapshot_version FOREIGN KEY (tenant_id, version_id) + REFERENCES version (tenant_id, id) ON DELETE RESTRICT, + CONSTRAINT chk_version_asset_snapshot_values CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND version_number > 0 + AND captured_version_state_epoch > 0 + AND item_count >= 0 + ) +); + +CREATE TABLE version_asset_export_item ( + tenant_id VARCHAR(36) NOT NULL, + version_id BIGINT NOT NULL, + usage_key VARCHAR(255) NOT NULL, + asset_id BIGINT NOT NULL, + content_type VARCHAR(100) NOT NULL, + content_hash VARCHAR(71) NOT NULL, + byte_size BIGINT NOT NULL, + CONSTRAINT pk_version_asset_export_item PRIMARY KEY (tenant_id, version_id, usage_key), + CONSTRAINT uq_version_asset_export_item_asset UNIQUE (tenant_id, version_id, asset_id), + CONSTRAINT fk_version_asset_export_item_snapshot FOREIGN KEY (tenant_id, version_id) + REFERENCES version_asset_export_snapshot (tenant_id, version_id) + DEFERRABLE INITIALLY DEFERRED, + CONSTRAINT fk_version_asset_export_item_mapping FOREIGN KEY + (tenant_id, version_id, asset_id, usage_key) + REFERENCES version_asset (tenant_id, version_id, asset_id, usage_key) + ON DELETE RESTRICT, + CONSTRAINT chk_version_asset_export_item_hash CHECK (content_hash ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT chk_version_asset_export_item_size CHECK (byte_size >= 0) +); + +-- [jooq ignore start] +CREATE FUNCTION guard_version_asset_mapping() RETURNS trigger AS $$ +DECLARE + target_tenant_id VARCHAR(36); + target_version_id BIGINT; + target_state VARCHAR(32); + target_epoch BIGINT; +BEGIN + IF TG_OP = 'UPDATE' AND ( + NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.version_id IS DISTINCT FROM OLD.version_id + OR NEW.asset_id IS DISTINCT FROM OLD.asset_id + OR NEW.usage_key IS DISTINCT FROM OLD.usage_key + ) THEN + RAISE EXCEPTION 'version asset association identity is immutable; create a new Draft mapping' + USING ERRCODE = 'check_violation'; + END IF; + IF TG_OP = 'DELETE' THEN + target_tenant_id := OLD.tenant_id; + target_version_id := OLD.version_id; + ELSE + target_tenant_id := NEW.tenant_id; + target_version_id := NEW.version_id; + END IF; + + SELECT v.version_state, v.version_state_epoch + INTO target_state, target_epoch + FROM version v + JOIN game g + ON g.id = v.identity_source_game_row_id + AND g.tenant_id = v.identity_source_game_tenant_key + AND g.tenant_id = v.tenant_id + AND g.canonical_tenant_id = v.canonical_tenant_id + AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + WHERE v.tenant_id = target_tenant_id AND v.id = target_version_id + AND v.canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND v.canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + FOR UPDATE OF v; + + IF NOT FOUND THEN + RAISE EXCEPTION 'version asset mapping requires the exact canonical tenant Version source' + USING ERRCODE = 'foreign_key_violation'; + END IF; + IF target_state <> 'DRAFT' OR target_epoch IS NULL OR target_epoch <= 0 THEN + RAISE EXCEPTION 'version asset mappings can change only while the Version is DRAFT' + USING ERRCODE = 'check_violation'; + END IF; + IF EXISTS ( + SELECT 1 FROM version_asset_export_snapshot s + WHERE s.tenant_id = target_tenant_id AND s.version_id = target_version_id + ) THEN + RAISE EXCEPTION 'version asset mappings are frozen by the durable export snapshot' + USING ERRCODE = 'check_violation'; + END IF; + IF TG_OP <> 'DELETE' AND NOT EXISTS ( + SELECT 1 FROM game_assets a + WHERE a.tenant_id = NEW.tenant_id + AND a.id = NEW.asset_id + AND a.file_name = NEW.usage_key + ) THEN + RAISE EXCEPTION 'version asset usage key must equal the exact source file name' + USING ERRCODE = 'check_violation'; + END IF; + + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_version_asset_mapping_guard + BEFORE INSERT OR UPDATE OR DELETE ON version_asset + FOR EACH ROW + EXECUTE FUNCTION guard_version_asset_mapping(); + +CREATE FUNCTION guard_version_asset_export_item() RETURNS trigger AS $$ +DECLARE + source_type VARCHAR(100); + source_size BIGINT; + target_state VARCHAR(32); +BEGIN + IF TG_OP <> 'INSERT' THEN + IF EXISTS ( + SELECT 1 FROM version_asset_export_snapshot s + WHERE s.tenant_id = OLD.tenant_id AND s.version_id = OLD.version_id + ) THEN + RAISE EXCEPTION 'version asset export snapshot items are immutable' + USING ERRCODE = 'check_violation'; + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; + END IF; + + SELECT version_state INTO target_state + FROM version + WHERE tenant_id = NEW.tenant_id AND id = NEW.version_id + FOR UPDATE; + IF NOT FOUND OR target_state <> 'DRAFT' THEN + RAISE EXCEPTION 'version asset export items require the exact Draft Version row' + USING ERRCODE = 'check_violation'; + END IF; + IF EXISTS ( + SELECT 1 FROM version_asset_export_snapshot s + WHERE s.tenant_id = NEW.tenant_id AND s.version_id = NEW.version_id + ) THEN + RAISE EXCEPTION 'version asset export snapshot items are immutable' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT a.content_type, octet_length(a.data)::BIGINT + INTO source_type, source_size + FROM game_assets a + JOIN version_asset va + ON va.tenant_id = a.tenant_id + AND va.asset_id = a.id + AND va.tenant_id = NEW.tenant_id + AND va.version_id = NEW.version_id + AND va.usage_key = NEW.usage_key + AND va.asset_id = NEW.asset_id + WHERE a.tenant_id = NEW.tenant_id AND a.id = NEW.asset_id; + + IF NOT FOUND OR source_type IS DISTINCT FROM NEW.content_type + OR source_size IS DISTINCT FROM NEW.byte_size THEN + RAISE EXCEPTION 'version asset export item source metadata does not match game_assets' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_version_asset_export_item_guard + BEFORE INSERT OR UPDATE OR DELETE ON version_asset_export_item + FOR EACH ROW + EXECUTE FUNCTION guard_version_asset_export_item(); + +CREATE FUNCTION guard_version_asset_export_snapshot() RETURNS trigger AS $$ +DECLARE + source_version_number INTEGER; + source_epoch BIGINT; + source_state VARCHAR(32); + source_canonical_tenant_id UUID; + source_canonical_version_id UUID; + item_rows BIGINT; + mapping_rows BIGINT; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'version asset export snapshot headers are immutable' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT v.version_number, + v.version_state_epoch, + v.version_state, + v.canonical_tenant_id, + v.canonical_version_id + INTO source_version_number, + source_epoch, + source_state, + source_canonical_tenant_id, + source_canonical_version_id + FROM version v + JOIN game g + ON g.id = v.identity_source_game_row_id + AND g.tenant_id = v.identity_source_game_tenant_key + AND g.tenant_id = v.tenant_id + AND g.canonical_tenant_id = v.canonical_tenant_id + AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + WHERE v.tenant_id = NEW.tenant_id AND v.id = NEW.version_id + FOR UPDATE OF v; + + IF NOT FOUND + OR source_state <> 'DRAFT' + OR source_epoch IS NULL OR source_epoch <= 0 + OR source_version_number IS DISTINCT FROM NEW.version_number + OR source_epoch IS DISTINCT FROM NEW.captured_version_state_epoch + OR source_canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR source_canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR source_canonical_tenant_id = '00000000-0000-0000-0000-000000000000'::UUID + OR source_canonical_version_id = '00000000-0000-0000-0000-000000000000'::UUID THEN + RAISE EXCEPTION 'version asset export snapshot requires the exact canonical Draft Version source' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT count(*) INTO item_rows + FROM version_asset_export_item i + WHERE i.tenant_id = NEW.tenant_id AND i.version_id = NEW.version_id; + SELECT count(*) INTO mapping_rows + FROM version_asset va + WHERE va.tenant_id = NEW.tenant_id AND va.version_id = NEW.version_id; + IF item_rows <> NEW.item_count OR mapping_rows <> NEW.item_count THEN + RAISE EXCEPTION 'version asset export snapshot item count does not prove the complete mapping set' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_version_asset_export_snapshot_guard + BEFORE INSERT OR UPDATE OR DELETE ON version_asset_export_snapshot + FOR EACH ROW + EXECUTE FUNCTION guard_version_asset_export_snapshot(); + +CREATE FUNCTION guard_frozen_game_asset_source() RETURNS trigger AS $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM version_asset_export_item i + WHERE i.tenant_id = OLD.tenant_id AND i.asset_id = OLD.id + ) THEN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'game asset source rows are immutable while a frozen version snapshot references them' + USING ERRCODE = 'check_violation'; + END IF; + IF NEW.id IS DISTINCT FROM OLD.id + OR NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.file_name IS DISTINCT FROM OLD.file_name + OR NEW.content_type IS DISTINCT FROM OLD.content_type + OR NEW.data IS DISTINCT FROM OLD.data THEN + RAISE EXCEPTION 'game asset source rows are immutable while a frozen version snapshot references them' + USING ERRCODE = 'check_violation'; + END IF; + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_game_assets_frozen_source + BEFORE UPDATE OR DELETE ON game_assets + FOR EACH ROW + EXECUTE FUNCTION guard_frozen_game_asset_source(); + +CREATE FUNCTION reject_frozen_asset_publication_truncate() RETURNS trigger AS $$ +BEGIN + IF TG_TABLE_NAME = 'game_assets' AND EXISTS ( + SELECT 1 FROM version_asset_export_item + ) THEN + RAISE EXCEPTION 'game asset source rows are retained by frozen version snapshots' + USING ERRCODE = 'check_violation'; + END IF; + IF TG_TABLE_NAME IN ('version_asset', 'version_asset_export_item', 'version_asset_export_snapshot') + AND EXISTS (SELECT 1 FROM version_asset_export_snapshot) THEN + RAISE EXCEPTION 'frozen version asset publication evidence cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_game_assets_frozen_source_no_truncate + BEFORE TRUNCATE ON game_assets + FOR EACH STATEMENT + EXECUTE FUNCTION reject_frozen_asset_publication_truncate(); + +CREATE TRIGGER trg_version_asset_mapping_no_truncate + BEFORE TRUNCATE ON version_asset + FOR EACH STATEMENT + EXECUTE FUNCTION reject_frozen_asset_publication_truncate(); + +CREATE TRIGGER trg_version_asset_export_item_no_truncate + BEFORE TRUNCATE ON version_asset_export_item + FOR EACH STATEMENT + EXECUTE FUNCTION reject_frozen_asset_publication_truncate(); + +CREATE TRIGGER trg_version_asset_export_snapshot_no_truncate + BEFORE TRUNCATE ON version_asset_export_snapshot + FOR EACH STATEMENT + EXECUTE FUNCTION reject_frozen_asset_publication_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V38__published_asset_digest_evidence.sql b/services/game-design-service/src/main/resources/db/migration/V38__published_asset_digest_evidence.sql new file mode 100644 index 0000000000..ac4bf05d03 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V38__published_asset_digest_evidence.sql @@ -0,0 +1,75 @@ +ALTER TABLE published_release_bundle + ADD COLUMN manifest_schema_version INTEGER, + ADD COLUMN artifact_digests_json TEXT, + ADD CONSTRAINT chk_published_asset_digest_evidence_shape CHECK ( + (manifest_schema_version IS NULL AND artifact_digests_json IS NULL) + OR (manifest_schema_version IS NOT NULL AND manifest_schema_version = 1 + AND artifact_digests_json IS NOT NULL) + ); + +-- Existing immutable release rows remain explicitly without complete asset proof. +-- V35.2's INSERT/UPDATE/DELETE guard also protects these added attestation fields. +-- Do not backfill retained evidence from mutable assets or object-store listings. + +ALTER TABLE version_asset_artifact + ADD COLUMN manifest_schema_version INTEGER, + ADD COLUMN artifact_digests_json TEXT, + ADD COLUMN published_object_proofs_json TEXT, + ADD COLUMN candidate_snapshot_version_id BIGINT, + ADD CONSTRAINT chk_asset_export_candidate_evidence CHECK ( + (manifest_schema_version IS NULL AND artifact_digests_json IS NULL + AND published_object_proofs_json IS NULL AND candidate_snapshot_version_id IS NULL) + OR (manifest_schema_version IS NOT NULL AND manifest_schema_version = 1 + AND artifact_digests_json IS NOT NULL + AND published_object_proofs_json IS NOT NULL + AND candidate_snapshot_version_id IS NOT NULL AND manifest_hash IS NOT NULL + AND candidate_snapshot_version_id = version_id + AND manifest_hash ~ '^sha256:[0-9a-f]{64}$') + ), + ADD CONSTRAINT fk_asset_export_candidate_snapshot + FOREIGN KEY (tenant_id, candidate_snapshot_version_id) + REFERENCES version_asset_export_snapshot (tenant_id, version_id); + +-- [jooq ignore start] +CREATE FUNCTION guard_asset_export_candidate_evidence() RETURNS TRIGGER AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.manifest_schema_version IS NOT NULL THEN + RAISE EXCEPTION 'ASSET_EXPORT_CANDIDATE_RETENTION_REQUIRED'; + END IF; + RETURN OLD; + END IF; + IF OLD.manifest_schema_version IS NOT NULL AND ( + NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.version_id IS DISTINCT FROM OLD.version_id + OR NEW.exported_version_number IS DISTINCT FROM OLD.exported_version_number + OR NEW.manifest_hash IS DISTINCT FROM OLD.manifest_hash + OR NEW.manifest_schema_version IS DISTINCT FROM OLD.manifest_schema_version + OR NEW.artifact_digests_json IS DISTINCT FROM OLD.artifact_digests_json + OR NEW.published_object_proofs_json IS DISTINCT FROM OLD.published_object_proofs_json + OR NEW.candidate_snapshot_version_id IS DISTINCT FROM OLD.candidate_snapshot_version_id + OR NEW.exported_manifest_asset_keys_json IS DISTINCT FROM OLD.exported_manifest_asset_keys_json + ) THEN + RAISE EXCEPTION 'ASSET_EXPORT_CANDIDATE_IMMUTABLE'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_asset_export_candidate_immutable + BEFORE UPDATE OR DELETE ON version_asset_artifact + FOR EACH ROW EXECUTE FUNCTION guard_asset_export_candidate_evidence(); + +CREATE FUNCTION guard_asset_export_candidate_truncate() RETURNS TRIGGER AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM version_asset_artifact WHERE manifest_schema_version IS NOT NULL) THEN + RAISE EXCEPTION 'ASSET_EXPORT_CANDIDATE_RETENTION_REQUIRED'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_asset_export_candidate_no_truncate + BEFORE TRUNCATE ON version_asset_artifact + FOR EACH STATEMENT EXECUTE FUNCTION guard_asset_export_candidate_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql b/services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql new file mode 100644 index 0000000000..b002f13613 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql @@ -0,0 +1,11 @@ +ALTER TABLE published_release_bundle + ALTER COLUMN generation_config_revision TYPE TEXT; + +ALTER TABLE launch_descriptor + ALTER COLUMN generation_config_revision TYPE TEXT; + +ALTER TABLE version_asset_artifact + ALTER COLUMN last_error_message TYPE TEXT; + +ALTER TABLE publish_attempt + ALTER COLUMN failure_message TYPE TEXT; diff --git a/services/game-design-service/src/main/resources/db/migration/V40__publish_attempt_ability_schema_digest.sql b/services/game-design-service/src/main/resources/db/migration/V40__publish_attempt_ability_schema_digest.sql new file mode 100644 index 0000000000..559b432b86 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V40__publish_attempt_ability_schema_digest.sql @@ -0,0 +1,2 @@ +ALTER TABLE publish_attempt_participant_digest + ADD COLUMN ability_schema_digest VARCHAR(128); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java index 2745d88a1f..222c5e985b 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java @@ -36,11 +36,14 @@ @Testcontainers(disabledWithoutDocker = true) class PublishedReleaseCanonicalIdentityIntegrationTest { + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final String OTHER_MANIFEST_HASH = "sha256:" + "b".repeat(64); private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; private static final MigrationVersion V35 = MigrationVersion.fromVersion("35"); private static final MigrationVersion V35_1 = MigrationVersion.fromVersion("35.1"); private static final MigrationVersion V35_2 = MigrationVersion.fromVersion("35.2"); private static final MigrationVersion V36 = MigrationVersion.fromVersion("36"); + private static final MigrationVersion V38 = MigrationVersion.fromVersion("38"); private static final Table VERSION = DSL.table(DSL.name("version")); private static final Table RELEASE_BUNDLE = DSL.table(DSL.name("published_release_bundle")); private static final Field ID = DSL.field(DSL.name("id"), Long.class); @@ -52,6 +55,10 @@ class PublishedReleaseCanonicalIdentityIntegrationTest { DSL.field(DSL.name("canonical_tenant_id"), UUID.class); private static final Field CANONICAL_VERSION_ID = DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field MANIFEST_SCHEMA_VERSION = + DSL.field(DSL.name("manifest_schema_version"), Integer.class); + private static final Field ARTIFACT_DIGESTS_JSON = + DSL.field(DSL.name("artifact_digests_json"), String.class); private static final UUID NIL_UUID = new UUID(0L, 0L); @Container @@ -88,6 +95,18 @@ void migrationLeavesRetainedReleaseTupleAndXminUnchangedAndUnmapped() { assertThat(retainedTuple(fixture.dsl(), retainedBundleId)).isEqualTo(retainedTupleBefore); assertThat(bundleXmin(fixture.dsl(), retainedBundleId)).isEqualTo(retainedXminBefore); + assertThat( + fixture + .dsl() + .select(CANONICAL_TENANT_ID, CANONICAL_VERSION_ID) + .from(RELEASE_BUNDLE) + .where(ID.eq(retainedBundleId)) + .fetchOne()) + .satisfies( + row -> { + assertThat(row.get(CANONICAL_TENANT_ID)).isNull(); + assertThat(row.get(CANONICAL_VERSION_ID)).isNull(); + }); assertThat( fixture .dsl() @@ -96,6 +115,23 @@ void migrationLeavesRetainedReleaseTupleAndXminUnchangedAndUnmapped() { .where(ID.eq(retainedBundleId)) .fetchOne(PUBLISHED_RELEASE_BUNDLE_REF)) .isNull(); + + // V38 only adds nullable proof columns; it must not rewrite or invent proof for this row. + migrate(fixture.dataSource(), fixture.schema(), V38); + assertThat(retainedTuple(fixture.dsl(), retainedBundleId)).isEqualTo(retainedTupleBefore); + assertThat(bundleXmin(fixture.dsl(), retainedBundleId)).isEqualTo(retainedXminBefore); + assertThat( + fixture + .dsl() + .select(MANIFEST_SCHEMA_VERSION, ARTIFACT_DIGESTS_JSON) + .from(RELEASE_BUNDLE) + .where(ID.eq(retainedBundleId)) + .fetchOne()) + .satisfies( + row -> { + assertThat(row.get(MANIFEST_SCHEMA_VERSION)).isNull(); + assertThat(row.get(ARTIFACT_DIGESTS_JSON)).isNull(); + }); PublishedReleaseBundle retained = fixture .releaseBundleRepository() @@ -104,6 +140,8 @@ void migrationLeavesRetainedReleaseTupleAndXminUnchangedAndUnmapped() { assertThat(retained.getCanonicalTenantId()).isNull(); assertThat(retained.getCanonicalVersionId()).isNull(); assertThat(retained.getPublishedReleaseBundleRef()).isNull(); + assertThat(retained.getManifestSchemaVersion()).isNull(); + assertThat(retained.getArtifactDigestsJson()).isNull(); assertThatThrownBy(() -> fixture.releaseBundleRepository().save(retained)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Published release bundle is immutable"); @@ -119,7 +157,7 @@ void migrationLeavesRetainedReleaseTupleAndXminUnchangedAndUnmapped() { @Test void normalSavePersistsExactVersionAndVerifiedGameIdentityAndReadsBackWithinTransaction() { - Fixture fixture = fixture(V36); + Fixture fixture = fixture(V38); Game owner = saveGame(fixture, "fresh-release-source"); Game other = saveGame(fixture, "other-release-source"); Version version = saveVersion(fixture, owner); @@ -172,7 +210,7 @@ void normalSavePersistsExactVersionAndVerifiedGameIdentityAndReadsBackWithinTran @Test void repositoryNestedTransactionRollsBackWithOuterSpringPublisherTransaction() { - Fixture fixture = fixture(V36); + Fixture fixture = fixture(V38); Game owner = saveGame(fixture, "outer-release-rollback-owner"); Version version = saveVersion(fixture, owner); String versionXminBefore = versionXmin(fixture.dsl(), version.getId()); @@ -242,7 +280,7 @@ void repositoryNestedTransactionRollsBackWithOuterSpringPublisherTransaction() { @Test void deniesWrongTenantNilAndSubstitutedCallerOrDatabaseIdentityWithoutGrowingBundles() { - Fixture fixture = fixture(V36); + Fixture fixture = fixture(V38); Game owner = saveGame(fixture, "denied-release-owner"); Game other = saveGame(fixture, "denied-release-other"); Version version = saveVersion(fixture, owner); @@ -343,6 +381,32 @@ void bundleIdentityIsImmutableRetainedNullCannotBeBackfilledAndMetadataCannotBeD .fetchOne(PUBLISHED_RELEASE_BUNDLE_REF)) .isNull(); + Map retainedTupleBeforeV38 = retainedTuple(fixture.dsl(), retainedBundleId); + String retainedXminBeforeV38 = bundleXmin(fixture.dsl(), retainedBundleId); + migrate(fixture.dataSource(), fixture.schema(), V38); + assertThat(retainedTuple(fixture.dsl(), retainedBundleId)).isEqualTo(retainedTupleBeforeV38); + assertThat(bundleXmin(fixture.dsl(), retainedBundleId)).isEqualTo(retainedXminBeforeV38); + assertThat( + fixture + .dsl() + .select( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + PUBLISHED_RELEASE_BUNDLE_REF, + MANIFEST_SCHEMA_VERSION, + ARTIFACT_DIGESTS_JSON) + .from(RELEASE_BUNDLE) + .where(ID.eq(retainedBundleId)) + .fetchOne()) + .satisfies( + row -> { + assertThat(row.get(CANONICAL_TENANT_ID)).isNull(); + assertThat(row.get(CANONICAL_VERSION_ID)).isNull(); + assertThat(row.get(PUBLISHED_RELEASE_BUNDLE_REF)).isNull(); + assertThat(row.get(MANIFEST_SCHEMA_VERSION)).isNull(); + assertThat(row.get(ARTIFACT_DIGESTS_JSON)).isNull(); + }); + Version mappedVersion = saveVersion(fixture, game); PublishedReleaseBundle mapped = fixture.releaseBundleRepository().save(bundle(game.getTenantId(), mappedVersion.getId())); @@ -360,7 +424,7 @@ void bundleIdentityIsImmutableRetainedNullCannotBeBackfilledAndMetadataCannotBeD assertThatThrownBy(() -> fixture.releaseBundleRepository().save(exactReadback)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Published release bundle is immutable"); - exactReadback.setManifestHash("sha256:attempted-release-metadata-mutation"); + exactReadback.setManifestHash(OTHER_MANIFEST_HASH); assertThatThrownBy(() -> fixture.releaseBundleRepository().save(exactReadback)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Published release bundle is immutable"); @@ -370,7 +434,7 @@ void bundleIdentityIsImmutableRetainedNullCannotBeBackfilledAndMetadataCannotBeD fixture .dsl() .update(RELEASE_BUNDLE) - .set(DSL.field(DSL.name("manifest_hash"), String.class), "sha256:forged") + .set(DSL.field(DSL.name("manifest_hash"), String.class), OTHER_MANIFEST_HASH) .where(ID.eq(mapped.getId())) .execute()) .isInstanceOf(DataAccessException.class) @@ -410,7 +474,7 @@ void bundleIdentityIsImmutableRetainedNullCannotBeBackfilledAndMetadataCannotBeD fixture .dsl() .update(RELEASE_BUNDLE) - .set(DSL.field(DSL.name("manifest_hash"), String.class), "sha256:forged") + .set(DSL.field(DSL.name("manifest_hash"), String.class), OTHER_MANIFEST_HASH) .where(ID.eq(retainedBundleId)) .execute()) .isInstanceOf(DataAccessException.class) @@ -472,7 +536,7 @@ void bundleIdentityIsImmutableRetainedNullCannotBeBackfilledAndMetadataCannotBeD assertThat(retainedAfterAttempts.getCanonicalTenantId()).isNull(); assertThat(retainedAfterAttempts.getCanonicalVersionId()).isNull(); assertThat(retainedAfterAttempts.getPublishedReleaseBundleRef()).isNull(); - assertThat(retainedAfterAttempts.getManifestHash()).isEqualTo("sha256:retained"); + assertThat(retainedAfterAttempts.getManifestHash()).isEqualTo(MANIFEST_HASH); assertThatThrownBy( () -> fixture.dsl().deleteFrom(RELEASE_BUNDLE).where(ID.eq(mapped.getId())).execute()) @@ -576,10 +640,11 @@ private Long insertRetainedBundle(DSLContext dsl, String tenantId, Long versionI + "generation_config_revision, required_manifest_asset_keys_json, " + "participant_digests_json, command_definitions_json, script_only, " + "script_patch_version) VALUES (?, ?, 4, 'v1', 'retained-workflow', " - + "'sha256:retained', 'retained-config', '[\"asset-a\"]', '[]', '[]', FALSE, NULL) " + + "?, 'retained-config', '[\"asset-a\"]', '[]', '[]', FALSE, NULL) " + "RETURNING id", tenantId, - versionId) + versionId, + MANIFEST_HASH) .fetchOne(0, Long.class); } @@ -590,7 +655,9 @@ private PublishedReleaseBundle bundle(String tenantId, Long versionId) { bundle.setVersionNumber(1); bundle.setAttestationSchemaVersion("v1"); bundle.setPublishWorkflowId("workflow-" + versionId); - bundle.setManifestHash("sha256:manifest"); + bundle.setManifestHash(MANIFEST_HASH); + bundle.setManifestSchemaVersion(1); + bundle.setArtifactDigestsJson("[]"); bundle.setGenerationConfigRevision("generation-1"); bundle.setRequiredManifestAssetKeysJson("[]"); bundle.setParticipantDigestsJson("[]"); @@ -608,12 +675,14 @@ private void insertRawBundle( "INSERT INTO published_release_bundle (tenant_id, version_id, version_number, " + "attestation_schema_version, publish_workflow_id, manifest_hash, " + "generation_config_revision, required_manifest_asset_keys_json, " - + "participant_digests_json, command_definitions_json, script_only, " + + "participant_digests_json, command_definitions_json, manifest_schema_version, " + + "artifact_digests_json, script_only, " + "canonical_tenant_id, canonical_version_id, published_release_bundle_ref) " - + "VALUES (?, ?, 1, 'v1', 'direct-write-test', 'sha256:raw', 'generation-1', " - + "'[]', '[]', '[]', FALSE, ?, ?, ?)", + + "VALUES (?, ?, 1, 'v1', 'direct-write-test', ?, 'generation-1', " + + "'[]', '[]', '[]', 1, '[]', FALSE, ?, ?, ?)", tenantId, versionId, + MANIFEST_HASH, canonicalTenantId, canonicalVersionId, UUID.randomUUID().toString()); @@ -644,7 +713,8 @@ private Map releaseBundleTuple(DSLContext dsl, Long bundleId) { + "version_number, attestation_schema_version, publish_workflow_id, " + "manifest_hash, generation_config_revision, " + "required_manifest_asset_keys_json, participant_digests_json, " - + "command_definitions_json, script_only, script_patch_version, published_at " + + "command_definitions_json, script_only, script_patch_version, published_at, " + + "manifest_schema_version, artifact_digests_json " + "FROM published_release_bundle WHERE id = ?", bundleId), "Published release bundle tuple query returned no row") diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryIntegrationTest.java index 7a283b5d41..2e88f4a89d 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryIntegrationTest.java @@ -3,9 +3,13 @@ import static org.assertj.core.api.Assertions.assertThat; import java.time.LocalDateTime; +import java.util.UUID; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import org.junit.jupiter.api.Test; @@ -14,6 +18,8 @@ import org.springframework.context.annotation.Import; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @@ -44,6 +50,52 @@ static void configure(DynamicPropertyRegistry registry) { } @Autowired private VersionAssetArtifactRepository repository; + @Autowired private VersionAssetArtifactService artifactService; + @Autowired private GameRepository gameRepository; + @Autowired private VersionRepository versionRepository; + @Autowired private PlatformTransactionManager transactionManager; + + @Test + void stagedIntentCommitsThroughSpringProxyBeforeCallingTransactionRollsBack() { + TransactionTemplate owner = new TransactionTemplate(transactionManager); + Game game = new Game(); + game.setTenantId(UUID.randomUUID().toString()); + game.setName("staged intent proof"); + game.setDescription("actual owner source"); + Game storedGame = owner.execute(status -> gameRepository.save(game)); + assertThat(storedGame).isNotNull(); + Version version = new Version(); + version.setTenantId(storedGame.getTenantId()); + version.setVersionNumber(1); + version.setNotes("staged intent proof"); + Version storedVersion = owner.execute(status -> versionRepository.save(version)); + assertThat(storedVersion).isNotNull(); + String workflow = "stable-staged-proof-" + UUID.randomUUID(); + var committed = + owner.execute( + status -> { + var staged = + artifactService.stageExport( + storedGame.getTenantId(), storedVersion.getId(), 1, workflow); + status.setRollbackOnly(); + return staged; + }); + assertThat(committed).isNotNull(); + assertThat(committed.artifactState()).isEqualTo("STAGED"); + assertThat(committed.stateEpoch()).isEqualTo(1L); + assertThat(artifactService.getState(storedGame.getTenantId(), storedVersion.getId())) + .isEqualTo(committed); + assertThat( + artifactService.stageExport( + storedGame.getTenantId(), storedVersion.getId(), 1, workflow)) + .isEqualTo(committed); + assertThat( + repository + .findByTenantIdAndVersionId(storedGame.getTenantId(), storedVersion.getId()) + .orElseThrow() + .getManifestSchemaVersion()) + .isNull(); + } @Test void saveAndFindRoundTripTimestampFields() { @@ -75,6 +127,7 @@ void saveAndFindRoundTripTimestampFields() { LocalDateTime updatedAt = LocalDateTime.of(2026, 1, 1, 0, 0); reloaded.setUpdatedAt(updatedAt); reloaded.setManifestHash("demo-manifest-hash-2"); + reloaded.setStateEpoch(Math.addExact(reloaded.getStateEpoch(), 1L)); repository.save(reloaded); VersionAssetArtifact updated = repository.findByTenantIdAndVersionId("1", 7L).orElseThrow(); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepositoryIntegrationTest.java new file mode 100644 index 0000000000..e90531313e --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepositoryIntegrationTest.java @@ -0,0 +1,801 @@ +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.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.common.config.PostgresProperties; +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.repository.GameAssetRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.AssetSelection; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.impl.VersionAssetPublicationServiceImpl; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.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 VersionAssetPublicationRepositoryIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final MigrationVersion V35 = MigrationVersion.fromVersion("35"); + private static final MigrationVersion V37 = MigrationVersion.fromVersion("37"); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @org.junit.jupiter.api.Test + void v37LeavesRetainedVersionTupleAndXminUnchangedAndDeniesItsUnmappedIdentity() { + Fixture fixture = fixture(V35); + Game game = saveGame(fixture, "retained-publication-owner"); + long retainedVersionId = insertRetainedVersion(fixture.dsl(), game.getTenantId()); + byte[] retainedSourceBytes = bytes("retained asset source"); + GameAsset retainedSource = + saveAsset(fixture, game.getTenantId(), "retained.png", "image/png", retainedSourceBytes); + Map retainedTupleBefore = + retainedVersionTuple(fixture.dsl(), retainedVersionId); + Map sourceTupleBefore = assetTuple(fixture.dsl(), retainedSource.getId()); + String retainedXminBefore = versionXmin(fixture.dsl(), retainedVersionId); + String sourceXminBefore = assetXmin(fixture.dsl(), retainedSource.getId()); + + migrate(fixture.dataSource(), fixture.schema(), V37); + Fixture migrated = fixtureFromSchema(fixture.schema(), fixture.dataSource()); + + assertThat(retainedVersionTuple(migrated.dsl(), retainedVersionId)) + .isEqualTo(retainedTupleBefore); + assertThat(assetTuple(migrated.dsl(), retainedSource.getId())).isEqualTo(sourceTupleBefore); + assertThat(assetData(migrated.dsl(), retainedSource.getId())).isEqualTo(retainedSourceBytes); + assertThat(versionXmin(migrated.dsl(), retainedVersionId)).isEqualTo(retainedXminBefore); + assertThat(assetXmin(migrated.dsl(), retainedSource.getId())).isEqualTo(sourceXminBefore); + assertThatThrownBy( + () -> + migrated + .service() + .associateDraftAsset( + game.getTenantId(), retainedVersionId, retainedSource.getId(), "logo")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("complete canonical owner identity"); + assertThat(mappingCount(migrated.dsl(), game.getTenantId(), retainedVersionId)).isZero(); + assertThat(versionXmin(migrated.dsl(), retainedVersionId)).isEqualTo(retainedXminBefore); + } + + @org.junit.jupiter.api.Test + void freezesOnlyExactMappedBytesAndRetriesFromCommittedSnapshotAfterNewAssetAndServiceRestart() { + Fixture fixture = fixture(V37); + Game game = saveGame(fixture, "snapshot-retry-owner"); + Version version = saveVersion(fixture, game, 1); + byte[] selectedBytes = bytes("mapped bytes survive retry"); + GameAsset selected = + saveAsset(fixture, game.getTenantId(), "logo-雪.png", "image/png", selectedBytes); + String supplementaryUsageKey = new String(Character.toChars(0x10000)) + "-asset.bin"; + String privateUseUsageKey = "\uE000-asset.bin"; + GameAsset supplementary = + saveAsset( + fixture, + game.getTenantId(), + supplementaryUsageKey, + "application/octet-stream", + bytes("supplementary")); + GameAsset privateUse = + saveAsset( + fixture, + game.getTenantId(), + privateUseUsageKey, + "application/octet-stream", + bytes("private use")); + saveAsset(fixture, game.getTenantId(), "unmapped.css", "text/css", bytes("not selected")); + + fixture + .service() + .associateDraftAsset(game.getTenantId(), version.getId(), selected.getId(), "logo"); + fixture + .service() + .associateDraftAsset(game.getTenantId(), version.getId(), selected.getId(), "logo"); + fixture + .service() + .associateDraftAsset(game.getTenantId(), version.getId(), supplementary.getId(), "binary"); + fixture + .service() + .associateDraftAsset(game.getTenantId(), version.getId(), privateUse.getId(), "binary"); + ExportSnapshot first = fixture.service().freezeOrReadSnapshot(game.getTenantId(), 1); + assertThat(first.tenantId()).isEqualTo(game.getTenantId()); + assertThat(first.versionId()).isEqualTo(version.getId()); + assertThat(first.versionNumber()).isEqualTo(1); + assertThat(first.capturedVersionStateEpoch()).isEqualTo(1L); + assertThat(first.canonicalTenantId()).isEqualTo(game.getCanonicalTenantId()); + assertThat(first.canonicalVersionId()).isEqualTo(version.getCanonicalVersionId()); + assertThat(first.items()).hasSize(3); + assertThat(first.items().get(0).usageKey()).isEqualTo("logo-雪.png"); + assertThat(first.items().get(0).assetId()).isEqualTo(selected.getId()); + assertThat(first.items().get(0).contentType()).isEqualTo("image/png"); + assertThat(first.items().get(0).contentDigest()).isEqualTo(sha256(selectedBytes)); + assertThat(first.items().get(0).bytes()).isEqualTo(selectedBytes); + assertThat(first.items().get(1).usageKey()).isEqualTo(privateUseUsageKey); + assertThat(first.items().get(2).usageKey()).isEqualTo(supplementaryUsageKey); + assertThat( + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT item_count FROM version_asset_export_snapshot WHERE tenant_id = ? AND version_id = ?", + game.getTenantId(), + version.getId()), + "Expected frozen snapshot header row") + .get("item_count", Integer.class)) + .isEqualTo(3); + + saveAsset( + fixture, game.getTenantId(), "added-after-freeze.svg", "image/svg+xml", bytes("late")); + fixture + .dsl() + .execute( + "UPDATE version SET version_state = 'RETIRED', version_state_epoch = 2 " + + "WHERE tenant_id = ? AND id = ?", + game.getTenantId(), + version.getId()); + Fixture restarted = fixtureFromSchema(fixture.schema(), fixture.dataSource()); + ExportSnapshot retried = restarted.service().freezeOrReadSnapshot(game.getTenantId(), 1); + assertSameSelection(first, retried); + assertSameSelection(first, restarted.service().readFrozenSnapshot(game.getTenantId(), 1)); + assertThatThrownBy( + () -> + restarted + .service() + .associateDraftAsset( + game.getTenantId(), version.getId(), selected.getId(), "different")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Draft Version"); + } + + @org.junit.jupiter.api.Test + void durableHeaderDistinguishesProvedEmptySelectionFromMissingSnapshot() { + Fixture fixture = fixture(V37); + Game game = saveGame(fixture, "empty-snapshot-owner"); + saveVersion(fixture, game, 1); + + assertThatThrownBy(() -> fixture.service().readFrozenSnapshot(game.getTenantId(), 1)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No durable frozen"); + + ExportSnapshot empty = fixture.service().freezeOrReadSnapshot(game.getTenantId(), 1); + assertThat(empty.items()).isEmpty(); + assertThat(fixture.service().readFrozenSnapshot(game.getTenantId(), 1).items()).isEmpty(); + assertThat( + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT item_count FROM version_asset_export_snapshot WHERE tenant_id = ? AND version_id = ?", + game.getTenantId(), + empty.versionId()), + "Expected proved empty snapshot header row") + .get("item_count", Integer.class)) + .isZero(); + + int versionNumber = 2; + for (String state : List.of("PUBLISHED", "ACTIVE", "RETIRED")) { + int retainedVersionNumber = versionNumber; + Version retainedLifecycleVersion = saveVersion(fixture, game, retainedVersionNumber); + fixture + .dsl() + .execute( + "UPDATE version SET version_state = ?, version_state_epoch = 2 " + + "WHERE tenant_id = ? AND id = ?", + state, + game.getTenantId(), + retainedLifecycleVersion.getId()); + assertThatThrownBy( + () -> fixture.service().readFrozenSnapshot(game.getTenantId(), retainedVersionNumber)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No durable frozen"); + assertThatThrownBy( + () -> + fixture.service().freezeOrReadSnapshot(game.getTenantId(), retainedVersionNumber)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Draft Version"); + versionNumber++; + } + int unexpectedVersionNumber = versionNumber; + Version unexpectedState = saveVersion(fixture, game, unexpectedVersionNumber); + fixture + .dsl() + .execute( + "UPDATE version SET version_state = 'UNEXPECTED' WHERE tenant_id = ? AND id = ?", + game.getTenantId(), + unexpectedState.getId()); + assertThatThrownBy( + () -> + fixture.service().freezeOrReadSnapshot(game.getTenantId(), unexpectedVersionNumber)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unexpected lifecycle state"); + } + + @org.junit.jupiter.api.Test + void deniesTenantIdentityAndUsageCollisionsWithoutMutatingOwnerRows() { + Fixture fixture = fixture(V37); + Game owner = saveGame(fixture, "association-owner"); + Game other = saveGame(fixture, "association-other"); + Version version = saveVersion(fixture, owner, 1); + Version otherVersion = saveVersion(fixture, other, 1); + GameAsset first = + saveAsset( + fixture, owner.getTenantId(), "same-name.bin", "application/octet-stream", bytes("a")); + GameAsset duplicateKey = + saveAsset( + fixture, owner.getTenantId(), "same-name.bin", "application/octet-stream", bytes("b")); + GameAsset foreignAsset = + saveAsset( + fixture, other.getTenantId(), "foreign.bin", "application/octet-stream", bytes("f")); + + fixture + .service() + .associateDraftAsset(owner.getTenantId(), version.getId(), first.getId(), null); + String versionXminBefore = versionXmin(fixture.dsl(), version.getId()); + String ownerXminBefore = gameXmin(fixture.dsl(), owner.getId()); + String sourceXminBefore = assetXmin(fixture.dsl(), first.getId()); + List deniedWrites = + List.of( + () -> + fixture + .service() + .associateDraftAsset( + owner.getTenantId(), version.getId(), duplicateKey.getId(), null), + () -> + fixture + .service() + .associateDraftAsset( + owner.getTenantId(), version.getId(), foreignAsset.getId(), null), + () -> + fixture + .service() + .associateDraftAsset(other.getTenantId(), version.getId(), first.getId(), null), + () -> + fixture + .service() + .associateDraftAsset( + owner.getTenantId(), version.getId(), Long.MAX_VALUE, null), + () -> + fixture + .service() + .associateDraftAsset( + owner.getTenantId(), otherVersion.getId(), first.getId(), null)); + for (ThrowingCallable deniedWrite : deniedWrites) { + assertThatThrownBy(deniedWrite).isInstanceOf(IllegalStateException.class); + } + 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 (?, 5, 'DRAFT', 1, ?, ?, ?, ?, 'NEW_GAME_ROW')", + owner.getTenantId(), + UUID.randomUUID(), + owner.getCanonicalTenantId(), + other.getId(), + other.getTenantId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("exact game row"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "INSERT INTO version_asset " + + "(tenant_id, version_id, asset_id, usage_key, usage_type) VALUES (?, ?, ?, ?, ?)", + owner.getTenantId(), + version.getId(), + foreignAsset.getId(), + "foreign.bin", + "binary")) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "INSERT INTO version_asset " + + "(tenant_id, version_id, asset_id, usage_key, usage_type) VALUES (?, ?, ?, ?, ?)", + owner.getTenantId(), + otherVersion.getId(), + first.getId(), + "same-name.bin", + "binary")) + .isInstanceOf(DataAccessException.class); + + assertThat(mappingCount(fixture.dsl(), owner.getTenantId(), version.getId())).isEqualTo(1); + assertThat(versionXmin(fixture.dsl(), version.getId())).isEqualTo(versionXminBefore); + assertThat(gameXmin(fixture.dsl(), owner.getId())).isEqualTo(ownerXminBefore); + assertThat(assetXmin(fixture.dsl(), first.getId())).isEqualTo(sourceXminBefore); + assertThat(mappingCount(fixture.dsl(), other.getTenantId(), otherVersion.getId())).isZero(); + assertThatThrownBy(() -> fixture.service().readFrozenSnapshot(other.getTenantId(), 1)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No durable frozen"); + } + + @org.junit.jupiter.api.Test + void concurrentDraftMappingAndFirstFreezeSerializeOnTheExactVersionRow() throws Exception { + Fixture fixture = fixture(V37); + Game game = saveGame(fixture, "mapping-freeze-race"); + Version version = saveVersion(fixture, game, 1); + GameAsset asset = + saveAsset( + fixture, game.getTenantId(), "race.bin", "application/octet-stream", bytes("race")); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future mapping = + executor.submit( + () -> { + await(start); + fixture + .service() + .associateDraftAsset( + game.getTenantId(), version.getId(), asset.getId(), "race"); + return null; + }); + Future freeze = + executor.submit( + () -> { + await(start); + return fixture.service().freezeOrReadSnapshot(game.getTenantId(), 1); + }); + start.countDown(); + ExportSnapshot snapshot = freeze.get(20, TimeUnit.SECONDS); + AtomicBoolean mappingCommitted = new AtomicBoolean(true); + try { + mapping.get(20, TimeUnit.SECONDS); + } catch (java.util.concurrent.ExecutionException exception) { + if (!(exception.getCause() instanceof IllegalStateException)) { + throw exception; + } + mappingCommitted.set(false); + } + assertThat(snapshot.items()).hasSize(mappingCommitted.get() ? 1 : 0); + assertThat(mappingCount(fixture.dsl(), game.getTenantId(), version.getId())) + .isEqualTo(mappingCommitted.get() ? 1 : 0); + } finally { + executor.shutdownNow(); + assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + @org.junit.jupiter.api.Test + void frozenSnapshotAndItsRepairSourcesRejectMutationAndSnapshotBuildRollsBackAtomically() { + Fixture fixture = fixture(V37); + Game game = saveGame(fixture, "immutable-snapshot-owner"); + Version version = saveVersion(fixture, game, 1); + byte[] payload = bytes("retained exact bytes"); + GameAsset asset = + saveAsset( + fixture, game.getTenantId(), "immutable.bin", "application/octet-stream", payload); + fixture + .service() + .associateDraftAsset(game.getTenantId(), version.getId(), asset.getId(), "binary"); + + assertThatThrownBy( + () -> + fixture + .transactionTemplate() + .execute( + status -> { + fixture + .dsl() + .execute( + "INSERT INTO version_asset_export_item " + + "(tenant_id, version_id, usage_key, asset_id, content_type, content_hash, byte_size) " + + "VALUES (?, ?, ?, ?, ?, ?, ?)", + game.getTenantId(), + version.getId(), + "immutable.bin", + asset.getId(), + "application/octet-stream", + sha256(payload), + (long) payload.length); + fixture + .dsl() + .execute( + "INSERT INTO version_asset_export_snapshot " + + "(tenant_id, version_id, canonical_tenant_id, canonical_version_id, version_number, " + + "captured_version_state_epoch, item_count) VALUES (?, ?, ?, ?, ?, ?, ?)", + game.getTenantId(), + version.getId(), + game.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getVersionNumber(), + 1L, + 0); + return null; + })) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("item count"); + assertThat( + fixture + .dsl() + .fetchOne( + "SELECT 1 FROM version_asset_export_snapshot WHERE tenant_id = ? AND version_id = ?", + game.getTenantId(), + version.getId())) + .isNull(); + assertThat(fixture.dsl().fetchCount(DSL.table("version_asset_export_item"))).isZero(); + + ExportSnapshot committed = fixture.service().freezeOrReadSnapshot(game.getTenantId(), 1); + assertThat(committed.items()).hasSize(1); + assertThatThrownBy( + () -> + fixture + .service() + .associateDraftAsset( + game.getTenantId(), version.getId(), asset.getId(), "binary")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("frozen by the durable export snapshot"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_assets SET data = ? WHERE tenant_id = ? AND id = ?", + bytes("changed"), + game.getTenantId(), + asset.getId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_assets SET file_name = ? WHERE tenant_id = ? AND id = ?", + "renamed.bin", + game.getTenantId(), + asset.getId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_assets SET content_type = ? WHERE tenant_id = ? AND id = ?", + "application/x-other", + game.getTenantId(), + asset.getId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_assets SET tenant_id = ? WHERE tenant_id = ? AND id = ?", + "another-tenant", + game.getTenantId(), + asset.getId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "DELETE FROM game_assets WHERE tenant_id = ? AND id = ?", + game.getTenantId(), + asset.getId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE version_asset_export_item SET content_hash = ? " + + "WHERE tenant_id = ? AND version_id = ?", + sha256(bytes("changed")), + game.getTenantId(), + version.getId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "DELETE FROM version_asset_export_snapshot WHERE tenant_id = ? AND version_id = ?", + game.getTenantId(), + version.getId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE version_asset_export_snapshot SET item_count = 0 " + + "WHERE tenant_id = ? AND version_id = ?", + game.getTenantId(), + version.getId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE version_asset SET usage_type = 'changed' " + + "WHERE tenant_id = ? AND version_id = ?", + game.getTenantId(), + version.getId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("frozen"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "DELETE FROM version_asset WHERE tenant_id = ? AND version_id = ?", + game.getTenantId(), + version.getId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("frozen"); + assertThat(fixture.service().readFrozenSnapshot(game.getTenantId(), 1).items().get(0).bytes()) + .isEqualTo(payload); + } + + @org.junit.jupiter.api.Test + void committedSnapshotSurvivesCallingTransactionRollback() { + Fixture fixture = fixture(V37); + Game game = saveGame(fixture, "requires-new-snapshot-owner"); + saveVersion(fixture, game, 1); + TransactionTemplate outer = fixture.transactionTemplate(); + + outer.execute( + status -> { + assertThat(fixture.service().freezeOrReadSnapshot(game.getTenantId(), 1).items()) + .isEmpty(); + status.setRollbackOnly(); + return null; + }); + + assertThat(fixture.service().readFrozenSnapshot(game.getTenantId(), 1).items()).isEmpty(); + assertThat( + fixture + .dsl() + .fetchOne( + "SELECT 1 FROM version_asset_export_snapshot WHERE tenant_id = ?", + game.getTenantId())) + .isNotNull(); + } + + private Fixture fixture(MigrationVersion target) { + String schema = "gd_vasp_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, target); + return fixtureFromSchema(schema, dataSource); + } + + private Fixture fixtureFromSchema(String schema, DriverManagerDataSource dataSource) { + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + GameRepository gameRepository = new GameRepository(dsl); + GameAssetRepository gameAssetRepository = new GameAssetRepository(dsl); + PostgresProperties postgresProperties = new PostgresProperties(); + postgresProperties.setSchema(schema); + VersionRepository versionRepository = new VersionRepository(dsl, postgresProperties); + VersionAssetPublicationRepository publicationRepository = + new VersionAssetPublicationRepository(dsl); + VersionAssetPublicationServiceImpl service = + new VersionAssetPublicationServiceImpl(transactionManager, publicationRepository); + return new Fixture( + schema, + dataSource, + dsl, + transactionTemplate, + gameRepository, + gameAssetRepository, + versionRepository, + service); + } + + 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) { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(target) + .load() + .migrate(); + } + + private Game saveGame(Fixture fixture, String tenantId) { + Game game = new Game(); + game.setTenantId(tenantId); + game.setName("Version asset publication owner"); + game.setDescription("Integration source row"); + return fixture.transactionTemplate().execute(status -> fixture.gameRepository().save(game)); + } + + private Version saveVersion(Fixture fixture, Game game, int versionNumber) { + Version version = new Version(); + version.setTenantId(game.getTenantId()); + version.setVersionNumber(versionNumber); + version.setNotes("version asset publication fixture"); + return fixture + .transactionTemplate() + .execute(status -> fixture.versionRepository().save(version)); + } + + private GameAsset saveAsset( + Fixture fixture, String tenantId, String fileName, String contentType, byte[] data) { + GameAsset asset = new GameAsset(); + asset.setTenantId(tenantId); + asset.setFileName(fileName); + asset.setContentType(contentType); + asset.setData(data); + return fixture + .transactionTemplate() + .execute(status -> fixture.gameAssetRepository().save(asset)); + } + + private long insertRetainedVersion(DSLContext dsl, String tenantId) { + return Objects.requireNonNull( + 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), + "Expected inserted retained Version row"); + } + + private Map retainedVersionTuple(DSLContext dsl, long versionId) { + return Objects.requireNonNull( + dsl.fetchOne( + "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 = ?", + versionId), + "Expected retained Version row") + .intoMap(); + } + + private Map assetTuple(DSLContext dsl, long assetId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT id, tenant_id, file_name, content_type, created_at FROM game_assets WHERE id = ?", + assetId), + "Expected retained asset row") + .intoMap(); + } + + private byte[] assetData(DSLContext dsl, long assetId) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT data FROM game_assets WHERE id = ?", assetId), + "Expected retained asset data row") + .get("data", byte[].class); + } + + private String versionXmin(DSLContext dsl, long versionId) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT xmin::text AS xmin FROM version WHERE id = ?", versionId), + "Expected retained Version xmin row") + .get("xmin", String.class); + } + + private String gameXmin(DSLContext dsl, long gameId) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT xmin::text AS xmin FROM game WHERE id = ?", gameId), + "Expected retained Game xmin row") + .get("xmin", String.class); + } + + private String assetXmin(DSLContext dsl, long assetId) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT xmin::text AS xmin FROM game_assets WHERE id = ?", assetId), + "Expected retained asset xmin row") + .get("xmin", String.class); + } + + private long mappingCount(DSLContext dsl, String tenantId, long versionId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) AS mapping_count FROM version_asset WHERE tenant_id = ? AND version_id = ?", + tenantId, + versionId), + "Expected mapping count aggregate row") + .get("mapping_count", Long.class); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void assertSameSelection(ExportSnapshot expected, ExportSnapshot actual) { + assertThat(actual.tenantId()).isEqualTo(expected.tenantId()); + assertThat(actual.versionId()).isEqualTo(expected.versionId()); + assertThat(actual.versionNumber()).isEqualTo(expected.versionNumber()); + assertThat(actual.capturedVersionStateEpoch()).isEqualTo(expected.capturedVersionStateEpoch()); + assertThat(actual.canonicalTenantId()).isEqualTo(expected.canonicalTenantId()); + assertThat(actual.canonicalVersionId()).isEqualTo(expected.canonicalVersionId()); + assertThat(actual.items()).hasSize(expected.items().size()); + for (int index = 0; index < expected.items().size(); index++) { + AssetSelection expectedItem = expected.items().get(index); + AssetSelection actualItem = actual.items().get(index); + assertThat(actualItem.usageKey()).isEqualTo(expectedItem.usageKey()); + assertThat(actualItem.assetId()).isEqualTo(expectedItem.assetId()); + assertThat(actualItem.contentType()).isEqualTo(expectedItem.contentType()); + assertThat(actualItem.contentDigest()).isEqualTo(expectedItem.contentDigest()); + assertThat(actualItem.bytes()).isEqualTo(expectedItem.bytes()); + } + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent publication test start signal timed out"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Concurrent publication test was interrupted", exception); + } + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + TransactionTemplate transactionTemplate, + GameRepository gameRepository, + GameAssetRepository gameAssetRepository, + VersionRepository versionRepository, + VersionAssetPublicationServiceImpl service) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java index 11e5f795b8..a8f4028f3e 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -115,6 +115,9 @@ void resolvesPersistedSourceAndReplaysOriginalDescriptorAfterDefaultsAndVersionC ResolvedLaunchDescriptorDto original = launchDescriptorService.resolveLaunchDescriptor(fixture.request()); + String generationConfigRevision = fixture.bundle().getGenerationConfigRevision(); + assertThat(generationConfigRevision.length()).isGreaterThan(128); + assertThat(original.generationConfigRevision()).isEqualTo(generationConfigRevision); assertThat(original.canonicalTenantId()).isEqualTo(fixture.canonicalTenantId().toString()); assertThat(original.publishedReleaseBundleRef()) .isEqualTo(fixture.bundle().getPublishedReleaseBundleRef()); @@ -163,6 +166,7 @@ void resolvesPersistedSourceAndReplaysOriginalDescriptorAfterDefaultsAndVersionC .isEqualTo(original.authoredWorldBinding().resultDigest()); assertThat(persisted.getPublishedReleaseBundleRef()) .isEqualTo(original.publishedReleaseBundleRef()); + assertThat(persisted.getGenerationConfigRevision()).isEqualTo(generationConfigRevision); assertThat( dsl.fetchCount( LAUNCH_DESCRIPTOR, @@ -443,6 +447,173 @@ void rolledBackDescriptorInsertLeavesNoCanonicalOrPrivateRequestClaim() { .isEqualTo(evidence.requestDigest()); } + @Test + void v39MigrationPreservesRetainedPublicationEvidenceAndStoresLongDiagnostics() { + String schema = "game_design_publication_text_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = isolatedDataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("34")); + DSLContext isolatedDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + + String tenantId = privateTenantKey(); + String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + // Synthetic pre-identity rows seed migration preservation only; no source identity is inferred. + long versionId = + requiredId( + isolatedDsl + .resultQuery( + "INSERT INTO version " + + "(tenant_id, version_number, version_state, version_state_epoch) " + + "VALUES (?, 1, 'PUBLISHED', 7) RETURNING id", + tenantId) + .fetchOne(0, Long.class), + "retained Version"); + long templateId = + requiredId( + isolatedDsl + .resultQuery( + "INSERT INTO game_templates (tenant_id, name, config) " + + "VALUES (?, ?, '{}'::jsonb) RETURNING id", + tenantId, + "Retained Publication Template " + suffix) + .fetchOne(0, Long.class), + "retained Game Template"); + String generationRevision = "retained-generation-rév-🧭-" + suffix; + long bundleId = + requiredId( + isolatedDsl + .resultQuery( + "INSERT INTO published_release_bundle " + + "(tenant_id, version_id, version_number, attestation_schema_version, " + + "publish_workflow_id, manifest_hash, required_manifest_asset_keys_json, " + + "participant_digests_json, generation_config_revision) " + + "VALUES (?, ?, 1, 'v1', ?, ?, '[]', '[]', ?) RETURNING id", + tenantId, + versionId, + "v38-retained-bundle-" + suffix, + "sha256:" + "f".repeat(64), + generationRevision) + .fetchOne(0, Long.class), + "retained release bundle"); + long descriptorId = + requiredId( + isolatedDsl + .resultQuery( + "INSERT INTO launch_descriptor " + + "(launch_descriptor_id, tenant_id, game_template_id, " + + "control_plane_request_id, request_hash, version_id, runtime_flags_json, " + + "generation_config_revision, version_state_epoch, release_bundle_id, " + + "published_release_bundle_ref) " + + "VALUES (?, ?, ?, ?, ?, ?, '{}', ?, 7, ?, ?) RETURNING id", + "ld-v38-retained-" + suffix, + tenantId, + templateId, + "v38-retained-request-" + suffix, + "retained-request-hash-" + suffix, + versionId, + generationRevision, + bundleId, + "retained-release-ref-" + suffix) + .fetchOne(0, Long.class), + "retained launch descriptor"); + + migrate(dataSource, schema, MigrationVersion.fromVersion("38")); + String retainedFailure = "retained-failure-雪-" + suffix; + String retainedArtifactError = "retained-artifact-error-🧭-" + suffix; + long attemptId = + requiredId( + isolatedDsl + .resultQuery( + "INSERT INTO publish_attempt " + + "(tenant_id, publish_workflow_id, publish_type, status, version_id, " + + "version_number, failure_code, failure_message, completed_at) " + + "VALUES (?, ?, 'FULL_VERSION', 'FAILED', ?, 1, 'PUBLISH_FAILED', ?, " + + "TIMESTAMP '2026-09-30 12:34:56') RETURNING id", + tenantId, + "v38-retained-attempt-" + suffix, + versionId, + retainedFailure) + .fetchOne(0, Long.class), + "retained publish attempt"); + long artifactId = + requiredId( + isolatedDsl + .resultQuery( + "INSERT INTO version_asset_artifact " + + "(tenant_id, version_id, artifact_state, state_epoch, " + + "exported_version_number, manifest_hash, last_workflow_id, " + + "last_error_code, last_error_message) " + + "VALUES (?, ?, 'FAILED', 11, 1, ?, ?, 'PUBLISH_FAILED', ?) RETURNING id", + tenantId, + versionId, + "sha256:" + "a".repeat(64), + "v38-retained-artifact-" + suffix, + retainedArtifactError) + .fetchOne(0, Long.class), + "retained version asset artifact"); + + Map> retainedRows = + publicationEvidenceRows( + isolatedDsl, versionId, bundleId, descriptorId, attemptId, artifactId); + migrate(dataSource, schema, null); + assertThat( + publicationEvidenceRows( + isolatedDsl, versionId, bundleId, descriptorId, attemptId, artifactId)) + .isEqualTo(retainedRows); + assertThat( + requiredSnapshot(retainedRows, "published_release_bundle") + .get("generation_config_revision")) + .isEqualTo(generationRevision); + assertThat( + requiredSnapshot(retainedRows, "launch_descriptor").get("generation_config_revision")) + .isEqualTo(generationRevision); + assertThat(requiredSnapshot(retainedRows, "publish_attempt").get("failure_message")) + .isEqualTo(retainedFailure); + assertThat(requiredSnapshot(retainedRows, "version_asset_artifact").get("last_error_message")) + .isEqualTo(retainedArtifactError); + + String longFailure = "complete-failure-雪-" + "f".repeat(540); + String longArtifactError = "complete-artifact-error-🧭-" + "e".repeat(540); + isolatedDsl.execute( + "UPDATE publish_attempt SET failure_message = ? WHERE id = ?", longFailure, attemptId); + isolatedDsl.execute( + "UPDATE version_asset_artifact SET last_error_message = ? WHERE id = ?", + longArtifactError, + artifactId); + assertThat( + requiredRow( + isolatedDsl, + "SELECT failure_message FROM publish_attempt WHERE id = ?", + attemptId, + "long publish-attempt failure readback") + .get("failure_message")) + .isEqualTo(longFailure); + assertThat( + requiredRow( + isolatedDsl, + "SELECT last_error_message FROM version_asset_artifact WHERE id = ?", + artifactId, + "long artifact-error readback") + .get("last_error_message")) + .isEqualTo(longArtifactError); + assertThat( + requiredRow( + isolatedDsl, + "SELECT status, version_number FROM publish_attempt WHERE id = ?", + attemptId, + "publish-attempt state readback")) + .containsEntry("status", "FAILED") + .containsEntry("version_number", 1); + assertThat( + requiredRow( + isolatedDsl, + "SELECT artifact_state, state_epoch FROM version_asset_artifact WHERE id = ?", + artifactId, + "artifact state readback")) + .containsEntry("artifact_state", "FAILED") + .containsEntry("state_epoch", 11L); + } + @Test void v35AndV36MigrationsPreserveRetainedBundleAndUnboundDescriptorWithoutBackfill() { String schema = "game_design_launch_history_" + UUID.randomUUID().toString().replace("-", ""); @@ -660,7 +831,7 @@ private Fixture fixture(String controlPlaneRequestId) { bundle.setAttestationSchemaVersion("v1"); bundle.setPublishWorkflowId("synthetic-storage-proof-" + suffix); bundle.setManifestHash("sha256:" + "e".repeat(64)); - bundle.setGenerationConfigRevision("gen-rev:" + suffix); + bundle.setGenerationConfigRevision("gen-rev:" + suffix + ":" + "g".repeat(180)); bundle.setRequiredManifestAssetKeysJson("[]"); bundle.setParticipantDigestsJson("[]"); bundle.setScriptOnly(false); @@ -922,6 +1093,67 @@ var record = return record.intoMap(); } + private Map> publicationEvidenceRows( + DSLContext isolatedDsl, + long versionId, + long bundleId, + long descriptorId, + long attemptId, + long artifactId) { + return Map.of( + "version", + requiredRow(isolatedDsl, "SELECT * FROM version WHERE id = ?", versionId, "Version"), + "published_release_bundle", + requiredRow( + isolatedDsl, + "SELECT * FROM published_release_bundle WHERE id = ?", + bundleId, + "published release bundle"), + "launch_descriptor", + requiredRow( + isolatedDsl, + "SELECT * FROM launch_descriptor WHERE id = ?", + descriptorId, + "launch descriptor"), + "publish_attempt", + requiredRow( + isolatedDsl, + "SELECT * FROM publish_attempt WHERE id = ?", + attemptId, + "publish attempt"), + "version_asset_artifact", + requiredRow( + isolatedDsl, + "SELECT * FROM version_asset_artifact WHERE id = ?", + artifactId, + "version asset artifact")); + } + + private Map requiredRow( + DSLContext isolatedDsl, String query, long rowId, String description) { + var row = isolatedDsl.fetchOne(query, rowId); + if (row == null) { + throw new IllegalStateException(description + " readback is absent"); + } + return row.intoMap(); + } + + private Map requiredSnapshot( + Map> snapshots, String description) { + Map snapshot = snapshots.get(description); + if (snapshot == null) { + throw new IllegalStateException(description + " snapshot is absent"); + } + return snapshot; + } + + private long requiredId(Long id, String description) { + if (id == null) { + throw new IllegalStateException(description + " insert returned no identity"); + } + return id; + } + private String privateTenantKey() { return "src-" + UUID.randomUUID().toString().replace("-", ""); } 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 29ba77152d..e40054aecb 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 @@ -14,16 +14,19 @@ import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.PublishAttempt; +import net.firedevops.firemud.gamedesign.entity.PublishAttemptParticipantDigest; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; import net.firedevops.firemud.gamedesign.entity.VersionTemplateRemapSet; import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; +import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; import net.firedevops.firemud.gamedesign.model.PublishType; import net.firedevops.firemud.gamedesign.model.TemplateRemapSetStatus; import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.PublishAttemptParticipantDigestRepository; import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; @@ -67,6 +70,8 @@ class PublishAttemptServiceTransactionIntegrationTest { private static final String TENANT_ID = "9001"; private static final String WORKFLOW_ID = "full-version-transaction-integration-test"; + private static final String TRANSACTION_MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final String FINALIZATION_MANIFEST_HASH = "sha256:" + "b".repeat(64); @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -84,6 +89,8 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private PublishedReleaseBundleRepository publishedReleaseBundleRepository; @Autowired private VersionAssetArtifactRepository versionAssetArtifactRepository; @Autowired private VersionRepository versionRepository; + @Autowired private VersionAssetExportCandidateService versionAssetExportCandidateService; + @Autowired private VersionAssetPublicationService versionAssetPublicationService; @Autowired private VersionTemplateRemapSetRepository templateRemapSetRepository; @Autowired private DSLContext dsl; @MockitoBean private AssetExportService assetExportService; @@ -127,9 +134,11 @@ void fullVersionTransactionRollsBackVersionBundleArtifactAndAttemptTogether() { bundle.setVersionNumber(persistedVersion.getVersionNumber()); bundle.setAttestationSchemaVersion("v1"); bundle.setPublishWorkflowId(WORKFLOW_ID); - bundle.setManifestHash("transaction-proof-manifest"); + bundle.setManifestHash(TRANSACTION_MANIFEST_HASH); + bundle.setManifestSchemaVersion(1); bundle.setGenerationConfigRevision("transaction-proof-generation"); bundle.setRequiredManifestAssetKeysJson("[]"); + bundle.setArtifactDigestsJson("[]"); bundle.setParticipantDigestsJson("[]"); bundle.setCommandDefinitionsJson("[]"); publishedReleaseBundleRepository.save(bundle); @@ -141,6 +150,9 @@ void fullVersionTransactionRollsBackVersionBundleArtifactAndAttemptTogether() { artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); artifact.setStateEpoch(2L); artifact.setManifestHash(bundle.getManifestHash()); + // This manually inserted row proves transaction rollback, not export. + // No durable source snapshot exists in this fixture, so candidate proof + // remains explicitly absent rather than bypassing its required FK. artifact.setLastWorkflowId(WORKFLOW_ID); artifact.setExportedManifestAssetKeysJson("[]"); versionAssetArtifactRepository.save(artifact); @@ -214,6 +226,122 @@ void fullVersionRequestDigestBackfillReturnsEmptyForMismatchedAttemptIdentity() assertThat(storedAttempt.getRequestDigest()).isEqualTo("exact-identity-digest"); } + @Test + void recordsAndIndependentlyReadsDedicatedAbilitySchemaDigestOnPublishAttempt() { + String tenantId = "9010"; + String publishWorkflowId = "full-version-ability-schema-integration-test"; + Game game = new Game(); + game.setTenantId(tenantId); + game.setName("ability-schema-persistence-proof-game"); + gameRepository.save(game); + + Version version = new Version(); + version.setTenantId(tenantId); + version.setVersionNumber(17); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + version.setNotes("ability schema participant persistence proof"); + Version savedVersion = versionRepository.save(version); + String scopeValue = String.valueOf(savedVersion.getId()); + + PublishAttempt attempt = new PublishAttempt(); + attempt.setTenantId(tenantId); + attempt.setPublishWorkflowId(publishWorkflowId); + attempt.setPublishType(PublishType.FULL_VERSION); + attempt.setStatus(PublishAttemptStatus.PENDING); + attempt.setVersionId(savedVersion.getId()); + attempt.setVersionNumber(savedVersion.getVersionNumber()); + PublishAttempt savedAttempt = publishAttemptRepository.save(attempt); + + publishAttemptService.recordFullVersionParticipantDigests( + publishWorkflowId, + List.of( + new PublishParticipantDigestDto( + "GAME_LOGIC", + scopeValue, + null, + "commit-full-version-17", + "sha256:aggregate-game-logic-1", + 1, + "sha256:ability-schema-1", + null, + null), + new PublishParticipantDigestDto( + "GAME_DESIGN_CONTROL_PLANE", + scopeValue, + null, + "commit-full-version-17", + "sha256:aggregate-control-plane-1", + 1, + null, + null, + null), + new PublishParticipantDigestDto( + "WORLD_MANAGEMENT", + scopeValue, + null, + "commit-full-version-17", + "sha256:aggregate-world-1", + 1, + null, + null, + null), + new PublishParticipantDigestDto( + "ENTITY_MANAGEMENT", + scopeValue, + null, + "commit-full-version-17", + "sha256:aggregate-entity-1", + 1, + null, + null, + null), + new PublishParticipantDigestDto( + "AUTOMATION_SCRIPTING", + scopeValue, + null, + "commit-full-version-17", + "sha256:aggregate-automation-1", + 1, + null, + null, + null))); + + List persistedDigests = + new PublishAttemptParticipantDigestRepository(dsl) + .findByPublishAttemptId(savedAttempt.getId()); + + assertThat(savedAttempt.getPublishType()).isEqualTo(PublishType.FULL_VERSION); + assertThat(savedAttempt.getVersionId()).isEqualTo(savedVersion.getId()); + assertThat(persistedDigests).hasSize(5); + PublishAttemptParticipantDigest gameLogicDigest = + persistedDigests.stream() + .filter(digest -> digest.getParticipantKey() == PublishParticipantKey.GAME_LOGIC) + .findFirst() + .orElseThrow(); + assertThat(gameLogicDigest.getParticipantKey()).isEqualTo(PublishParticipantKey.GAME_LOGIC); + assertThat(gameLogicDigest.getScopeValue()).isEqualTo(scopeValue); + assertThat(gameLogicDigest.getBaseVersionId()).isNull(); + assertThat(gameLogicDigest.getAppliedCommitId()).isEqualTo("commit-full-version-17"); + assertThat(gameLogicDigest.getDigestSchemaVersion()).isEqualTo(1); + assertThat(gameLogicDigest.getContentDigest()).isEqualTo("sha256:aggregate-game-logic-1"); + assertThat(gameLogicDigest.getAbilitySchemaDigest()).isEqualTo("sha256:ability-schema-1"); + assertThat(gameLogicDigest.getAbilitySchemaDigest()) + .isNotEqualTo(gameLogicDigest.getContentDigest()); + + assertThat(persistedDigests) + .allSatisfy( + digest -> { + assertThat(digest.getScopeValue()).isEqualTo(scopeValue); + assertThat(digest.getBaseVersionId()).isNull(); + assertThat(digest.getAppliedCommitId()).isEqualTo("commit-full-version-17"); + assertThat(digest.getDigestSchemaVersion()).isEqualTo(1); + }); + assertThat(persistedDigests) + .filteredOn(digest -> digest.getParticipantKey() != PublishParticipantKey.GAME_LOGIC) + .allSatisfy(digest -> assertThat(digest.getAbilitySchemaDigest()).isNull()); + } + @Test void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogether() { String tenantId = "9002"; @@ -248,8 +376,15 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth null)); }); Mockito.when(assetExportService.exportAssets(tenantId, 1)) - .thenReturn( - new ExportedAssetManifest("transaction-proof-manifest", List.of("manifest.json"))); + .thenAnswer( + invocation -> { + int versionNumber = invocation.getArgument(1); + versionAssetPublicationService.freezeOrReadSnapshot(tenantId, versionNumber); + return versionAssetExportCandidateService.recordExportCandidate( + tenantId, + versionNumber, + new ExportedAssetManifest(FINALIZATION_MANIFEST_HASH, 1, List.of(), List.of())); + }); VersionDto publishedVersion = versionPublishCommandService.publishFullVersion( @@ -272,7 +407,7 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth assertThat(attempt.getVersionId()).isEqualTo(publishedVersion.id()); assertThat(storedVersion.getVersionState()).isEqualTo(VersionLifecycleState.PUBLISHED); assertThat(bundle.getPublishWorkflowId()).isEqualTo(publishWorkflowId); - assertThat(bundle.getManifestHash()).isEqualTo("transaction-proof-manifest"); + assertThat(bundle.getManifestHash()).isEqualTo(FINALIZATION_MANIFEST_HASH); assertThat(bundle.getPublishedReleaseBundleRef()).isNotBlank(); assertThat(bundle.getPublishedReleaseBundleRef()) .isNotEqualTo( @@ -318,7 +453,18 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth .findByTenantIdAndVersionId(tenantId, publishedVersion.id()) .orElseThrow() .getManifestHash()) - .isEqualTo("transaction-proof-manifest"); + .isEqualTo(FINALIZATION_MANIFEST_HASH); + String generationConfigRevision = bundle.getGenerationConfigRevision(); + assertThat(generationConfigRevision.length()).isGreaterThan(128); + versionPublishCommandService.publishFullVersion( + tenantId, "successful transaction proof", publishRequestId, publishWorkflowId); + assertThat( + publishedReleaseBundleRepository + .findByTenantIdAndVersionId(tenantId, publishedVersion.id()) + .orElseThrow() + .getGenerationConfigRevision()) + .isEqualTo(generationConfigRevision); + Mockito.verify(assetExportService, Mockito.times(1)).exportAssets(tenantId, 1); assertThat(artifact.getArtifactState()).isEqualTo(VersionAssetArtifactState.PUBLISHED); } @@ -353,6 +499,7 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( AtomicReference exportCallbackFailure = new AtomicReference<>(); AtomicBoolean exportCompleted = new AtomicBoolean(); AtomicBoolean finalizationFailureInjected = new AtomicBoolean(); + String longFailureMessage = "forced finalization failure " + "x".repeat(600); Mockito.when( publishGateService.collectFullVersionParticipantDigests( @@ -388,12 +535,17 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( .assertMatchesRecordedDigests( Mockito.eq(tenantId), Mockito.eq(PublishType.FULL_VERSION), Mockito.anyList()); ExportedAssetManifest exportedManifest = - new ExportedAssetManifest("post-export-finalization-manifest", List.of("manifest.json")); + new ExportedAssetManifest(FINALIZATION_MANIFEST_HASH, 1, List.of(), List.of()); Mockito.when(assetExportService.exportAssets(Mockito.eq(tenantId), Mockito.anyInt())) .thenAnswer( invocation -> { exportedVersionNumber.set(invocation.getArgument(1)); try { + versionAssetPublicationService.freezeOrReadSnapshot( + tenantId, exportedVersionNumber.get()); + ExportedAssetManifest recordedManifest = + versionAssetExportCandidateService.recordExportCandidate( + tenantId, exportedVersionNumber.get(), exportedManifest); VersionTemplateRemapSet approvedRemapSet = new VersionTemplateRemapSet(); approvedRemapSet.setRemapSetId("failed-candidate-approved-remap"); approvedRemapSet.setTenantId(tenantId); @@ -407,7 +559,7 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( templateRemapSetRepository.save(approvedRemapSet); remapSetId.set(approvedRemapSet.getRemapSetId()); exportCompleted.set(true); - return exportedManifest; + return recordedManifest; } catch (Throwable failure) { exportCallbackFailure.set(failure); throw failure; @@ -416,7 +568,7 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( Mockito.doAnswer( invocation -> { finalizationFailureInjected.set(true); - throw new IllegalStateException("forced finalization failure"); + throw new IllegalStateException(longFailureMessage); }) .when(versionAssetArtifactService) .markPublished( @@ -465,7 +617,7 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( .as("asset export uses the candidate's persisted version number") .isEqualTo(candidateVersionNumber.get()); assertThat(attempt.getStatus()).isEqualTo(PublishAttemptStatus.FAILED); - assertThat(attempt.getFailureMessage()).isEqualTo("forced finalization failure"); + assertThat(attempt.getFailureMessage()).isEqualTo(longFailureMessage); Version retainedCandidate = versionRepository.findByTenantIdAndId(tenantId, candidateVersionId.get()).orElseThrow(); assertThat(retainedCandidate.getVersionState()).isEqualTo(VersionLifecycleState.DRAFT); @@ -478,6 +630,14 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( .findByTenantIdAndVersionId(tenantId, candidateVersionId.get()) .orElseThrow(); assertThat(failedArtifact.getArtifactState()).isEqualTo(VersionAssetArtifactState.FAILED); + assertThat(failedArtifact.getStateEpoch()).isEqualTo(3L); + assertThat(failedArtifact.getLastErrorMessage()).isEqualTo(longFailureMessage); + assertThat(failedArtifact.getManifestHash()).isEqualTo(FINALIZATION_MANIFEST_HASH); + assertThat(failedArtifact.getManifestSchemaVersion()).isEqualTo(1); + assertThat(failedArtifact.getArtifactDigestsJson()).isEqualTo("[]"); + assertThat(failedArtifact.getCandidateSnapshotVersionId()).isEqualTo(candidateVersionId.get()); + assertThat(failedArtifact.getPublishedObjectProofsJson()) + .contains("manifests/sha256/", FINALIZATION_MANIFEST_HASH); VersionTemplateRemapSet retainedRemapSet = templateRemapSetRepository .findByTenantIdAndRemapSetId(tenantId, remapSetId.get()) @@ -486,6 +646,31 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( assertThat(retainedRemapSet.getApprovedAt()).isNotNull(); assertThat(retainedRemapSet.getSourceVersionId()).isEqualTo(sourceVersionId); assertThat(retainedRemapSet.getTargetVersionId()).isEqualTo(candidateVersionId.get()); + + assertThatThrownBy( + () -> + versionPublishCommandService.publishFullVersion( + tenantId, "failed remap proof", publishRequestId, publishWorkflowId)) + .isInstanceOf(IllegalStateException.class) + .hasMessage(longFailureMessage); + PublishAttempt replayedAttempt = + publishAttemptRepository.findByPublishWorkflowId(publishWorkflowId).orElseThrow(); + assertThat(replayedAttempt).isEqualTo(attempt); + assertThat(replayedAttempt.getStatus()).isEqualTo(PublishAttemptStatus.FAILED); + assertThat(replayedAttempt.getVersionId()).isEqualTo(candidateVersionId.get()); + assertThat(replayedAttempt.getVersionNumber()).isEqualTo(candidateVersionNumber.get()); + assertThat(replayedAttempt.getFailureCode()).isEqualTo(attempt.getFailureCode()); + assertThat(replayedAttempt.getFailureMessage()).isEqualTo(longFailureMessage); + VersionAssetArtifact replayedArtifact = + versionAssetArtifactRepository + .findByTenantIdAndVersionId(tenantId, candidateVersionId.get()) + .orElseThrow(); + assertThat(replayedArtifact).isEqualTo(failedArtifact); + assertThat(replayedArtifact.getArtifactState()).isEqualTo(VersionAssetArtifactState.FAILED); + assertThat(replayedArtifact.getStateEpoch()).isEqualTo(3L); + assertThat(replayedArtifact.getLastErrorMessage()).isEqualTo(longFailureMessage); + Mockito.verify(assetExportService, Mockito.times(1)) + .exportAssets(Mockito.eq(tenantId), Mockito.anyInt()); } private static String firstStackFrame(Throwable failure) { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationMinioPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationMinioPostgresIntegrationTest.java new file mode 100644 index 0000000000..d86435441e --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/VersionAssetPublicationMinioPostgresIntegrationTest.java @@ -0,0 +1,632 @@ +package net.firedevops.firemud.gamedesign.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import net.firedevops.firemud.common.config.PostgresProperties; +import net.firedevops.firemud.gamedesign.config.AssetStoreProperties; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.GameAsset; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; +import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.impl.AssetExportServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.VersionAssetArtifactServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.VersionAssetExportCandidateServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.VersionAssetPublicationServiceImpl; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; +import org.mockito.AdditionalAnswers; +import org.mockito.Mockito; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.S3Configuration; +import software.amazon.awssdk.services.s3.model.CreateBucketRequest; +import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; +import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import tools.jackson.databind.ObjectMapper; + +/** + * Composes the Flyway-backed owner rows and real publication services with the AWS SDK and a + * run-owned MinIO provider. This proves the private PostgreSQL-to-object-store producer boundary; + * it does not prove public delivery, creator authorization, release activation, or launch. + */ +@Testcontainers(disabledWithoutDocker = true) +class VersionAssetPublicationMinioPostgresIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final String TENANT_ID = "minio-postgres-composition-tenant"; + private static final String PUBLIC_BASE_URL = "https://assets.example.invalid/assets"; + private static final String WORKFLOW_ID = "minio-postgres-composition-workflow"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + private S3Client s3Client; + private String bucket; + + @AfterEach + void removeOnlyTheOwnedBucket() { + if (s3Client == null) { + return; + } + try { + if (bucket != null) { + for (var object : + s3Client + .listObjectsV2(ListObjectsV2Request.builder().bucket(bucket).build()) + .contents()) { + s3Client.deleteObject( + DeleteObjectRequest.builder().bucket(bucket).key(object.key()).build()); + } + s3Client.deleteBucket(DeleteBucketRequest.builder().bucket(bucket).build()); + } + } finally { + s3Client.close(); + } + } + + @Test + void + composesPostgresSnapshotAndCandidateWithMinioBeforeWriteAndRetriesAfterLostAcknowledgement() { + String endpoint = System.getenv("MINIO_ASSET_EXPORT_ENDPOINT"); + Assumptions.assumeTrue( + endpoint != null && !endpoint.isBlank(), + "set MINIO_ASSET_EXPORT_ENDPOINT to run the PostgreSQL-to-MinIO composition proof"); + + String accessKey = requiredEnvironment("MINIO_ASSET_EXPORT_ACCESS_KEY"); + String secretKey = requiredEnvironment("MINIO_ASSET_EXPORT_SECRET_KEY"); + s3Client = newS3Client(endpoint, accessKey, secretKey); + String ownedBucket = "firemud-asset-pg-" + UUID.randomUUID().toString().replace("-", ""); + s3Client.createBucket(CreateBucketRequest.builder().bucket(ownedBucket).build()); + bucket = ownedBucket; + + Fixture fixture = fixture(); + Game game = saveGame(fixture); + Version version = saveVersion(fixture, game, 1); + byte[] publishedBytes = bytes("Flyway-backed mapped asset bytes"); + GameAsset asset = + saveAsset( + fixture, game.getTenantId(), "composition-proof-logo.png", "image/png", publishedBytes); + fixture + .publicationService() + .associateDraftAsset(game.getTenantId(), version.getId(), asset.getId(), "logo"); + stageArtifact(fixture, game, version, WORKFLOW_ID); + + String publishedKey = "artifacts/sha256/" + sha256Hex(publishedBytes); + AtomicBoolean losePutAcknowledgement = new AtomicBoolean(true); + AtomicBoolean loseFirstReadback = new AtomicBoolean(true); + AtomicReference candidateBeforePut = new AtomicReference<>(); + AtomicReference artifactXminBeforePut = new AtomicReference<>(); + S3Client interruptedClient = + observingClient( + s3Client, + request -> { + assertThat(request.bucket()).isEqualTo(bucket); + assertPersistedSnapshotAndCandidate( + fixture.schema(), + fixture.dataSource(), + game.getTenantId(), + version.getId(), + asset.getId(), + "composition-proof-logo.png", + publishedBytes, + "image/png", + publishedKey, + candidateBeforePut, + artifactXminBeforePut); + }, + publishedKey, + losePutAcknowledgement, + loseFirstReadback); + + AssetExportServiceImpl interruptedExporter = + newExporter(fixture, interruptedClient, bucket, endpoint); + assertThatThrownBy(() -> interruptedExporter.exportAssets(game.getTenantId(), 1)) + .isInstanceOf(AssetExportOutcomePendingException.class) + .hasMessageContaining("exact object readback is unavailable"); + assertThat(losePutAcknowledgement.get()).isFalse(); + assertThat(loseFirstReadback.get()).isFalse(); + + assertStoredObject(publishedKey, publishedBytes, "image/png"); + assertThat(candidateBeforePut.get()).isNotNull(); + assertThat(artifactXminBeforePut.get()).isNotBlank(); + + Fixture reconstructed = fixtureFromSchema(fixture.schema(), fixture.dataSource()); + ExportedAssetManifest retry = + newExporter(reconstructed, s3Client, bucket, endpoint).exportAssets(game.getTenantId(), 1); + assertThat(retry).isEqualTo(candidateBeforePut.get()); + assertStoredObject(publishedKey, publishedBytes, "image/png"); + String manifestKey = "manifests/sha256/" + retry.manifestHash().substring("sha256:".length()); + byte[] storedManifest = readObject(manifestKey, "application/json").asByteArray(); + assertThat(sha256Hex(storedManifest)) + .isEqualTo(retry.manifestHash().substring("sha256:".length())); + assertThat(new String(storedManifest, StandardCharsets.UTF_8)) + .contains("composition-proof-logo.png"); + + Fixture afterRetry = fixtureFromSchema(fixture.schema(), fixture.dataSource()); + assertThat(afterRetry.candidateService().readExportCandidate(game.getTenantId(), 1)) + .isEqualTo(candidateBeforePut.get()); + ExportSnapshot retriedSnapshot = + afterRetry.publicationService().readFrozenSnapshot(game.getTenantId(), 1); + assertThat(retriedSnapshot.versionId()).isEqualTo(version.getId()); + assertThat(retriedSnapshot.items()).hasSize(1); + assertThat(retriedSnapshot.items().get(0).bytes()).isEqualTo(publishedBytes); + assertThat(retriedSnapshot.items().get(0).contentDigest()) + .isEqualTo("sha256:" + sha256Hex(publishedBytes)); + assertThat(artifactXmin(afterRetry.dsl(), game.getTenantId(), version.getId())) + .isEqualTo(artifactXminBeforePut.get()); + VersionAssetArtifact retainedCandidate = + afterRetry + .artifactRepository() + .findByTenantIdAndVersionId(game.getTenantId(), version.getId()) + .orElseThrow(); + assertThat(retainedCandidate.getStateEpoch()).isEqualTo(2L); + assertThat(retainedCandidate.getManifestHash()).isEqualTo(retry.manifestHash()); + assertThat( + afterRetry + .versionRepository() + .findByTenantIdAndVersionNumber(game.getTenantId(), 1) + .orElseThrow() + .getVersionState() + .name()) + .isEqualTo("DRAFT"); + + byte[] conflictingBytes = bytes("pre-existing conflicting object"); + byte[] requestedConflictBytes = bytes("requested immutable conflict bytes"); + String conflictKey = "artifacts/sha256/" + sha256Hex(requestedConflictBytes); + s3Client.putObject( + PutObjectRequest.builder() + .bucket(bucket) + .key(conflictKey) + .contentType("application/octet-stream") + .build(), + RequestBody.fromBytes(conflictingBytes)); + + Version conflictVersion = saveVersion(fixture, game, 2); + GameAsset conflictAsset = + saveAsset( + fixture, + game.getTenantId(), + "immutable-conflict.png", + "image/png", + requestedConflictBytes); + fixture + .publicationService() + .associateDraftAsset( + game.getTenantId(), conflictVersion.getId(), conflictAsset.getId(), "logo"); + stageArtifact(fixture, game, conflictVersion, WORKFLOW_ID + "-conflict"); + + Fixture conflictReadback = fixtureFromSchema(fixture.schema(), fixture.dataSource()); + S3Client conflictObservingClient = + observingClient( + s3Client, + request -> { + assertThat(request.bucket()).isEqualTo(bucket); + assertPersistedSnapshotAndCandidate( + fixture.schema(), + fixture.dataSource(), + game.getTenantId(), + conflictVersion.getId(), + conflictAsset.getId(), + "immutable-conflict.png", + requestedConflictBytes, + "image/png", + conflictKey, + new AtomicReference<>(), + new AtomicReference<>()); + }, + null, + new AtomicBoolean(false), + new AtomicBoolean(false)); + assertThatThrownBy( + () -> + newExporter(conflictReadback, conflictObservingClient, bucket, endpoint) + .exportAssets(game.getTenantId(), 2)) + .isInstanceOf(IllegalStateException.class) + .hasMessageStartingWith("IMMUTABLE_OBJECT_CONFLICT"); + assertStoredObject(conflictKey, conflictingBytes, "application/octet-stream"); + } + + private void assertPersistedSnapshotAndCandidate( + String schema, + DriverManagerDataSource dataSource, + String tenantId, + long versionId, + long assetId, + String expectedUsageKey, + byte[] sourceBytes, + String contentType, + String expectedArtifactKey, + AtomicReference capturedCandidate, + AtomicReference capturedArtifactXmin) { + Fixture independentlyReconstructed = fixtureFromSchema(schema, dataSource); + Version version = + independentlyReconstructed + .versionRepository() + .findByTenantIdAndId(tenantId, versionId) + .orElseThrow(); + ExportSnapshot snapshot = + independentlyReconstructed + .publicationService() + .readFrozenSnapshot(tenantId, version.getVersionNumber()); + assertThat(snapshot.versionId()).isEqualTo(versionId); + assertThat(snapshot.canonicalTenantId()).isEqualTo(version.getCanonicalTenantId()); + assertThat(snapshot.canonicalVersionId()).isEqualTo(version.getCanonicalVersionId()); + assertThat(snapshot.items()).hasSize(1); + assertThat(snapshot.items().get(0).assetId()).isEqualTo(assetId); + assertThat(snapshot.items().get(0).bytes()).isEqualTo(sourceBytes); + assertThat(snapshot.items().get(0).contentType()).isEqualTo(contentType); + assertThat(snapshot.items().get(0).contentDigest()) + .isEqualTo("sha256:" + sha256Hex(sourceBytes)); + + var header = + independentlyReconstructed + .dsl() + .fetchOne( + "SELECT item_count, captured_version_state_epoch FROM version_asset_export_snapshot " + + "WHERE tenant_id = ? AND version_id = ?", + tenantId, + versionId); + assertThat(header).isNotNull(); + assertThat(header.get("item_count", Integer.class)).isEqualTo(1); + assertThat(header.get("captured_version_state_epoch", Long.class)).isEqualTo(1L); + var persistedItem = + independentlyReconstructed + .dsl() + .fetchOne( + "SELECT i.usage_key, i.asset_id, i.content_type, i.content_hash, i.byte_size, " + + "va.usage_key AS mapping_usage_key, va.usage_type, ga.file_name, ga.data, " + + "g.id AS source_game_id, " + + "g.canonical_tenant_id, v.identity_source_game_row_id, " + + "v.identity_source_game_tenant_key, v.identity_source_provenance_kind " + + "FROM version_asset_export_item i " + + "JOIN version_asset va ON va.tenant_id = i.tenant_id " + + "AND va.version_id = i.version_id AND va.asset_id = i.asset_id " + + "AND va.usage_key = i.usage_key " + + "JOIN game_assets ga ON ga.tenant_id = i.tenant_id AND ga.id = i.asset_id " + + "JOIN version v ON v.tenant_id = i.tenant_id AND v.id = i.version_id " + + "JOIN game g ON g.tenant_id = v.identity_source_game_tenant_key " + + "AND g.id = v.identity_source_game_row_id " + + "WHERE i.tenant_id = ? AND i.version_id = ?", + tenantId, + versionId); + assertThat(persistedItem).isNotNull(); + assertThat(persistedItem.get("usage_key", String.class)).isEqualTo(expectedUsageKey); + assertThat(persistedItem.get("mapping_usage_key", String.class)).isEqualTo(expectedUsageKey); + assertThat(persistedItem.get("asset_id", Long.class)).isEqualTo(assetId); + assertThat(persistedItem.get("content_type", String.class)).isEqualTo(contentType); + assertThat(persistedItem.get("content_hash", String.class)) + .isEqualTo("sha256:" + sha256Hex(sourceBytes)); + assertThat(persistedItem.get("byte_size", Long.class)).isEqualTo((long) sourceBytes.length); + assertThat(persistedItem.get("usage_type", String.class)).isEqualTo("logo"); + assertThat(persistedItem.get("file_name", String.class)).isEqualTo(expectedUsageKey); + assertThat(persistedItem.get("data", byte[].class)).isEqualTo(sourceBytes); + assertThat(persistedItem.get("source_game_id", Long.class)) + .isEqualTo(persistedItem.get("identity_source_game_row_id", Long.class)); + assertThat(persistedItem.get("identity_source_game_tenant_key", String.class)) + .isEqualTo(tenantId); + assertThat(persistedItem.get("identity_source_provenance_kind", String.class)) + .isEqualTo("NEW_GAME_ROW"); + assertThat(persistedItem.get("canonical_tenant_id", UUID.class)) + .isEqualTo(snapshot.canonicalTenantId()); + + ExportedAssetManifest candidate = + independentlyReconstructed + .candidateService() + .readExportCandidate(tenantId, version.getVersionNumber()); + assertThat(candidate.manifestSchemaVersion()).isEqualTo(1); + assertThat(candidate.artifactDigests()).hasSize(1); + PublishedArtifactDigest digest = candidate.artifactDigests().get(0); + assertThat(digest.usageKey()).isEqualTo(snapshot.items().get(0).usageKey()); + assertThat(digest.immutableObjectKey()).isEqualTo(expectedArtifactKey); + assertThat(digest.contentDigest()).isEqualTo("sha256:" + sha256Hex(sourceBytes)); + assertThat(digest.contentType()).isEqualTo(contentType); + assertThat(candidate.manifestHash()).matches("sha256:[0-9a-f]{64}"); + + VersionAssetArtifact storedArtifact = + independentlyReconstructed + .artifactRepository() + .findByTenantIdAndVersionId(tenantId, versionId) + .orElseThrow(); + assertThat(storedArtifact.getArtifactState().name()).isEqualTo("STAGED"); + assertThat(storedArtifact.getStateEpoch()).isEqualTo(2L); + assertThat(storedArtifact.getManifestHash()).isEqualTo(candidate.manifestHash()); + assertThat(storedArtifact.getManifestSchemaVersion()).isEqualTo(1); + assertThat(storedArtifact.getArtifactDigestsJson()) + .contains(expectedArtifactKey, digest.contentDigest()); + assertThat(storedArtifact.getPublishedObjectProofsJson()) + .contains(expectedArtifactKey, "manifests/sha256/", candidate.manifestHash()); + assertThat(storedArtifact.getCandidateSnapshotVersionId()).isEqualTo(versionId); + assertThat(storedArtifact.getExportedManifestAssetKeysJson()).contains(expectedUsageKey); + var mappingCount = + independentlyReconstructed + .dsl() + .fetchOne( + "SELECT count(*) AS mapping_count FROM version_asset " + + "WHERE tenant_id = ? AND version_id = ?", + tenantId, + versionId); + assertThat(mappingCount.get("mapping_count", Long.class)).isEqualTo(1L); + + String rowXmin = artifactXmin(independentlyReconstructed.dsl(), tenantId, versionId); + if (capturedCandidate != null) { + capturedCandidate.compareAndSet(null, candidate); + } + if (capturedArtifactXmin != null) { + capturedArtifactXmin.compareAndSet(null, rowXmin); + } + } + + private Fixture fixture() { + String schema = "gd_minio_pg_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema); + return fixtureFromSchema(schema, dataSource); + } + + private Fixture fixtureFromSchema(String schema, DriverManagerDataSource dataSource) { + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + PlatformTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + GameRepository gameRepository = new GameRepository(dsl); + GameAssetRepository gameAssetRepository = new GameAssetRepository(dsl); + PostgresProperties postgresProperties = new PostgresProperties(); + postgresProperties.setSchema(schema); + VersionRepository versionRepository = new VersionRepository(dsl, postgresProperties); + VersionAssetPublicationRepository publicationRepository = + new VersionAssetPublicationRepository(dsl); + VersionAssetPublicationServiceImpl publicationService = + new VersionAssetPublicationServiceImpl(transactionManager, publicationRepository); + VersionAssetArtifactRepository artifactRepository = new VersionAssetArtifactRepository(dsl); + VersionAssetExportCandidateServiceImpl candidateService = + new VersionAssetExportCandidateServiceImpl( + versionRepository, + artifactRepository, + publicationService, + transactionManager, + new ObjectMapper()); + return new Fixture( + schema, + dataSource, + dsl, + transactionManager, + transactionTemplate, + gameRepository, + gameAssetRepository, + versionRepository, + publicationService, + artifactRepository, + candidateService); + } + + private DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + return dataSource; + } + + private void migrate(DriverManagerDataSource dataSource, String schema) { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + } + + private Game saveGame(Fixture fixture) { + Game game = new Game(); + game.setTenantId(TENANT_ID); + game.setName("PostgreSQL MinIO composition owner"); + game.setDescription("Canonical Game Design source row"); + return fixture.transactionTemplate().execute(status -> fixture.gameRepository().save(game)); + } + + private Version saveVersion(Fixture fixture, Game game, int versionNumber) { + Version version = new Version(); + version.setTenantId(game.getTenantId()); + version.setVersionNumber(versionNumber); + version.setNotes("PostgreSQL MinIO composition fixture"); + return fixture + .transactionTemplate() + .execute(status -> fixture.versionRepository().save(version)); + } + + private GameAsset saveAsset( + Fixture fixture, String tenantId, String fileName, String contentType, byte[] data) { + GameAsset asset = new GameAsset(); + asset.setTenantId(tenantId); + asset.setFileName(fileName); + asset.setContentType(contentType); + asset.setData(data); + return fixture + .transactionTemplate() + .execute(status -> fixture.gameAssetRepository().save(asset)); + } + + private void stageArtifact(Fixture fixture, Game game, Version version, String workflowId) { + VersionAssetArtifactServiceImpl stageService = + new VersionAssetArtifactServiceImpl( + fixture.artifactRepository(), + null, + fixture.versionRepository(), + null, + null, + null, + null, + null, + new ObjectMapper()); + fixture + .transactionTemplate() + .execute( + status -> + stageService.stageExport( + game.getTenantId(), version.getId(), version.getVersionNumber(), workflowId)); + } + + private AssetExportServiceImpl newExporter( + Fixture fixture, S3Client client, String bucket, String endpoint) { + AssetStoreProperties properties = new AssetStoreProperties(); + properties.setEndpoint(endpoint); + properties.setPublicBaseUrl(PUBLIC_BASE_URL); + properties.setBucket(bucket); + properties.setRegion("us-east-1"); + return new AssetExportServiceImpl( + fixture.publicationService(), fixture.candidateService(), client, properties); + } + + private S3Client newS3Client(String endpoint, String accessKey, String secretKey) { + return S3Client.builder() + .endpointOverride(URI.create(endpoint)) + .credentialsProvider( + StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey))) + .region(Region.US_EAST_1) + .serviceConfiguration(S3Configuration.builder().pathStyleAccessEnabled(true).build()) + .build(); + } + + private S3Client observingClient( + S3Client delegate, + Consumer beforePut, + String loseAcknowledgementKey, + AtomicBoolean losePutAcknowledgement, + AtomicBoolean loseFirstReadback) { + S3Client observer = Mockito.mock(S3Client.class, AdditionalAnswers.delegatesTo(delegate)); + doAnswer( + invocation -> { + PutObjectRequest request = invocation.getArgument(0, PutObjectRequest.class); + beforePut.accept(request); + var response = + delegate.putObject(request, invocation.getArgument(1, RequestBody.class)); + if (request.key().equals(loseAcknowledgementKey) + && losePutAcknowledgement.compareAndSet(true, false)) { + throw SdkClientException.builder() + .message("simulated lost SDK acknowledgement after successful MinIO PUT") + .build(); + } + return response; + }) + .when(observer) + .putObject(any(PutObjectRequest.class), any(RequestBody.class)); + doAnswer( + invocation -> { + GetObjectRequest request = invocation.getArgument(0, GetObjectRequest.class); + if (request.key().equals(loseAcknowledgementKey) + && loseFirstReadback.compareAndSet(true, false)) { + throw SdkClientException.builder() + .message("simulated unavailable readback after lost MinIO PUT acknowledgement") + .build(); + } + return delegate.getObjectAsBytes(request); + }) + .when(observer) + .getObjectAsBytes(any(GetObjectRequest.class)); + return observer; + } + + private ResponseBytes readObject(String key, String contentType) { + ResponseBytes response = + s3Client.getObjectAsBytes(GetObjectRequest.builder().bucket(bucket).key(key).build()); + assertThat(response.response().contentType()).isEqualTo(contentType); + assertThat(response.response().contentLength()).isEqualTo((long) response.asByteArray().length); + return response; + } + + private void assertStoredObject(String key, byte[] expectedBytes, String expectedContentType) { + ResponseBytes response = readObject(key, expectedContentType); + assertThat(response.asByteArray()).isEqualTo(expectedBytes); + assertThat(sha256Hex(response.asByteArray())).isEqualTo(sha256Hex(expectedBytes)); + } + + private String artifactXmin(DSLContext dsl, String tenantId, long versionId) { + var artifactRow = + dsl.fetchOne( + "SELECT xmin::text AS xmin FROM version_asset_artifact " + + "WHERE tenant_id = ? AND version_id = ?", + tenantId, + versionId); + if (artifactRow == null) { + throw new IllegalStateException("Expected persisted Version asset artifact xmin row"); + } + return artifactRow.get("xmin", String.class); + } + + private static String requiredEnvironment(String key) { + String value = System.getenv(key); + if (value == null || value.isBlank()) { + throw new IllegalStateException(key + " must be set when MINIO_ASSET_EXPORT_ENDPOINT is set"); + } + return value; + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static String sha256Hex(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 unavailable", exception); + } + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + PlatformTransactionManager transactionManager, + TransactionTemplate transactionTemplate, + GameRepository gameRepository, + GameAssetRepository gameAssetRepository, + VersionRepository versionRepository, + VersionAssetPublicationServiceImpl publicationService, + VersionAssetArtifactRepository artifactRepository, + VersionAssetExportCandidateServiceImpl candidateService) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceIntegrationTest.java new file mode 100644 index 0000000000..ed3d16b785 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceIntegrationTest.java @@ -0,0 +1,672 @@ +package integration.net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.PostgresProperties; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.GameAsset; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; +import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.service.impl.VersionAssetArtifactServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.VersionAssetExportCandidateServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.VersionAssetPublicationServiceImpl; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +@Testcontainers(disabledWithoutDocker = true) +class VersionAssetExportCandidateServiceIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final MigrationVersion V37 = MigrationVersion.fromVersion("37"); + private static final MigrationVersion V38 = MigrationVersion.fromVersion("38"); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void durableCandidateIsSnapshotBoundRetryableAndIncludesManifestAndBinaryProofs() { + Fixture fixture = fixture(null); + Game game = saveGame(fixture, "candidate-owner"); + Version version = saveVersion(fixture, game, 1); + byte[] selectedBytes = bytes("retained candidate source bytes"); + GameAsset selected = + saveAsset(fixture, game.getTenantId(), "logo雪.png", "image/png", selectedBytes); + fixture + .publicationService() + .associateDraftAsset(game.getTenantId(), version.getId(), selected.getId(), "logo"); + ExportSnapshot snapshot = + fixture.publicationService().freezeOrReadSnapshot(game.getTenantId(), 1); + stageArtifact(fixture, game.getTenantId(), version.getId(), 1, "stable-publish-workflow"); + ExportedAssetManifest candidate = candidate(snapshot, "manifest bytes bound to version one"); + + ExportedAssetManifest committed = + fixture.candidateService().recordExportCandidate(game.getTenantId(), 1, candidate); + VersionAssetArtifact afterWrite = + fixture + .artifactRepository() + .findByTenantIdAndVersionId(game.getTenantId(), version.getId()) + .orElseThrow(); + String firstXmin = artifactXmin(fixture.dsl(), game.getTenantId(), version.getId()); + assertThat(committed).isEqualTo(candidate); + assertThat(afterWrite.getArtifactState()).isEqualTo(VersionAssetArtifactState.STAGED); + assertThat(afterWrite.getStateEpoch()).isEqualTo(2L); + assertThat(afterWrite.getLastWorkflowId()).isEqualTo("stable-publish-workflow"); + assertThat(afterWrite.getManifestHash()).isEqualTo(candidate.manifestHash()); + assertThat(afterWrite.getManifestSchemaVersion()).isEqualTo(1); + assertThat(afterWrite.getCandidateSnapshotVersionId()).isEqualTo(version.getId()); + assertThat(afterWrite.getExportedManifestAssetKeysJson()).isEqualTo("[\"logo雪.png\"]"); + assertThat(afterWrite.getArtifactDigestsJson()).contains("logo雪.png", "BINARY", "image/png"); + assertThat(afterWrite.getPublishedObjectProofsJson()) + .contains("artifacts/sha256/", "manifests/sha256/", candidate.manifestHash()); + VersionAssetExportCandidateServiceImpl restartedService = + candidateService( + fixture.versionRepository(), + fixture.artifactRepository(), + fixture.publicationService(), + fixture.transactionManager()); + assertThat(restartedService.readExportCandidate(game.getTenantId(), 1)).isEqualTo(candidate); + + ExportedAssetManifest conflictingManifest = + new ExportedAssetManifest( + "sha256:" + "a".repeat(64), + candidate.manifestSchemaVersion(), + candidate.requiredManifestAssetKeys(), + candidate.artifactDigests()); + assertThatThrownBy( + () -> + fixture + .candidateService() + .recordExportCandidate(game.getTenantId(), 1, conflictingManifest)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_EXPORT_CANDIDATE_CONFLICT"); + assertThat(artifactXmin(fixture.dsl(), game.getTenantId(), version.getId())) + .isEqualTo(firstXmin); + + saveAsset( + fixture, + game.getTenantId(), + "unrelated-after-freeze.css", + "text/css", + bytes("must not enter the candidate")); + assertThat(restartedService.recordExportCandidate(game.getTenantId(), 1, candidate)) + .isEqualTo(candidate); + assertThat(artifactXmin(fixture.dsl(), game.getTenantId(), version.getId())) + .isEqualTo(firstXmin); + + fixture + .dsl() + .execute( + "UPDATE version SET version_state = 'PUBLISHED', version_state_epoch = 2 " + + "WHERE tenant_id = ? AND id = ?", + game.getTenantId(), + version.getId()); + fixture + .dsl() + .execute( + "UPDATE version_asset_artifact SET artifact_state = 'PUBLISHED', state_epoch = 3 " + + "WHERE tenant_id = ? AND version_id = ?", + game.getTenantId(), + version.getId()); + String publishedXmin = artifactXmin(fixture.dsl(), game.getTenantId(), version.getId()); + assertThat(restartedService.recordExportCandidate(game.getTenantId(), 1, candidate)) + .isEqualTo(candidate); + assertThat(restartedService.readExportCandidate(game.getTenantId(), 1)).isEqualTo(candidate); + assertThat(artifactXmin(fixture.dsl(), game.getTenantId(), version.getId())) + .isEqualTo(publishedXmin); + } + + @Test + void emptyFrozenSnapshotIsExplicitAndMissingSnapshotOrArtifactIsNeverInferred() { + Fixture fixture = fixture(null); + Game game = saveGame(fixture, "candidate-empty-owner"); + Version emptyVersion = saveVersion(fixture, game, 1); + ExportSnapshot emptySnapshot = + fixture.publicationService().freezeOrReadSnapshot(game.getTenantId(), 1); + stageArtifact(fixture, game.getTenantId(), emptyVersion.getId(), 1, "empty-workflow"); + ExportedAssetManifest emptyCandidate = candidate(emptySnapshot, "empty selection manifest"); + assertThat(emptyCandidate.artifactDigests()).isEmpty(); + assertThat( + fixture.candidateService().recordExportCandidate(game.getTenantId(), 1, emptyCandidate)) + .isEqualTo(emptyCandidate); + VersionAssetArtifact emptyArtifact = + fixture + .artifactRepository() + .findByTenantIdAndVersionId(game.getTenantId(), emptyVersion.getId()) + .orElseThrow(); + assertThat(emptyArtifact.getPublishedObjectProofsJson()) + .contains("manifests/sha256/") + .doesNotContain("artifacts/sha256/"); + + Version noSnapshotVersion = saveVersion(fixture, game, 2); + stageArtifact( + fixture, game.getTenantId(), noSnapshotVersion.getId(), 2, "no-snapshot-workflow"); + assertThatThrownBy(() -> fixture.candidateService().readExportCandidate(game.getTenantId(), 2)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No durable frozen Version asset snapshot"); + + Version noArtifactVersion = saveVersion(fixture, game, 3); + fixture.publicationService().freezeOrReadSnapshot(game.getTenantId(), 3); + assertThatThrownBy( + () -> + fixture + .candidateService() + .recordExportCandidate( + game.getTenantId(), 3, candidateForEmptyVersion(noArtifactVersion))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_EXPORT_CANDIDATE_NOT_FOUND"); + assertThat( + fixture + .dsl() + .fetchOne( + "SELECT 1 FROM version_asset_artifact WHERE tenant_id = ? AND version_id = ?", + game.getTenantId(), + noArtifactVersion.getId())) + .isNull(); + } + + @Test + void retainedNullCandidateFieldsRemainAbsentAcrossV38WithoutReadInference() { + Fixture fixture = fixture(V37); + Game game = saveGame(fixture, "candidate-retained-owner"); + Version version = saveVersion(fixture, game, 1); + GameAsset asset = + saveAsset( + fixture, + game.getTenantId(), + "retained.bin", + "application/octet-stream", + bytes("retained")); + fixture + .publicationService() + .associateDraftAsset(game.getTenantId(), version.getId(), asset.getId(), "binary"); + fixture.publicationService().freezeOrReadSnapshot(game.getTenantId(), 1); + insertLegacyStagedArtifact(fixture, game.getTenantId(), version.getId(), 1); + String oldXmin = artifactXmin(fixture.dsl(), game.getTenantId(), version.getId()); + + migrate(fixture.dataSource(), fixture.schema(), V38); + VersionAssetExportCandidateServiceImpl candidateService = + candidateService( + fixture.versionRepository(), + fixture.artifactRepository(), + fixture.publicationService(), + fixture.transactionManager()); + + assertThatThrownBy(() -> candidateService.readExportCandidate(game.getTenantId(), 1)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_EXPORT_CANDIDATE_NOT_FOUND"); + VersionAssetArtifact artifact = + fixture + .artifactRepository() + .findByTenantIdAndVersionId(game.getTenantId(), version.getId()) + .orElseThrow(); + assertThat(artifact.getManifestSchemaVersion()).isNull(); + assertThat(artifact.getArtifactDigestsJson()).isNull(); + assertThat(artifact.getPublishedObjectProofsJson()).isNull(); + assertThat(artifact.getCandidateSnapshotVersionId()).isNull(); + assertThat(artifactXmin(fixture.dsl(), game.getTenantId(), version.getId())).isEqualTo(oldXmin); + } + + @Test + void failedDatabaseCandidateWriteRollsBackAllEvidenceAndEpoch() { + Fixture fixture = candidateFixture("candidate-rollback-owner"); + String functionName = "fail_candidate_update"; + String triggerName = "trg_fail_candidate_update"; + fixture + .dsl() + .execute( + "CREATE FUNCTION " + + functionName + + "() RETURNS TRIGGER AS $$ BEGIN " + + "RAISE EXCEPTION 'test candidate persistence failure'; END; $$ LANGUAGE plpgsql"); + fixture + .dsl() + .execute( + "CREATE TRIGGER " + + triggerName + + " BEFORE UPDATE ON version_asset_artifact " + + "FOR EACH ROW EXECUTE FUNCTION " + + functionName + + "()"); + try { + assertThatThrownBy( + () -> + fixture + .candidateService() + .recordExportCandidate(fixture.tenantId(), 1, fixture.candidate())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("test candidate persistence failure"); + VersionAssetArtifact afterFailure = + fixture + .artifactRepository() + .findByTenantIdAndVersionId(fixture.tenantId(), fixture.versionId()) + .orElseThrow(); + assertThat(afterFailure.getStateEpoch()).isEqualTo(1L); + assertThat(afterFailure.getManifestHash()).isNull(); + assertThat(afterFailure.getManifestSchemaVersion()).isNull(); + assertThat(afterFailure.getArtifactDigestsJson()).isNull(); + assertThat(afterFailure.getPublishedObjectProofsJson()).isNull(); + assertThat(afterFailure.getCandidateSnapshotVersionId()).isNull(); + } finally { + fixture.dsl().execute("DROP TRIGGER IF EXISTS " + triggerName + " ON version_asset_artifact"); + fixture.dsl().execute("DROP FUNCTION IF EXISTS " + functionName + "()"); + } + } + + @Test + void concurrentExactCandidateRecordsCommitOneEpochAndCallerRollbackCannotUndoIt() + throws Exception { + Fixture fixture = candidateFixture("candidate-race-owner"); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> { + await(start); + return fixture + .candidateService() + .recordExportCandidate(fixture.tenantId(), 1, fixture.candidate()); + }); + Future second = + executor.submit( + () -> { + await(start); + return fixture + .candidateService() + .recordExportCandidate(fixture.tenantId(), 1, fixture.candidate()); + }); + start.countDown(); + assertThat(first.get(20, TimeUnit.SECONDS)).isEqualTo(fixture.candidate()); + assertThat(second.get(20, TimeUnit.SECONDS)).isEqualTo(fixture.candidate()); + } finally { + executor.shutdownNow(); + assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + assertThat( + fixture + .artifactRepository() + .findByTenantIdAndVersionId(fixture.tenantId(), fixture.versionId()) + .orElseThrow() + .getStateEpoch()) + .isEqualTo(2L); + + fixture + .transactionTemplate() + .execute( + status -> { + assertThat( + fixture + .candidateService() + .recordExportCandidate(fixture.tenantId(), 1, fixture.candidate())) + .isEqualTo(fixture.candidate()); + status.setRollbackOnly(); + return null; + }); + assertThat(fixture.candidateService().readExportCandidate(fixture.tenantId(), 1)) + .isEqualTo(fixture.candidate()); + } + + @Test + void databaseFreezesAllCandidateProofFieldsAndEpochOverflowWritesNothing() { + Fixture fixture = candidateFixture("candidate-immutable-owner"); + fixture.candidateService().recordExportCandidate(fixture.tenantId(), 1, fixture.candidate()); + String proofXmin = artifactXmin(fixture.dsl(), fixture.tenantId(), fixture.versionId()); + + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE version_asset_artifact SET manifest_hash = ?, " + + "manifest_schema_version = 2, artifact_digests_json = '[]', " + + "published_object_proofs_json = '[]', candidate_snapshot_version_id = NULL, " + + "exported_manifest_asset_keys_json = '[]' " + + "WHERE tenant_id = ? AND version_id = ?", + "sha256:" + "f".repeat(64), + fixture.tenantId(), + fixture.versionId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("ASSET_EXPORT_CANDIDATE_IMMUTABLE"); + assertThat(artifactXmin(fixture.dsl(), fixture.tenantId(), fixture.versionId())) + .isEqualTo(proofXmin); + assertThat(fixture.candidateService().readExportCandidate(fixture.tenantId(), 1)) + .isEqualTo(fixture.candidate()); + + Fixture overflow = candidateFixture("candidate-overflow-owner"); + overflow + .dsl() + .execute( + "UPDATE version_asset_artifact SET state_epoch = ? WHERE tenant_id = ? AND version_id = ?", + Long.MAX_VALUE, + overflow.tenantId(), + overflow.versionId()); + assertThatThrownBy( + () -> + overflow + .candidateService() + .recordExportCandidate(overflow.tenantId(), 1, overflow.candidate())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_EXPORT_CANDIDATE_CONFLICT"); + VersionAssetArtifact unchanged = + overflow + .artifactRepository() + .findByTenantIdAndVersionId(overflow.tenantId(), overflow.versionId()) + .orElseThrow(); + assertThat(unchanged.getStateEpoch()).isEqualTo(Long.MAX_VALUE); + assertThat(unchanged.getManifestSchemaVersion()).isNull(); + assertThat(unchanged.getPublishedObjectProofsJson()).isNull(); + } + + private Fixture candidateFixture(String tenantId) { + Fixture fixture = fixture(null); + Game game = saveGame(fixture, tenantId); + Version version = saveVersion(fixture, game, 1); + byte[] bytes = bytes("integration exact asset bytes"); + GameAsset asset = saveAsset(fixture, tenantId, "candidate.png", "image/png", bytes); + fixture + .publicationService() + .associateDraftAsset(tenantId, version.getId(), asset.getId(), "logo"); + ExportSnapshot snapshot = fixture.publicationService().freezeOrReadSnapshot(tenantId, 1); + stageArtifact(fixture, tenantId, version.getId(), 1, "publish-workflow-candidate"); + return fixture.withCandidate( + tenantId, version.getId(), candidate(snapshot, "integration manifest bytes")); + } + + private Fixture fixture(MigrationVersion target) { + String schema = "gd_vac_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, target); + return fixtureFromSchema(schema, dataSource); + } + + private Fixture fixtureFromSchema(String schema, DriverManagerDataSource dataSource) { + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + GameRepository gameRepository = new GameRepository(dsl); + GameAssetRepository gameAssetRepository = new GameAssetRepository(dsl); + PostgresProperties postgresProperties = new PostgresProperties(); + postgresProperties.setSchema(schema); + VersionRepository versionRepository = new VersionRepository(dsl, postgresProperties); + VersionAssetPublicationRepository publicationRepository = + new VersionAssetPublicationRepository(dsl); + VersionAssetPublicationServiceImpl publicationService = + new VersionAssetPublicationServiceImpl(transactionManager, publicationRepository); + VersionAssetArtifactRepository artifactRepository = new VersionAssetArtifactRepository(dsl); + return new Fixture( + schema, + dataSource, + dsl, + transactionManager, + transactionTemplate, + gameRepository, + gameAssetRepository, + versionRepository, + publicationService, + artifactRepository, + candidateService( + versionRepository, artifactRepository, publicationService, transactionManager)); + } + + private VersionAssetExportCandidateServiceImpl candidateService( + VersionRepository versionRepository, + VersionAssetArtifactRepository artifactRepository, + VersionAssetPublicationServiceImpl publicationService, + PlatformTransactionManager transactionManager) { + return new VersionAssetExportCandidateServiceImpl( + versionRepository, + artifactRepository, + publicationService, + transactionManager, + new ObjectMapper()); + } + + 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("classpath:db/migration"); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private Game saveGame(Fixture fixture, String tenantId) { + Game game = new Game(); + game.setTenantId(tenantId); + game.setName("Version asset candidate owner"); + game.setDescription("Candidate integration source row"); + return fixture.transactionTemplate().execute(status -> fixture.gameRepository().save(game)); + } + + private Version saveVersion(Fixture fixture, Game game, int versionNumber) { + Version version = new Version(); + version.setTenantId(game.getTenantId()); + version.setVersionNumber(versionNumber); + version.setNotes("Candidate integration fixture"); + return fixture + .transactionTemplate() + .execute(status -> fixture.versionRepository().save(version)); + } + + private GameAsset saveAsset( + Fixture fixture, String tenantId, String fileName, String contentType, byte[] data) { + GameAsset asset = new GameAsset(); + asset.setTenantId(tenantId); + asset.setFileName(fileName); + asset.setContentType(contentType); + asset.setData(data); + return fixture + .transactionTemplate() + .execute(status -> fixture.gameAssetRepository().save(asset)); + } + + private void stageArtifact( + Fixture fixture, String tenantId, long versionId, int versionNumber, String workflowId) { + VersionAssetArtifactServiceImpl stageService = + new VersionAssetArtifactServiceImpl( + fixture.artifactRepository(), + null, + fixture.versionRepository(), + null, + null, + null, + null, + null, + new ObjectMapper()); + fixture + .transactionTemplate() + .execute( + status -> stageService.stageExport(tenantId, versionId, versionNumber, workflowId)); + } + + private void insertLegacyStagedArtifact( + Fixture fixture, String tenantId, long versionId, int versionNumber) { + fixture + .dsl() + .execute( + "INSERT INTO version_asset_artifact " + + "(tenant_id, version_id, exported_version_number, artifact_state, state_epoch, " + + "manifest_hash, last_workflow_id, last_error_code, last_error_message, " + + "exported_manifest_asset_keys_json, updated_at) " + + "VALUES (?, ?, ?, 'STAGED', 1, NULL, 'retained-workflow', NULL, NULL, '[]', CURRENT_TIMESTAMP)", + tenantId, + versionId, + versionNumber); + } + + private ExportedAssetManifest candidate(ExportSnapshot snapshot, String manifestSource) { + List digests = + snapshot.items().stream() + .map( + source -> + new PublishedArtifactDigest( + source.usageKey(), + "BINARY", + "artifacts/sha256/" + source.contentDigest().substring(7), + source.contentDigest(), + source.contentType(), + 1)) + .toList(); + return new ExportedAssetManifest( + sha256(bytes(manifestSource)), + 1, + digests.stream().map(PublishedArtifactDigest::usageKey).toList(), + digests); + } + + private ExportedAssetManifest candidateForEmptyVersion(Version version) { + return new ExportedAssetManifest( + sha256(bytes("version:" + version.getId() + ":empty-manifest")), 1, List.of(), List.of()); + } + + private String artifactXmin(DSLContext dsl, String tenantId, long versionId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT xmin::text AS xmin FROM version_asset_artifact " + + "WHERE tenant_id = ? AND version_id = ?", + tenantId, + versionId), + "Expected Version asset artifact xmin row") + .get("xmin", String.class); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent candidate test start signal timed out"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Concurrent candidate test was interrupted", exception); + } + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + PlatformTransactionManager transactionManager, + TransactionTemplate transactionTemplate, + GameRepository gameRepository, + GameAssetRepository gameAssetRepository, + VersionRepository versionRepository, + VersionAssetPublicationServiceImpl publicationService, + VersionAssetArtifactRepository artifactRepository, + VersionAssetExportCandidateServiceImpl candidateService, + String tenantId, + long versionId, + ExportedAssetManifest candidate) { + private Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + PlatformTransactionManager transactionManager, + TransactionTemplate transactionTemplate, + GameRepository gameRepository, + GameAssetRepository gameAssetRepository, + VersionRepository versionRepository, + VersionAssetPublicationServiceImpl publicationService, + VersionAssetArtifactRepository artifactRepository, + VersionAssetExportCandidateServiceImpl candidateService) { + this( + schema, + dataSource, + dsl, + transactionManager, + transactionTemplate, + gameRepository, + gameAssetRepository, + versionRepository, + publicationService, + artifactRepository, + candidateService, + null, + 0L, + null); + } + + private Fixture withCandidate( + String tenantId, long versionId, ExportedAssetManifest candidate) { + return new Fixture( + schema, + dataSource, + dsl, + transactionManager, + transactionTemplate, + gameRepository, + gameAssetRepository, + versionRepository, + publicationService, + artifactRepository, + candidateService, + tenantId, + versionId, + candidate); + } + } +} diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java index 98eee02d1d..241da0321c 100644 --- a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java @@ -1,240 +1,786 @@ package net.firedevops.firemud.gamedesign.service; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import java.io.IOException; +import java.io.InputStream; import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; import java.util.List; -import java.util.Optional; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.gamedesign.config.AssetStoreProperties; -import net.firedevops.firemud.gamedesign.entity.GameAsset; -import net.firedevops.firemud.gamedesign.entity.Version; -import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; -import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; -import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.AssetSelection; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; import net.firedevops.firemud.gamedesign.service.impl.AssetExportServiceImpl; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.EnumSource; +import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; +import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; @ExtendWith(MockitoExtension.class) class AssetExportServiceImplTest { - @Mock private GameAssetRepository repository; - @Mock private VersionRepository versionRepository; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("8b0c1a0f-b8c9-4c4b-9021-381f57699001"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("8b0c1a0f-b8c9-4c4b-9021-381f57699002"); + private static final String TENANT_ID = "owner-tenant-key"; + private static final int VERSION_NUMBER = 7; + private static final String PUBLIC_BASE_URL = "https://assets.example.invalid/assets"; + private static final String PRIVATE_ENDPOINT = "http://minio.internal:9000"; + + @Mock private VersionAssetPublicationService publicationService; + @Mock private VersionAssetExportCandidateService candidateService; @Mock private S3Client s3Client; + private final AtomicReference storedCandidate = new AtomicReference<>(); + private final Map objectStore = new HashMap<>(); + private final Set failPutBeforeCommit = new HashSet<>(); + private final Set losePutAcknowledgementAfterCommit = new HashSet<>(); + private final Set failReadback = new HashSet<>(); + private AssetExportServiceImpl service; + private ExportSnapshot snapshot; @BeforeEach void setup() { - service = newService(256); + objectStore.clear(); + failPutBeforeCommit.clear(); + losePutAcknowledgementAfterCommit.clear(); + failReadback.clear(); + storedCandidate.set(null); + snapshot = singleAssetSnapshot(); + lenient() + .when(publicationService.freezeOrReadSnapshot(TENANT_ID, VERSION_NUMBER)) + .thenAnswer(ignored -> snapshot); + lenient() + .when(publicationService.readFrozenSnapshot(TENANT_ID, VERSION_NUMBER)) + .thenAnswer(ignored -> copySnapshot(snapshot)); + lenient() + .when( + candidateService.recordExportCandidate( + any(String.class), anyInt(), any(ExportedAssetManifest.class))) + .thenAnswer( + invocation -> { + ExportedAssetManifest requested = invocation.getArgument(2); + ExportedAssetManifest existing = storedCandidate.get(); + if (existing == null) { + storedCandidate.set(requested); + existing = requested; + } + if (!existing.equals(requested)) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_CONFLICT"); + } + return existing; + }); + lenient() + .when(candidateService.readExportCandidate(any(String.class), anyInt())) + .thenAnswer( + ignored -> { + ExportedAssetManifest existing = storedCandidate.get(); + if (existing == null) { + throw new IllegalStateException("candidate not found"); + } + return existing; + }); + lenient() + .when(s3Client.putObject(any(PutObjectRequest.class), any(RequestBody.class))) + .thenAnswer(this::putObject); + lenient() + .when(s3Client.getObjectAsBytes(any(GetObjectRequest.class))) + .thenAnswer(this::getObject); + service = newService(PUBLIC_BASE_URL); + } + + @Test + void readsAndMatchesDurableSnapshotBeforeConditionalObjectWrites() { + service.exportAssets(TENANT_ID, VERSION_NUMBER); + + InOrder order = inOrder(publicationService, candidateService, s3Client); + order.verify(publicationService).freezeOrReadSnapshot(TENANT_ID, VERSION_NUMBER); + order.verify(publicationService).readFrozenSnapshot(TENANT_ID, VERSION_NUMBER); + order + .verify(candidateService) + .recordExportCandidate( + org.mockito.ArgumentMatchers.eq(TENANT_ID), + org.mockito.ArgumentMatchers.eq(VERSION_NUMBER), + any(ExportedAssetManifest.class)); + order.verify(candidateService).readExportCandidate(TENANT_ID, VERSION_NUMBER); + order + .verify(s3Client) + .putObject( + argThat( + (PutObjectRequest request) -> + "*".equals(request.ifNoneMatch()) + && request.key().startsWith("artifacts/sha256/")), + any(RequestBody.class)); + } + + @Test + void unresolvedCandidateWriteBecomesOutcomePendingBeforeAnyObjectWrite() { + org.mockito.Mockito.doThrow(new IllegalStateException("temporary candidate store failure")) + .when(candidateService) + .recordExportCandidate( + org.mockito.ArgumentMatchers.eq(TENANT_ID), + org.mockito.ArgumentMatchers.eq(VERSION_NUMBER), + any(ExportedAssetManifest.class)); + + AssetExportOutcomePendingException thrown = + assertThrows( + AssetExportOutcomePendingException.class, + () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + org.junit.jupiter.api.Assertions.assertTrue( + thrown.getMessage().startsWith("ASSET_EXPORT_OUTCOME_PENDING:")); + verify(candidateService, never()).readExportCandidate(TENANT_ID, VERSION_NUMBER); + verifyNoInteractions(s3Client); + assertEquals(0, objectStore.size()); } - private AssetExportServiceImpl newService(int frozenSnapshotCacheMaxEntries) { - AssetStoreProperties props = new AssetStoreProperties(); - props.setBucket("bucket"); - props.setEndpoint("http://localhost:9000"); - props.setRegion("ap-southeast-2"); - props.setAccessKey("a"); - props.setSecretKey("s"); - props.setFrozenSnapshotCacheMaxEntries(frozenSnapshotCacheMaxEntries); - return new AssetExportServiceImpl( - repository, s3Client, props, new ObjectMapper(), versionRepository); + @Test + void unresolvedCandidateReadbackBecomesOutcomePendingBeforeAnyObjectWrite() { + org.mockito.Mockito.doThrow(new IllegalStateException("candidate readback unavailable")) + .when(candidateService) + .readExportCandidate(TENANT_ID, VERSION_NUMBER); + + AssetExportOutcomePendingException thrown = + assertThrows( + AssetExportOutcomePendingException.class, + () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + org.junit.jupiter.api.Assertions.assertTrue( + thrown.getMessage().startsWith("ASSET_EXPORT_OUTCOME_PENDING:")); + verifyNoInteractions(s3Client); + assertEquals(0, objectStore.size()); } @Test - void exportUploadsAssetsAndManifest() { - when(versionRepository.findByTenantIdAndVersionNumber("t", 1)) - .thenReturn(Optional.of(version(VersionLifecycleState.DRAFT))); - GameAsset asset = gameAsset("logo.png", "data"); - when(repository.findByTenantId("t")).thenReturn(List.of(asset)); + void conflictingPersistedCandidateIsDeniedBeforeAnyObjectWrite() { + ExportedAssetManifest conflict = conflictingCandidate(); + org.mockito.Mockito.doReturn(conflict) + .when(candidateService) + .readExportCandidate(TENANT_ID, VERSION_NUMBER); - ExportedAssetManifest manifest = service.exportAssets("t", 1); + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + assertEquals("ASSET_EXPORT_CANDIDATE_CONFLICT", thrown.getMessage()); + verifyNoInteractions(s3Client); + assertEquals(0, objectStore.size()); + } + + @Test + void missingDurableSnapshotFailsClosedWithoutReadingCurrentAssetsOrWritingObjects() { + when(publicationService.freezeOrReadSnapshot(TENANT_ID, VERSION_NUMBER)).thenReturn(null); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + assertEquals("VERSION_ASSET_SNAPSHOT_UNAVAILABLE", thrown.getMessage()); + verify(publicationService, never()).readFrozenSnapshot(TENANT_ID, VERSION_NUMBER); + verifyNoInteractions(s3Client); + } + + @Test + void exportsCanonicalActualByteDigestsAndManifestWithoutPrivateStorageLocation() + throws Exception { + ExportedAssetManifest exported = service.exportAssets(TENANT_ID, VERSION_NUMBER); + + assertEquals(exported, storedCandidate.get()); + byte[] assetBytes = "real uploaded bytes".getBytes(StandardCharsets.UTF_8); + String assetHex = sha256Hex(assetBytes); + String assetKey = "artifacts/sha256/" + assetHex; + assertEquals("sha256:" + assetHex, exported.artifactDigests().get(0).contentDigest()); + assertEquals(assetKey, exported.artifactDigests().get(0).immutableObjectKey()); + assertEquals(List.of("branding/logo"), exported.requiredManifestAssetKeys()); + assertEquals(1, exported.manifestSchemaVersion()); + assertEquals( + Set.of( + assetKey, "manifests/sha256/" + exported.manifestHash().substring("sha256:".length())), + objectStore.keySet()); + assertEquals("sha256:" + sha256Hex(manifestBytes(exported)), exported.manifestHash()); + + String manifestJson = new String(manifestBytes(exported), StandardCharsets.UTF_8); + assertEquals( + "{\"schemaVersion\":1,\"assets\":{\"branding/logo\":{\"usageKey\":\"branding/logo\"," + + "\"artifactKind\":\"BINARY\",\"immutableObjectKey\":\"" + + assetKey + + "\",\"contentDigest\":\"sha256:" + + assetHex + + "\",\"contentType\":\"image/png\",\"artifactSchemaVersion\":1," + + "\"producerService\":\"game-design-service\",\"versionId\":\"" + + CANONICAL_VERSION_ID + + "\",\"url\":\"" + + PUBLIC_BASE_URL + + "/" + + assetKey + + "\"}}}", + manifestJson); + JsonNode manifest = new ObjectMapper().readTree(manifestJson); + assertEquals(1, manifest.get("schemaVersion").asInt()); + assertEquals(1, manifest.get("assets").size()); + assertEquals("branding/logo", manifest.get("assets").propertyNames().iterator().next()); + assertEquals(-1, manifestJson.indexOf("minio.internal")); + assertEquals(-1, manifestJson.indexOf("bucket")); verify(s3Client) .putObject( - argThat((PutObjectRequest r) -> r.key().equals("t/1/logo.png")), - any(RequestBody.class)); - verify(s3Client) - .putObject( - argThat((PutObjectRequest r) -> r.key().equals("t/1/manifest.json")), + argThat( + (PutObjectRequest request) -> + request + .key() + .equals( + "manifests/sha256/" + + exported.manifestHash().substring("sha256:".length())) + && "application/json".equals(request.contentType()) + && "*".equals(request.ifNoneMatch())), any(RequestBody.class)); - assertEquals(List.of("logo.png", "manifest.json"), manifest.requiredManifestAssetKeys()); } @Test - void sameVersionRetryReusesFrozenSnapshot() { - Version draft = version(VersionLifecycleState.DRAFT); - Version published = version(VersionLifecycleState.PUBLISHED); - when(versionRepository.findByTenantIdAndVersionNumber("t", 1)) - .thenReturn(Optional.of(draft), Optional.of(draft), Optional.of(published)); - GameAsset original = gameAsset("logo.png", "original"); - GameAsset changed = gameAsset("changed.png", "changed"); - when(repository.findByTenantId("t")).thenReturn(List.of(original), List.of(changed)); + void emptyMappedSnapshotCreatesRealCanonicalEmptyManifest() throws Exception { + snapshot = snapshot(List.of()); + + ExportedAssetManifest exported = service.exportAssets(TENANT_ID, VERSION_NUMBER); + + assertEquals(List.of(), exported.requiredManifestAssetKeys()); + assertEquals(List.of(), exported.artifactDigests()); + assertEquals( + "{\"schemaVersion\":1,\"assets\":{}}", + new String(manifestBytes(exported), StandardCharsets.UTF_8)); + assertEquals( + Set.of("manifests/sha256/" + exported.manifestHash().substring("sha256:".length())), + objectStore.keySet()); + } + + @Test + void serializesAssetsInExactUtf8ByteUsageOrder() { + String bmpKey = "\ue000"; + String supplementaryKey = "\ud800\udc00"; + snapshot = + snapshot( + List.of( + selection(supplementaryKey, 25L, "supplementary", "image/png"), + selection(bmpKey, 24L, "bmp", "image/png"))); + + ExportedAssetManifest exported = service.exportAssets(TENANT_ID, VERSION_NUMBER); + String manifestJson = new String(manifestBytes(exported), StandardCharsets.UTF_8); + + assertEquals(List.of(bmpKey, supplementaryKey), exported.requiredManifestAssetKeys()); + org.junit.jupiter.api.Assertions.assertTrue( + manifestJson.indexOf('"' + bmpKey + '"') + < manifestJson.indexOf('"' + supplementaryKey + '"')); + } - ExportedAssetManifest first = service.exportAssets("t", 1); - ExportedAssetManifest retry = service.exportAssets("t", 1); + @Test + void serviceRestartReusesExactPersistedSnapshotAndImmutableKeys() { + ExportedAssetManifest first = service.exportAssets(TENANT_ID, VERSION_NUMBER); + AssetExportServiceImpl restarted = newService(PUBLIC_BASE_URL); + + ExportedAssetManifest retry = restarted.exportAssets(TENANT_ID, VERSION_NUMBER); assertEquals(first, retry); - verify(versionRepository, times(3)).findByTenantIdAndVersionNumber("t", 1); - verify(repository, times(1)).findByTenantId("t"); + verify(publicationService, org.mockito.Mockito.times(2)) + .freezeOrReadSnapshot(TENANT_ID, VERSION_NUMBER); + verify(publicationService, org.mockito.Mockito.times(2)) + .readFrozenSnapshot(TENANT_ID, VERSION_NUMBER); + assertEquals(2, objectStore.size()); + } + + @Test + void rejectsIndependentlyReadSnapshotMismatchBeforeAnyStoreWrite() { + ExportSnapshot changedBytes = + snapshot(List.of(selection("branding/logo", 24L, "different uploaded bytes", "image/png"))); + when(publicationService.readFrozenSnapshot(TENANT_ID, VERSION_NUMBER)).thenReturn(changedBytes); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + assertEquals("VERSION_ASSET_SNAPSHOT_MISMATCH", thrown.getMessage()); + assertEquals(0, objectStore.size()); + verifyNoInteractions(s3Client); } @Test - void unknownVersionIsRejectedWithoutSelectingTenantAssets() { - when(versionRepository.findByTenantIdAndVersionNumber("t", 99)).thenReturn(Optional.empty()); + void rejectsSnapshotSourceIdentityOrContentTypeSubstitutionBeforeAnyStoreWrite() { + when(publicationService.readFrozenSnapshot(TENANT_ID, VERSION_NUMBER)) + .thenReturn( + snapshot(List.of(selection("branding/logo", 25L, "real uploaded bytes", "image/png")))); + + IllegalStateException changedSourceId = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + assertEquals("VERSION_ASSET_SNAPSHOT_MISMATCH", changedSourceId.getMessage()); + verifyNoInteractions(s3Client); - IllegalArgumentException thrown = - assertThrows(IllegalArgumentException.class, () -> service.exportAssets("t", 99)); + org.mockito.Mockito.clearInvocations(publicationService); + when(publicationService.readFrozenSnapshot(TENANT_ID, VERSION_NUMBER)) + .thenReturn( + snapshot( + List.of(selection("branding/logo", 24L, "real uploaded bytes", "image/jpeg")))); - assertEquals("REPAIR_VERSION_SCOPE_UNAVAILABLE", thrown.getMessage()); - verifyNoInteractions(repository, s3Client); + IllegalStateException changedContentType = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + assertEquals("VERSION_ASSET_SNAPSHOT_MISMATCH", changedContentType.getMessage()); + verifyNoInteractions(s3Client); } @Test - void duplicateUsageKeysAreRejectedBeforeWritingAssets() { - when(versionRepository.findByTenantIdAndVersionNumber("t", 1)) - .thenReturn(Optional.of(version(VersionLifecycleState.DRAFT))); - when(repository.findByTenantId("t")) - .thenReturn(List.of(gameAsset("logo.png", "one"), gameAsset("logo.png", "two"))); + void rejectsOutOfScopeOrIncompleteCanonicalSnapshotBeforeAnyStoreWrite() { + snapshot = + snapshot( + "another-tenant", + VERSION_NUMBER, + 19L, + 1L, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + snapshot.items()); IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 1)); + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); - assertEquals("ASSET_USAGE_KEY_COLLISION", thrown.getMessage()); + assertEquals( + "VERSION_ASSET_SNAPSHOT_INVALID: incomplete or out-of-scope snapshot", thrown.getMessage()); verifyNoInteractions(s3Client); } @Test - void reservedManifestUsageKeyIsRejectedBeforeWritingAssets() { - when(versionRepository.findByTenantIdAndVersionNumber("t", 1)) - .thenReturn(Optional.of(version(VersionLifecycleState.DRAFT))); - when(repository.findByTenantId("t")) - .thenReturn(List.of(gameAsset("manifest.json", "asset data"))); + void rejectsNilCanonicalUuidBeforeAnyStoreWrite() { + snapshot = snapshot(List.of(), NIL_UUID, CANONICAL_VERSION_ID); IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 1)); + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); - assertEquals("ASSET_USAGE_KEY_COLLISION", thrown.getMessage()); + assertEquals( + "VERSION_ASSET_SNAPSHOT_INVALID: incomplete or out-of-scope snapshot", thrown.getMessage()); verifyNoInteractions(s3Client); } - @ParameterizedTest - @EnumSource( - value = VersionLifecycleState.class, - names = {"PUBLISHED", "ACTIVE"}) - void publishedAndActiveRetryFailsWithoutFrozenSnapshot(VersionLifecycleState state) { - Version version = version(state); - when(versionRepository.findByTenantIdAndVersionNumber("t", 1)).thenReturn(Optional.of(version)); + @Test + void rejectsNonpositiveOwnerVersionIdentityBeforeAnyStoreWrite() { + snapshot = + snapshot( + TENANT_ID, + VERSION_NUMBER, + 0L, + 3L, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + List.of()); IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 1)); + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); - assertEquals("REPAIR_VERSION_SCOPE_UNAVAILABLE", thrown.getMessage()); - verify(repository, never()).findByTenantId("t"); + assertEquals( + "VERSION_ASSET_SNAPSHOT_INVALID: incomplete or out-of-scope snapshot", thrown.getMessage()); verifyNoInteractions(s3Client); } @Test - void publishedRetryReusesSnapshotFrozenBeforePublication() { - Version draft = version(VersionLifecycleState.DRAFT); - Version published = version(VersionLifecycleState.PUBLISHED); - when(versionRepository.findByTenantIdAndVersionNumber("t", 1)) - .thenReturn(Optional.of(draft), Optional.of(draft), Optional.of(published)); + void rejectsMalformedUtf8UsageKeyBeforeSortingOrWriting() { + snapshot = snapshot(List.of(selection("\ud800", 24L, "real uploaded bytes", "image/png"))); - GameAsset original = gameAsset("logo.png", "original"); - GameAsset changed = gameAsset("changed.png", "changed"); - when(repository.findByTenantId("t")).thenReturn(List.of(original), List.of(changed)); + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); - ExportedAssetManifest first = service.exportAssets("t", 1); - ExportedAssetManifest retry = service.exportAssets("t", 1); + assertEquals( + "VERSION_ASSET_SNAPSHOT_INVALID: usageKey is not valid UTF-8", thrown.getMessage()); + verifyNoInteractions(s3Client); + } - assertEquals(first, retry); - verify(versionRepository, times(3)).findByTenantIdAndVersionNumber("t", 1); - verify(repository, times(1)).findByTenantId("t"); + @Test + void rejectsDuplicateUsageKeysBeforeAnyStoreWrite() { + snapshot = + snapshot( + List.of( + selection("branding/logo", 24L, "first", "image/png"), + selection("branding/logo", 25L, "second", "image/png"))); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + assertEquals("ASSET_USAGE_KEY_COLLISION", thrown.getMessage()); + verifyNoInteractions(s3Client); } @Test - void fullSnapshotCacheFailsClosedInsteadOfEvictingRetryEvidence() { - service = newService(1); - when(versionRepository.findByTenantIdAndVersionNumber("t", 1)) - .thenReturn(Optional.of(version(7L, 1, VersionLifecycleState.DRAFT))); - when(versionRepository.findByTenantIdAndVersionNumber("t", 2)) - .thenReturn(Optional.of(version(8L, 2, VersionLifecycleState.DRAFT))); - when(repository.findByTenantId("t")) - .thenReturn( - List.of(gameAsset("first.png", "first")), List.of(gameAsset("second.png", "second"))); + void rejectsReservedManifestKeyAndDuplicateSourceIdentityBeforeAnyStoreWrite() { + snapshot = + snapshot(List.of(selection("manifest.json", 24L, "real uploaded bytes", "image/png"))); + + IllegalStateException reservedKey = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + assertEquals("ASSET_USAGE_KEY_COLLISION", reservedKey.getMessage()); + verifyNoInteractions(s3Client); + + org.mockito.Mockito.clearInvocations(publicationService); + snapshot = + snapshot( + List.of( + selection("branding/logo", 24L, "first", "image/png"), + selection("branding/icon", 24L, "second", "image/png"))); - service.exportAssets("t", 1); - org.mockito.Mockito.clearInvocations(s3Client); + IllegalStateException duplicateSource = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + assertEquals( + "VERSION_ASSET_SNAPSHOT_INVALID: duplicate source asset identity", + duplicateSource.getMessage()); + verifyNoInteractions(s3Client); + } + + @Test + void rejectsInvalidSourceIdentityAndDigestBeforeAnyStoreWrite() { + snapshot = + snapshot(List.of(selection("branding/logo", 0L, "real uploaded bytes", "image/png"))); IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 2)); + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); - assertEquals("EXPORT_SNAPSHOT_CAPACITY", thrown.getMessage()); + assertEquals( + "VERSION_ASSET_SNAPSHOT_INVALID: incomplete source asset identity", thrown.getMessage()); verifyNoInteractions(s3Client); } @Test - void publicationRacingSnapshotCreationFailsBeforeObjectStoreWrites() { - Version draft = version(VersionLifecycleState.DRAFT); - Version published = version(VersionLifecycleState.PUBLISHED); - when(versionRepository.findByTenantIdAndVersionNumber("t", 1)) - .thenReturn(Optional.of(draft), Optional.of(published)); - when(repository.findByTenantId("t")).thenReturn(List.of(gameAsset("logo.png", "data"))); + void rejectsSourceByteDigestMismatchBeforeAnyStoreWrite() { + byte[] bytes = "real uploaded bytes".getBytes(StandardCharsets.UTF_8); + snapshot = + snapshot( + List.of( + new AssetSelection( + "branding/logo", 24L, bytes, "image/png", "sha256:" + "f".repeat(64)))); IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 1)); + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); - assertEquals("REPAIR_VERSION_SCOPE_UNAVAILABLE", thrown.getMessage()); + assertEquals("ASSET_SOURCE_BYTES_MISMATCH", thrown.getMessage()); verifyNoInteractions(s3Client); } @Test - void deleteExportedAssetsUsesExactManifestKeyList() { - service.deleteExportedAssets("t", 1, List.of("logo.png", "manifest.json")); + void rejectsInvalidPublicOriginsBeforeAnyExternalWrites() { + for (String invalidBaseUrl : + Arrays.asList( + null, + "http://assets.example.invalid/assets", + "https://user@assets.example.invalid/assets", + "https://assets.example.invalid/assets?x=1", + "https://assets.example.invalid/assets#fragment", + "https://assets.example.invalid/private", + "https://minio.internal:9000/assets")) { + AssetExportServiceImpl invalidService = newService(invalidBaseUrl); + + assertThrows( + IllegalStateException.class, + () -> invalidService.exportAssets(TENANT_ID, VERSION_NUMBER), + String.valueOf(invalidBaseUrl)); + } + verifyNoInteractions(s3Client); + } - verify(s3Client) - .deleteObject(argThat((DeleteObjectRequest r) -> r.key().equals("t/1/logo.png"))); - verify(s3Client) - .deleteObject(argThat((DeleteObjectRequest r) -> r.key().equals("t/1/manifest.json"))); + @Test + void identicalConditionalExistingObjectsMakeRetryIdempotent() { + ExportedAssetManifest first = service.exportAssets(TENANT_ID, VERSION_NUMBER); + ExportedAssetManifest retry = service.exportAssets(TENANT_ID, VERSION_NUMBER); + + assertEquals(first, retry); + assertEquals(2, objectStore.size()); + verify(s3Client, org.mockito.Mockito.times(4)) + .putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void changedPreexistingObjectIsDeniedWithoutOverwritingOrDeletingIt() { + byte[] original = "original immutable bytes".getBytes(StandardCharsets.UTF_8); + String key = + "artifacts/sha256/" + sha256Hex("real uploaded bytes".getBytes(StandardCharsets.UTF_8)); + objectStore.put(key, new StoredObject(original, "image/png")); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + org.junit.jupiter.api.Assertions.assertTrue( + thrown.getMessage().startsWith("IMMUTABLE_OBJECT_CONFLICT")); + assertArrayEquals(original, objectStore.get(key).bytes()); + verify(s3Client, never()).deleteObject(any(DeleteObjectRequest.class)); + assertEquals(1, objectStore.size()); + } + + @Test + void lostPutAcknowledgementRecoversOnlyAfterExactCommittedReadback() { + String key = + "artifacts/sha256/" + sha256Hex("real uploaded bytes".getBytes(StandardCharsets.UTF_8)); + losePutAcknowledgementAfterCommit.add(key); + + ExportedAssetManifest exported = service.exportAssets(TENANT_ID, VERSION_NUMBER); + + assertEquals( + "sha256:" + sha256Hex("real uploaded bytes".getBytes(StandardCharsets.UTF_8)), + exported.artifactDigests().get(0).contentDigest()); + assertEquals(2, objectStore.size()); + } + + @Test + void unavailableReadbackAfterAmbiguousPutProducesOutcomePendingAndRetainsBytes() { + String key = + "artifacts/sha256/" + sha256Hex("real uploaded bytes".getBytes(StandardCharsets.UTF_8)); + failPutBeforeCommit.add(key); + failReadback.add(key); + + AssetExportOutcomePendingException thrown = + assertThrows( + AssetExportOutcomePendingException.class, + () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + org.junit.jupiter.api.Assertions.assertTrue( + thrown.getMessage().startsWith("ASSET_EXPORT_OUTCOME_PENDING:")); + verify(s3Client, never()).deleteObject(any(DeleteObjectRequest.class)); + assertEquals(0, objectStore.size()); + } + + @Test + void unavailableReadbackAfterCommittedPutIsOutcomePendingWithoutCleanup() { + String key = + "artifacts/sha256/" + sha256Hex("real uploaded bytes".getBytes(StandardCharsets.UTF_8)); + failReadback.add(key); + + assertThrows( + AssetExportOutcomePendingException.class, + () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + assertEquals(1, objectStore.size()); + verify(s3Client, never()).deleteObject(any(DeleteObjectRequest.class)); + } + + @Test + void contentTypeMismatchOnReadbackDeniesObjectProof() { + byte[] bytes = "real uploaded bytes".getBytes(StandardCharsets.UTF_8); + String key = "artifacts/sha256/" + sha256Hex(bytes); + objectStore.put(key, new StoredObject(bytes, "application/octet-stream")); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, () -> service.exportAssets(TENANT_ID, VERSION_NUMBER)); + + org.junit.jupiter.api.Assertions.assertTrue( + thrown.getMessage().startsWith("IMMUTABLE_OBJECT_CONFLICT")); + assertEquals(1, objectStore.size()); + verify(s3Client, never()).deleteObject(any(DeleteObjectRequest.class)); + } + + @Test + void deleteFailsClosedWithoutIssuingAnyObjectDeletion() { + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, + () -> + service.deleteExportedAssets(TENANT_ID, VERSION_NUMBER, List.of("branding/logo"))); + + assertEquals( + "CONTENT_ADDRESSED_PURGE_PROOF_REQUIRED: version-scoped deletion cannot select shared immutable objects", + thrown.getMessage()); + verifyNoInteractions(s3Client); + } + + private AssetExportServiceImpl newService(String publicBaseUrl) { + AssetStoreProperties properties = new AssetStoreProperties(); + properties.setBucket("private-bucket"); + properties.setEndpoint(PRIVATE_ENDPOINT); + properties.setPublicBaseUrl(publicBaseUrl); + return new AssetExportServiceImpl(publicationService, candidateService, s3Client, properties); + } + + private ExportedAssetManifest conflictingCandidate() { + byte[] bytes = "real uploaded bytes".getBytes(StandardCharsets.UTF_8); + String hex = sha256Hex(bytes); + return new ExportedAssetManifest( + "sha256:" + "0".repeat(64), + 1, + List.of("branding/logo"), + List.of( + new PublishedArtifactDigest( + "branding/logo", + "BINARY", + "artifacts/sha256/" + hex, + "sha256:" + hex, + "image/png", + 1))); + } + + private ExportSnapshot singleAssetSnapshot() { + return snapshot(List.of(selection("branding/logo", 24L, "real uploaded bytes", "image/png"))); } - private static Version version(VersionLifecycleState state) { - return version(7L, 1, state); + private ExportSnapshot snapshot(List items) { + return snapshot(items, CANONICAL_TENANT_ID, CANONICAL_VERSION_ID); } - private static Version version(Long id, int versionNumber, VersionLifecycleState state) { - Version version = new Version(); - version.setId(id); - version.setTenantId("t"); - version.setVersionNumber(versionNumber); - version.setVersionState(state); - return version; + private ExportSnapshot snapshot( + List items, UUID canonicalTenantId, UUID canonicalVersionId) { + return snapshot( + TENANT_ID, VERSION_NUMBER, 19L, 3L, canonicalTenantId, canonicalVersionId, items); } - private static GameAsset gameAsset(String fileName, String data) { - GameAsset asset = new GameAsset(); - asset.setTenantId("t"); - asset.setFileName(fileName); - asset.setContentType("image/png"); - asset.setData(data.getBytes(StandardCharsets.UTF_8)); - return asset; + private ExportSnapshot snapshot( + String tenantId, + int versionNumber, + long versionId, + long versionStateEpoch, + UUID canonicalTenantId, + UUID canonicalVersionId, + List items) { + return new ExportSnapshot( + tenantId, + versionId, + versionNumber, + versionStateEpoch, + canonicalTenantId, + canonicalVersionId, + items); + } + + private static AssetSelection selection( + String usageKey, long assetId, String content, String contentType) { + byte[] bytes = content.getBytes(StandardCharsets.UTF_8); + return new AssetSelection(usageKey, assetId, bytes, contentType, "sha256:" + sha256Hex(bytes)); + } + + private byte[] manifestBytes(ExportedAssetManifest exported) { + return objectStore + .get("manifests/sha256/" + exported.manifestHash().substring("sha256:".length())) + .bytes(); + } + + private static ExportSnapshot copySnapshot(ExportSnapshot source) { + return new ExportSnapshot( + source.tenantId(), + source.versionId(), + source.versionNumber(), + source.capturedVersionStateEpoch(), + source.canonicalTenantId(), + source.canonicalVersionId(), + source.items().stream() + .map( + item -> + new AssetSelection( + item.usageKey(), + item.assetId(), + item.bytes(), + item.contentType(), + item.contentDigest())) + .toList()); + } + + private software.amazon.awssdk.services.s3.model.PutObjectResponse putObject( + org.mockito.invocation.InvocationOnMock invocation) throws IOException { + PutObjectRequest request = invocation.getArgument(0); + RequestBody body = invocation.getArgument(1); + if (failPutBeforeCommit.remove(request.key())) { + throw new IllegalStateException("simulated lost put result before durable readback"); + } + if (objectStore.containsKey(request.key())) { + throw S3Exception.builder() + .statusCode(412) + .message("conditional object already exists") + .build(); + } + byte[] bytes; + try (InputStream input = body.contentStreamProvider().newStream()) { + bytes = input.readAllBytes(); + } + objectStore.put(request.key(), new StoredObject(bytes, request.contentType())); + if (losePutAcknowledgementAfterCommit.remove(request.key())) { + throw new IllegalStateException("simulated lost put acknowledgement after commit"); + } + return PutObjectResponse.builder().build(); + } + + private ResponseBytes getObject( + org.mockito.invocation.InvocationOnMock invocation) { + GetObjectRequest request = invocation.getArgument(0); + if (failReadback.contains(request.key())) { + throw new IllegalStateException("simulated unavailable object readback"); + } + StoredObject object = objectStore.get(request.key()); + if (object == null) { + throw new IllegalStateException("simulated missing object readback"); + } + GetObjectResponse metadata = + GetObjectResponse.builder() + .contentType(object.contentType()) + .contentLength((long) object.bytes().length) + .build(); + return ResponseBytes.fromByteArray(metadata, object.bytes()); + } + + private static String sha256Hex(byte[] bytes) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(bytes); + StringBuilder result = new StringBuilder(digest.length * 2); + for (byte value : digest) { + result.append(Character.forDigit((value >>> 4) & 0xf, 16)); + result.append(Character.forDigit(value & 0xf, 16)); + } + return result.toString(); + } catch (Exception exception) { + throw new IllegalStateException(exception); + } + } + + private record StoredObject(byte[] bytes, String contentType) { + private StoredObject { + bytes = bytes.clone(); + } + + @Override + public byte[] bytes() { + return bytes.clone(); + } } } diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceMinioIntegrationTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceMinioIntegrationTest.java new file mode 100644 index 0000000000..b871866249 --- /dev/null +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceMinioIntegrationTest.java @@ -0,0 +1,347 @@ +package net.firedevops.firemud.gamedesign.service; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +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.Mockito.doAnswer; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.gamedesign.config.AssetStoreProperties; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.AssetSelection; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; +import net.firedevops.firemud.gamedesign.service.impl.AssetExportServiceImpl; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; +import org.mockito.AdditionalAnswers; +import org.mockito.Mockito; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.S3Configuration; +import software.amazon.awssdk.services.s3.model.CreateBucketRequest; +import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; +import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; + +/** + * Exercises the real Game Design exporter and AWS SDK against a run-owned MinIO server. + * + *

Without {@code MINIO_ASSET_EXPORT_ENDPOINT}, this integration test is skipped so ordinary Game + * Design test runs do not require an object store. The pinned-source MinIO workflow must set the + * endpoint and credentials explicitly before selecting this test. + */ +class AssetExportServiceMinioIntegrationTest { + private static final String TENANT_ID = "minio-provider-proof-tenant"; + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("8b0c1a0f-b8c9-4c4b-9021-381f57699001"); + private static final String PUBLIC_BASE_URL = "https://assets.example.invalid/assets"; + + private S3Client s3Client; + private String bucket; + + @AfterEach + void removeOnlyTheOwnedBucket() { + if (s3Client == null) { + return; + } + try { + if (bucket != null) { + for (var object : + s3Client + .listObjectsV2(ListObjectsV2Request.builder().bucket(bucket).build()) + .contents()) { + s3Client.deleteObject( + DeleteObjectRequest.builder().bucket(bucket).key(object.key()).build()); + } + s3Client.deleteBucket(DeleteBucketRequest.builder().bucket(bucket).build()); + } + } finally { + s3Client.close(); + } + } + + @Test + void publishesConditionallyReadsBackExactBytesAndRecoversCommittedPutAgainstMinio() { + String endpoint = System.getenv("MINIO_ASSET_EXPORT_ENDPOINT"); + Assumptions.assumeTrue( + endpoint != null && !endpoint.isBlank(), + "set MINIO_ASSET_EXPORT_ENDPOINT to run the real-provider proof"); + + String accessKey = requiredEnvironment("MINIO_ASSET_EXPORT_ACCESS_KEY"); + String secretKey = requiredEnvironment("MINIO_ASSET_EXPORT_SECRET_KEY"); + s3Client = + S3Client.builder() + .endpointOverride(URI.create(endpoint)) + .credentialsProvider( + StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey))) + .region(Region.US_EAST_1) + .serviceConfiguration(S3Configuration.builder().pathStyleAccessEnabled(true).build()) + .build(); + String ownedBucket = "firemud-asset-export-" + UUID.randomUUID().toString().replace("-", ""); + s3Client.createBucket(CreateBucketRequest.builder().bucket(ownedBucket).build()); + bucket = ownedBucket; + + byte[] publishedBytes = "provider-backed asset bytes".getBytes(StandardCharsets.UTF_8); + String publishedKey = "artifacts/sha256/" + sha256Hex(publishedBytes); + ExportFixture first = fixture(1, publishedBytes, "image/png"); + S3Client observingClient = observingClient(s3Client, first.events()); + AssetExportServiceImpl exporter = newExporter(first, observingClient, bucket, endpoint); + + ExportedAssetManifest published = exporter.exportAssets(TENANT_ID, 1); + assertEquals( + "sha256:" + sha256Hex(publishedBytes), published.artifactDigests().get(0).contentDigest()); + assertEquals(publishedKey, published.artifactDigests().get(0).immutableObjectKey()); + assertStoredObject(publishedKey, publishedBytes, "image/png"); + String manifestKey = + "manifests/sha256/" + published.manifestHash().substring("sha256:".length()); + assertStoredObject(manifestKey, manifestBytes(published), "application/json"); + assertEquals("sha256:" + sha256Hex(manifestBytes(published)), published.manifestHash()); + + S3Exception conditionalConflict = + assertThrows( + S3Exception.class, + () -> + s3Client.putObject( + PutObjectRequest.builder() + .bucket(bucket) + .key(publishedKey) + .contentType("image/png") + .ifNoneMatch("*") + .build(), + RequestBody.fromBytes(publishedBytes))); + assertEquals(412, conditionalConflict.statusCode()); + assertStoredObject(publishedKey, publishedBytes, "image/png"); + + assertTrue( + first.events().indexOf("candidate-read") < first.events().indexOf("put"), + "durable candidate readback must precede the first object-store write"); + assertEquals(published, exporter.exportAssets(TENANT_ID, 1)); + + byte[] conflictingBytes = "pre-existing conflicting bytes".getBytes(StandardCharsets.UTF_8); + byte[] requestedBytes = "requested bytes for conflict".getBytes(StandardCharsets.UTF_8); + String conflictKey = "artifacts/sha256/" + sha256Hex(requestedBytes); + s3Client.putObject( + PutObjectRequest.builder() + .bucket(bucket) + .key(conflictKey) + .contentType("application/octet-stream") + .build(), + RequestBody.fromBytes(conflictingBytes)); + AssetExportServiceImpl conflictingExporter = + newExporter(fixture(2, requestedBytes, "image/png"), s3Client, bucket, endpoint); + IllegalStateException conflict = + assertThrows( + IllegalStateException.class, () -> conflictingExporter.exportAssets(TENANT_ID, 2)); + assertTrue(conflict.getMessage().startsWith("IMMUTABLE_OBJECT_CONFLICT")); + assertStoredObject(conflictKey, conflictingBytes, "application/octet-stream"); + + byte[] acknowledgedLateBytes = + "committed before acknowledgement loss".getBytes(StandardCharsets.UTF_8); + String acknowledgedLateKey = "artifacts/sha256/" + sha256Hex(acknowledgedLateBytes); + S3Client acknowledgementLostClient = + Mockito.mock(S3Client.class, AdditionalAnswers.delegatesTo(s3Client)); + AtomicBoolean loseAcknowledgement = new AtomicBoolean(true); + doAnswer( + invocation -> { + PutObjectRequest request = invocation.getArgument(0); + var response = + s3Client.putObject(request, invocation.getArgument(1, RequestBody.class)); + if (acknowledgedLateKey.equals(request.key()) + && loseAcknowledgement.compareAndSet(true, false)) { + throw SdkClientException.builder() + .message("simulated lost SDK acknowledgement after successful MinIO PUT") + .build(); + } + return response; + }) + .when(acknowledgementLostClient) + .putObject(any(PutObjectRequest.class), any(RequestBody.class)); + ExportFixture acknowledgementFixture = fixture(3, acknowledgedLateBytes, "application/pdf"); + AssetExportServiceImpl acknowledgementExporter = + newExporter(acknowledgementFixture, acknowledgementLostClient, bucket, endpoint); + ExportedAssetManifest recovered = acknowledgementExporter.exportAssets(TENANT_ID, 3); + assertFalse(loseAcknowledgement.get(), "the lost acknowledgement must actually be injected"); + assertEquals(acknowledgedLateKey, recovered.artifactDigests().get(0).immutableObjectKey()); + assertStoredObject(acknowledgedLateKey, acknowledgedLateBytes, "application/pdf"); + } + + private void assertStoredObject(String key, byte[] expectedBytes, String expectedContentType) { + ResponseBytes response = + s3Client.getObjectAsBytes(GetObjectRequest.builder().bucket(bucket).key(key).build()); + assertArrayEquals(expectedBytes, response.asByteArray()); + assertEquals((long) expectedBytes.length, response.response().contentLength()); + assertEquals(expectedContentType, response.response().contentType()); + assertEquals(sha256Hex(expectedBytes), sha256Hex(response.asByteArray())); + } + + private byte[] manifestBytes(ExportedAssetManifest manifest) { + return s3Client + .getObjectAsBytes( + GetObjectRequest.builder() + .bucket(bucket) + .key("manifests/sha256/" + manifest.manifestHash().substring("sha256:".length())) + .build()) + .asByteArray(); + } + + private static String requiredEnvironment(String key) { + String value = System.getenv(key); + if (value == null || value.isBlank()) { + throw new IllegalStateException(key + " must be set when MINIO_ASSET_EXPORT_ENDPOINT is set"); + } + return value; + } + + private static AssetExportServiceImpl newExporter( + ExportFixture fixture, S3Client client, String bucket, String endpoint) { + AssetStoreProperties properties = new AssetStoreProperties(); + properties.setEndpoint(endpoint); + properties.setPublicBaseUrl(PUBLIC_BASE_URL); + properties.setBucket(bucket); + properties.setRegion("us-east-1"); + return new AssetExportServiceImpl( + fixture.publicationService(), fixture.candidateService(), client, properties); + } + + private static S3Client observingClient(S3Client delegate, List events) { + S3Client observer = Mockito.mock(S3Client.class, AdditionalAnswers.delegatesTo(delegate)); + doAnswer( + invocation -> { + events.add("put"); + return delegate.putObject( + invocation.getArgument(0, PutObjectRequest.class), + invocation.getArgument(1, RequestBody.class)); + }) + .when(observer) + .putObject(any(PutObjectRequest.class), any(RequestBody.class)); + return observer; + } + + private static ExportFixture fixture(int versionNumber, byte[] bytes, String contentType) { + ExportSnapshot snapshot = + new ExportSnapshot( + TENANT_ID, + 10_000L + versionNumber, + versionNumber, + 1L, + CANONICAL_TENANT_ID, + UUID.nameUUIDFromBytes( + ("minio-provider-proof-version-" + versionNumber).getBytes(StandardCharsets.UTF_8)), + List.of( + new AssetSelection( + "branding/provider-proof", + 20_000L + versionNumber, + bytes, + contentType, + "sha256:" + sha256Hex(bytes)))); + AtomicReference candidate = new AtomicReference<>(); + List events = new ArrayList<>(); + VersionAssetPublicationService publicationService = + new VersionAssetPublicationService() { + @Override + public void associateDraftAsset( + String tenantId, long versionId, long assetId, String usageType) { + throw new UnsupportedOperationException("the provider proof uses a frozen fixture"); + } + + @Override + public ExportSnapshot freezeOrReadSnapshot(String tenantId, int requestedVersionNumber) { + assertEquals(TENANT_ID, tenantId); + assertEquals(versionNumber, requestedVersionNumber); + return copySnapshot(snapshot); + } + + @Override + public ExportSnapshot readFrozenSnapshot(String tenantId, int requestedVersionNumber) { + assertEquals(TENANT_ID, tenantId); + assertEquals(versionNumber, requestedVersionNumber); + return copySnapshot(snapshot); + } + }; + VersionAssetExportCandidateService candidateService = + new VersionAssetExportCandidateService() { + @Override + public ExportedAssetManifest recordExportCandidate( + String tenantId, int requestedVersionNumber, ExportedAssetManifest requested) { + events.add("candidate-write"); + assertEquals(TENANT_ID, tenantId); + assertEquals(versionNumber, requestedVersionNumber); + ExportedAssetManifest existing = candidate.get(); + if (existing == null && candidate.compareAndSet(null, requested)) { + return requested; + } + existing = candidate.get(); + assertEquals(existing, requested, "candidate conflicts must fail before object writes"); + return existing; + } + + @Override + public ExportedAssetManifest readExportCandidate( + String tenantId, int requestedVersionNumber) { + events.add("candidate-read"); + assertEquals(TENANT_ID, tenantId); + assertEquals(versionNumber, requestedVersionNumber); + return candidate.get(); + } + }; + return new ExportFixture(publicationService, candidateService, events); + } + + private static ExportSnapshot copySnapshot(ExportSnapshot source) { + return new ExportSnapshot( + source.tenantId(), + source.versionId(), + source.versionNumber(), + source.capturedVersionStateEpoch(), + source.canonicalTenantId(), + source.canonicalVersionId(), + source.items().stream() + .map( + item -> + new AssetSelection( + item.usageKey(), + item.assetId(), + item.bytes(), + item.contentType(), + item.contentDigest())) + .toList()); + } + + private static String sha256Hex(byte[] bytes) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(bytes); + StringBuilder hex = new StringBuilder(digest.length * 2); + for (byte value : digest) { + hex.append(Character.forDigit((value >>> 4) & 0xf, 16)); + hex.append(Character.forDigit(value & 0xf, 16)); + } + return hex.toString(); + } catch (Exception exception) { + throw new IllegalStateException("SHA-256 unavailable", exception); + } + } + + private record ExportFixture( + VersionAssetPublicationService publicationService, + VersionAssetExportCandidateService candidateService, + List events) {} +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/GameLogicClientTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/GameLogicClientTest.java new file mode 100644 index 0000000000..55e3988d48 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/GameLogicClientTest.java @@ -0,0 +1,104 @@ +package net.firedevops.firemud.gamedesign.client; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +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.gamelogic.v1.GameLogicServiceGrpc; +import net.firedevops.firemud.gamelogic.v1.GetDraftDesignDigestRequest; +import net.firedevops.firemud.gamelogic.v1.GetDraftDesignDigestResponse; +import org.junit.jupiter.api.Test; + +class GameLogicClientTest { + + @Test + void fullVersionDigestReadPreservesDedicatedAbilitySchemaDigest() throws Exception { + var stub = mock(GameLogicServiceGrpc.GameLogicServiceBlockingStub.class); + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.full("tenant-1", "7", "request-1"); + when(stub.getDraftDesignDigest(any(GetDraftDesignDigestRequest.class))) + .thenReturn( + GetDraftDesignDigestResponse.newBuilder() + .setTenantId(binding.tenantId()) + .setVersionId(binding.versionId()) + .setAppliedCommitId("commit-7") + .setContentDigest("logic-aggregate-digest") + .setDigestSchemaVersion(1) + .setAbilitySchemaDigest("ability-schema-digest") + .build()); + var client = newTestClient(stub); + + var digest = client.getDraftDesignDigestForVersion(binding); + + assertEquals("logic-aggregate-digest", digest.contentDigest()); + assertEquals("ability-schema-digest", digest.abilitySchemaDigest()); + } + + @Test + void fullVersionDigestReadKeepsAbsentAbilitySchemaDigestAbsent() throws Exception { + var stub = mock(GameLogicServiceGrpc.GameLogicServiceBlockingStub.class); + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.full("tenant-1", "7", "request-1"); + when(stub.getDraftDesignDigest(any(GetDraftDesignDigestRequest.class))) + .thenReturn( + GetDraftDesignDigestResponse.newBuilder() + .setTenantId(binding.tenantId()) + .setVersionId(binding.versionId()) + .setAppliedCommitId("commit-7") + .setContentDigest("logic-aggregate-digest") + .setDigestSchemaVersion(1) + .build()); + var client = newTestClient(stub); + + var digest = client.getDraftDesignDigestForVersion(binding); + + assertNull(digest.abilitySchemaDigest()); + } + + private TestGameLogicClient newTestClient(GameLogicServiceGrpc.GameLogicServiceBlockingStub stub) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + CommonGrpcClientProperties grpc = new CommonGrpcClientProperties(); + grpc.setPlaintext(true); + var client = + new TestGameLogicClient( + endpoints, + grpc, + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop(), + stub); + client.initialize(); + return client; + } + + private static final class TestGameLogicClient extends GameLogicClient { + private final GameLogicServiceGrpc.GameLogicServiceBlockingStub stub; + + private TestGameLogicClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer, + GameLogicServiceGrpc.GameLogicServiceBlockingStub stub) { + super(endpoints, tlsProps, channelFactory, stubCustomizer); + this.stub = stub; + } + + private void initialize() throws Exception { + initReloadingClient(); + } + + @Override + protected GameLogicServiceGrpc.GameLogicServiceBlockingStub buildStub(ManagedChannel channel) { + return applyStubCustomizer(stub); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/AssetStorePropertiesBindingTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/AssetStorePropertiesBindingTest.java new file mode 100644 index 0000000000..db22a5100e --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/AssetStorePropertiesBindingTest.java @@ -0,0 +1,78 @@ +package unit.net.firedevops.firemud.gamedesign.config; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.gamedesign.config.AssetStoreProperties; +import org.junit.jupiter.api.Test; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.PropertySource; +import org.springframework.core.env.StandardEnvironment; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.FileSystemResource; + +class AssetStorePropertiesBindingTest { + + @Test + void canonicalEnvironmentVariablesBindToSeparatePrivateAndPublicEndpoints() throws IOException { + AssetStoreProperties properties = + bind( + Map.of( + "ASSET_STORE_ENDPOINT", "https://s3.private.example", + "ASSET_STORE_PUBLIC_BASE_URL", "https://cdn.example/assets", + "ASSET_STORE_BUCKET", "published-assets", + "ASSET_STORE_REGION", "ap-southeast-2", + "ASSET_STORE_ACCESS_KEY", "test-access-key", + "ASSET_STORE_SECRET_KEY", "test-secret-key")); + + assertThat(properties.getEndpoint()).isEqualTo("https://s3.private.example"); + assertThat(properties.getPublicBaseUrl()).isEqualTo("https://cdn.example/assets"); + assertThat(properties.getBucket()).isEqualTo("published-assets"); + assertThat(properties.getRegion()).isEqualTo("ap-southeast-2"); + assertThat(properties.getAccessKey()).isEqualTo("test-access-key"); + assertThat(properties.getSecretKey()).isEqualTo("test-secret-key"); + } + + @Test + void publicBaseAndPrivateConnectionHaveNoEndpointFallbackWhenEnvironmentIsAbsent() + throws IOException { + AssetStoreProperties properties = bind(Map.of()); + + assertThat(properties.getEndpoint()).isEmpty(); + assertThat(properties.getPublicBaseUrl()).isEmpty(); + assertThat(properties.getBucket()).isEmpty(); + assertThat(properties.getAccessKey()).isEmpty(); + assertThat(properties.getSecretKey()).isEmpty(); + assertThat(properties.getRegion()).isEqualTo("ap-southeast-2"); + } + + private AssetStoreProperties bind(Map environmentValues) throws IOException { + StandardEnvironment environment = new StandardEnvironment(); + environment + .getPropertySources() + .remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); + environment + .getPropertySources() + .remove(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME); + environment + .getPropertySources() + .addFirst(new MapPropertySource("test-environment", environmentValues)); + + YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); + ClassPathResource productionResource = new ClassPathResource("application-prod.yml"); + FileSystemResource baseResource = + new FileSystemResource( + productionResource.getFile().toPath().resolveSibling("application.yml")); + List> sources = loader.load("application", baseResource); + sources.forEach(environment.getPropertySources()::addLast); + + return Binder.get(environment) + .bind("asset.store", Bindable.of(AssetStoreProperties.class)) + .orElseThrow(IllegalStateException::new); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameAssetRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameAssetRepositoryTest.java new file mode 100644 index 0000000000..b5d0840f3a --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameAssetRepositoryTest.java @@ -0,0 +1,77 @@ +package net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.DriverManager; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import net.firedevops.firemud.gamedesign.entity.GameAsset; +import org.jooq.DSLContext; +import org.jooq.ExecuteContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.impl.DefaultConfiguration; +import org.jooq.impl.DefaultExecuteListener; +import org.jooq.impl.DefaultExecuteListenerProvider; +import org.junit.jupiter.api.Test; + +class GameAssetRepositoryTest { + @Test + void insertReturnsCompletePersistedAssetReadback() throws Exception { + try (var connection = DriverManager.getConnection("jdbc:h2:mem:game-asset-returning")) { + List executedSql = new ArrayList<>(); + DefaultConfiguration configuration = new DefaultConfiguration(); + configuration.set(connection); + configuration.set(SQLDialect.H2); + configuration.set( + new DefaultExecuteListenerProvider( + new DefaultExecuteListener() { + @Override + public void executeStart(ExecuteContext context) { + executedSql.add(context.sql()); + } + })); + DSLContext dsl = DSL.using(configuration); + dsl.execute( + "CREATE TABLE \"game_assets\" (" + + "\"id\" BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, " + + "\"tenant_id\" VARCHAR(36) NOT NULL, " + + "\"file_name\" VARCHAR(255) NOT NULL, " + + "\"content_type\" VARCHAR(100) NOT NULL, " + + "\"data\" BLOB NOT NULL, " + + "\"created_at\" TIMESTAMP NOT NULL)"); + + byte[] bytes = new byte[] {0, 1, 2, (byte) 0xff}; + LocalDateTime createdAt = LocalDateTime.of(2026, 10, 5, 9, 30); + GameAsset requested = new GameAsset(); + requested.setTenantId("tenant-1"); + requested.setFileName("portrait.png"); + requested.setContentType("image/png"); + requested.setData(bytes); + requested.setCreatedAt(createdAt); + + GameAsset saved = new GameAssetRepository(dsl).save(requested); + + assertThat(saved.getId()).isNotNull(); + assertThat(saved.getTenantId()).isEqualTo("tenant-1"); + assertThat(saved.getFileName()).isEqualTo("portrait.png"); + assertThat(saved.getContentType()).isEqualTo("image/png"); + assertThat(saved.getData()).containsExactly(bytes); + assertThat(saved.getCreatedAt()).isEqualTo(createdAt); + assertThat(executedSql) + .filteredOn(sql -> sql.toLowerCase().contains("insert into \"game_assets\"")) + .singleElement() + .satisfies( + sql -> { + assertThat(sql.toLowerCase()).contains("select \"id\""); + assertThat(sql.toLowerCase()).contains("\"tenant_id\""); + assertThat(sql.toLowerCase()).contains("\"file_name\""); + assertThat(sql.toLowerCase()).contains("\"content_type\""); + assertThat(sql.toLowerCase()).contains("\"data\""); + assertThat(sql.toLowerCase()).contains("\"created_at\""); + assertThat(sql.toLowerCase()).doesNotContain("select *"); + }); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java index b8e6c0a130..750a243e20 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java @@ -26,7 +26,7 @@ void findBoundByRequestConvertsMetadataBackedSmallintUuidAndTimestamp() throws E + "id BIGINT, launch_descriptor_id VARCHAR(64), tenant_id VARCHAR(36), " + "game_template_id BIGINT, control_plane_request_id VARCHAR(64), " + "request_hash VARCHAR(128), version_id BIGINT, script_patch_version VARCHAR(100), " - + "runtime_flags_json VARCHAR(4000), generation_config_revision VARCHAR(128), " + + "runtime_flags_json VARCHAR(4000), generation_config_revision TEXT, " + "version_state_epoch BIGINT, release_bundle_id BIGINT, " + "published_release_bundle_ref VARCHAR(128), remap_set_id VARCHAR(64), " + "descriptor_schema_version SMALLINT, target_namespace VARCHAR(63), " @@ -46,7 +46,10 @@ void findBoundByRequestConvertsMetadataBackedSmallintUuidAndTimestamp() throws E + "request_digest, result_digest, original_request_json, source_evidence_json, " + "outcome_status, failure_code, failure_message, created_at) VALUES " + "(17, 'launch-17', 'private-tenant', 23, 'request-17', 'sha256:request', 29, " - + "'patch-4', '{}', 'generation-6', 8, 31, 'release-31', NULL, 1, 'preview', '" + + "'patch-4', '{}', '" + + "generation-6:" + + "g".repeat(180) + + "', 8, 31, 'release-31', NULL, 1, 'preview', '" + canonicalTenantId + "', 'verdant-harbor', '" + sourceOperationId @@ -62,6 +65,8 @@ void findBoundByRequestConvertsMetadataBackedSmallintUuidAndTimestamp() throws E assertThat(descriptor.getCanonicalTenantId()).isEqualTo(canonicalTenantId.toString()); assertThat(descriptor.getAuthoredWorldSourceOperationId()) .isEqualTo(sourceOperationId.toString()); + assertThat(descriptor.getGenerationConfigRevision()) + .isEqualTo("generation-6:" + "g".repeat(180)); assertThat(descriptor.getCreatedAt()).isEqualTo(createdAt); } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishAttemptParticipantDigestRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishAttemptParticipantDigestRepositoryTest.java new file mode 100644 index 0000000000..84e573e345 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishAttemptParticipantDigestRepositoryTest.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.DriverManager; +import java.time.LocalDateTime; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.entity.PublishAttemptParticipantDigest; +import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; + +class PublishAttemptParticipantDigestRepositoryTest { + @Test + void saveReturnsAndIndependentlyReadsDedicatedAbilitySchemaDigestWithoutAggregateFallback() + throws Exception { + try (var connection = + DriverManager.getConnection( + "jdbc:h2:mem:publish-attempt-participant-digest-" + + UUID.randomUUID() + + ";DATABASE_TO_LOWER=TRUE")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + dsl.execute( + "CREATE TABLE publish_attempt_participant_digest (" + + "id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, " + + "publish_attempt_id BIGINT NOT NULL, participant_key VARCHAR(64) NOT NULL, " + + "scope_value VARCHAR(128) NOT NULL, base_version_id BIGINT, " + + "applied_commit_id VARCHAR(128), content_digest VARCHAR(128), " + + "ability_schema_digest VARCHAR(128), digest_schema_version INT, " + + "error_code VARCHAR(64), error_message VARCHAR(512), observed_at TIMESTAMP NOT NULL)"); + PublishAttemptParticipantDigestRepository repository = + new PublishAttemptParticipantDigestRepository(dsl); + LocalDateTime observedAt = LocalDateTime.of(2026, 10, 5, 9, 30); + + PublishAttemptParticipantDigest gameLogicDigest = digest("GAME_LOGIC", observedAt); + gameLogicDigest.setAbilitySchemaDigest("sha256:ability-schema-17"); + gameLogicDigest.setContentDigest("sha256:aggregate-17"); + PublishAttemptParticipantDigest savedGameLogicDigest = repository.save(gameLogicDigest); + + PublishAttemptParticipantDigest legacyDigest = digest("WORLD_MANAGEMENT", observedAt); + legacyDigest.setContentDigest("sha256:aggregate-world-17"); + PublishAttemptParticipantDigest savedLegacyDigest = repository.save(legacyDigest); + + assertThat(savedGameLogicDigest.getAbilitySchemaDigest()) + .isEqualTo("sha256:ability-schema-17"); + assertThat(savedLegacyDigest.getAbilitySchemaDigest()).isNull(); + assertThat(repository.findByPublishAttemptId(71L)) + .extracting(PublishAttemptParticipantDigest::getParticipantKey) + .containsExactly( + PublishParticipantKey.GAME_LOGIC, PublishParticipantKey.WORLD_MANAGEMENT); + assertThat(repository.findByPublishAttemptId(71L)) + .extracting(PublishAttemptParticipantDigest::getAbilitySchemaDigest) + .containsExactly("sha256:ability-schema-17", null); + assertThat(repository.findByPublishAttemptId(71L).get(0).getContentDigest()) + .isEqualTo("sha256:aggregate-17"); + } + } + + private static PublishAttemptParticipantDigest digest( + String participantKey, LocalDateTime observedAt) { + PublishAttemptParticipantDigest digest = new PublishAttemptParticipantDigest(); + digest.setPublishAttemptId(71L); + digest.setParticipantKey(PublishParticipantKey.valueOf(participantKey)); + digest.setScopeValue("17"); + digest.setBaseVersionId(null); + digest.setAppliedCommitId("commit-17"); + digest.setDigestSchemaVersion(1); + digest.setObservedAt(observedAt); + return digest; + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepositoryTest.java new file mode 100644 index 0000000000..f3b11f2c2d --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepositoryTest.java @@ -0,0 +1,59 @@ +package net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.DriverManager; +import java.time.LocalDateTime; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.entity.PublishAttempt; +import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; +import net.firedevops.firemud.gamedesign.model.PublishType; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; + +class PublishAttemptRepositoryTest { + @Test + void saveReturnsInsertedAttemptAndMatchesIndependentReadback() throws Exception { + try (var connection = + DriverManager.getConnection( + "jdbc:h2:mem:publish-attempt-" + UUID.randomUUID() + ";DATABASE_TO_LOWER=TRUE")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + dsl.execute( + "CREATE TABLE publish_attempt (" + + "id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, " + + "tenant_id VARCHAR(36) NOT NULL, publish_workflow_id VARCHAR(64) NOT NULL, " + + "publish_type VARCHAR(32) NOT NULL, status VARCHAR(16) NOT NULL, " + + "version_id BIGINT, version_number INT NOT NULL, " + + "script_patch_version VARCHAR(100), base_version_id BIGINT, " + + "request_digest VARCHAR(128), failure_code VARCHAR(64), " + + "failure_message TEXT, created_at TIMESTAMP NOT NULL, completed_at TIMESTAMP)"); + + PublishAttempt requested = new PublishAttempt(); + requested.setTenantId("tenant-publish-attempt"); + requested.setPublishWorkflowId("publish-attempt-insert-readback"); + requested.setPublishType(PublishType.FULL_VERSION); + requested.setStatus(PublishAttemptStatus.FAILED); + requested.setVersionId(73L); + requested.setVersionNumber(9); + requested.setRequestDigest("sha256:" + "a".repeat(64)); + requested.setFailureCode("PARTICIPANT_UNAVAILABLE"); + requested.setFailureMessage("full diagnostic evidence " + "x".repeat(600)); + requested.setCreatedAt(LocalDateTime.of(2026, 10, 5, 12, 30)); + requested.setCompletedAt(LocalDateTime.of(2026, 10, 5, 12, 31)); + + PublishAttemptRepository repository = new PublishAttemptRepository(dsl); + PublishAttempt saved = repository.save(requested); + PublishAttempt independentlyRead = + repository.findByPublishWorkflowId("publish-attempt-insert-readback").orElseThrow(); + + assertThat(saved.getId()).isNotNull(); + assertThat(saved).usingRecursiveComparison().ignoringFields("id").isEqualTo(requested); + assertThat(saved).usingRecursiveComparison().isEqualTo(independentlyRead); + assertThat(independentlyRead.getScriptPatchVersion()).isNull(); + assertThat(independentlyRead.getBaseVersionId()).isNull(); + assertThat(independentlyRead.getFailureMessage()).hasSizeGreaterThan(512); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java index 3d9459c62a..a9a267fc4d 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java @@ -16,6 +16,7 @@ class PublishedReleaseBundleRepositoryTest { private static final UUID TENANT_UUID = UUID.fromString("11111111-1111-4111-8111-111111111111"); private static final UUID VERSION_UUID = UUID.fromString("22222222-2222-4222-8222-222222222222"); private static final UUID OTHER_UUID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); @Test void newBundleUsesExactPersistedVersionAndGameIdentityAndReadsItBack() throws Exception { @@ -32,11 +33,19 @@ void newBundleUsesExactPersistedVersionAndGameIdentityAndReadsItBack() throws Ex "NEW_GAME_ROW"); PublishedReleaseBundle requested = bundle("tenant-key", 17L); + String participantDigestsJson = + "[{\"participantKey\":\"GAME_LOGIC\",\"scopeValue\":\"17\"," + + "\"appliedCommitId\":\"commit-17\",\"contentDigest\":\"aggregate-17\"," + + "\"digestSchemaVersion\":1,\"abilitySchemaDigest\":\"ability-17\"}]"; + requested.setParticipantDigestsJson(participantDigestsJson); requested.setPublishedReleaseBundleRef("caller-supplied-release-reference"); PublishedReleaseBundle saved = fixture.repository().save(requested); assertThat(saved.getId()).isNotNull(); assertThat(saved.getCanonicalTenantId()).isEqualTo(TENANT_UUID); assertThat(saved.getCanonicalVersionId()).isEqualTo(VERSION_UUID); + assertThat(saved.getManifestSchemaVersion()).isEqualTo(1); + assertThat(saved.getArtifactDigestsJson()).isEqualTo("[]"); + assertThat(saved.getParticipantDigestsJson()).isEqualTo(participantDigestsJson); assertThat(saved.getPublishedReleaseBundleRef()) .isNotBlank() .isNotEqualTo("caller-supplied-release-reference"); @@ -55,7 +64,7 @@ void newBundleUsesExactPersistedVersionAndGameIdentityAndReadsItBack() throws Ex .usingRecursiveComparison() .isEqualTo(stored); - stored.setManifestHash("sha256:updated-test-value"); + stored.setManifestHash("sha256:" + "c".repeat(64)); assertThatThrownBy(() -> fixture.repository().save(stored)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Published release bundle is immutable"); @@ -65,7 +74,7 @@ void newBundleUsesExactPersistedVersionAndGameIdentityAndReadsItBack() throws Ex .hasMessageContaining("Published release bundle is immutable"); PublishedReleaseBundle persistedAfterAttempts = fixture.repository().findByTenantIdAndVersionId("tenant-key", 17L).orElseThrow(); - assertThat(persistedAfterAttempts.getManifestHash()).isEqualTo("sha256:initial-test-value"); + assertThat(persistedAfterAttempts.getManifestHash()).isEqualTo(MANIFEST_HASH); assertThat(persistedAfterAttempts.getCanonicalTenantId()).isEqualTo(TENANT_UUID); assertThat(persistedAfterAttempts.getCanonicalVersionId()).isEqualTo(VERSION_UUID); assertThat(fixture.bundleCount()).isEqualTo(1); @@ -146,6 +155,7 @@ private static Fixture fixture() throws Exception { + "generation_config_revision VARCHAR(128), " + "required_manifest_asset_keys_json CLOB NOT NULL, " + "participant_digests_json CLOB NOT NULL, command_definitions_json CLOB NOT NULL, " + + "manifest_schema_version INT, artifact_digests_json CLOB, " + "script_only BOOLEAN NOT NULL, script_patch_version VARCHAR(100), " + "published_at TIMESTAMP NOT NULL)"); return new Fixture(connection, dsl, new PublishedReleaseBundleRepository(dsl)); @@ -200,7 +210,9 @@ private static PublishedReleaseBundle bundle(String tenantId, long versionId) { bundle.setVersionNumber(1); bundle.setAttestationSchemaVersion("1"); bundle.setPublishWorkflowId("workflow-" + versionId); - bundle.setManifestHash("sha256:initial-test-value"); + bundle.setManifestHash(MANIFEST_HASH); + bundle.setManifestSchemaVersion(1); + bundle.setArtifactDigestsJson("[]"); bundle.setGenerationConfigRevision("generation-1"); bundle.setRequiredManifestAssetKeysJson("[]"); bundle.setParticipantDigestsJson("[]"); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryTest.java index 3146193994..d460daca12 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryTest.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamedesign.repository; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.sql.DriverManager; import java.util.ArrayList; @@ -47,6 +48,10 @@ public void executeStart(ExecuteContext context) { + "\"last_error_code\" VARCHAR(255), " + "\"last_error_message\" VARCHAR(1000), " + "\"exported_manifest_asset_keys_json\" VARCHAR(4000), " + + "\"manifest_schema_version\" INT, " + + "\"artifact_digests_json\" VARCHAR(4000), " + + "\"published_object_proofs_json\" VARCHAR(4000), " + + "\"candidate_snapshot_version_id\" BIGINT, " + "\"updated_at\" TIMESTAMP NOT NULL, " + "UNIQUE (\"tenant_id\", \"version_id\"))"); @@ -80,6 +85,31 @@ public void executeStart(ExecuteContext context) { assertThat(sql.toLowerCase()).doesNotContain("tenant_id"); assertThat(sql.toLowerCase()).doesNotContain("version_id"); }); + + VersionAssetArtifactRepository repository = new VersionAssetArtifactRepository(dsl); + VersionAssetArtifact stale = + repository.findByTenantIdAndVersionId("tenant-1", 7L).orElseThrow(); + inserted.setStateEpoch(3L); + inserted.setLastWorkflowId("exact-next-workflow"); + VersionAssetArtifact winner = repository.save(inserted); + assertThat(winner.getStateEpoch()).isEqualTo(3L); + assertThat(winner.getLastWorkflowId()).isEqualTo("exact-next-workflow"); + stale.setStateEpoch(3L); + stale.setLastWorkflowId("stale-workflow"); + assertThatThrownBy(() -> repository.save(stale)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_ARTIFACT_STATE_CONFLICT"); + assertThat(repository.findByTenantIdAndVersionId("tenant-1", 7L).orElseThrow()) + .isEqualTo(winner); + winner.setTenantId("other-tenant"); + winner.setStateEpoch(4L); + assertThatThrownBy(() -> repository.save(winner)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_ARTIFACT_STATE_CONFLICT"); + assertThat(repository.findByTenantIdAndVersionId("other-tenant", 7L)).isEmpty(); + assertThat( + repository.findByTenantIdAndVersionId("tenant-1", 7L).orElseThrow().getStateEpoch()) + .isEqualTo(3L); } } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/PublishedArtifactDigestTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/PublishedArtifactDigestTest.java new file mode 100644 index 0000000000..10d624d0be --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/PublishedArtifactDigestTest.java @@ -0,0 +1,129 @@ +package net.firedevops.firemud.gamedesign.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + +class PublishedArtifactDigestTest { + private static final String HASH = "0123456789abcdef".repeat(4); + private static final String MANIFEST_HASH = "sha256:" + HASH; + + @Test + void acceptsExactDigestAndContentAddressedObjectKey() { + PublishedArtifactDigest digest = + new PublishedArtifactDigest( + "branding/logo", + "BINARY", + "artifacts/sha256/" + HASH, + "sha256:" + HASH, + "image/png", + 1); + + assertEquals("branding/logo", digest.usageKey()); + assertEquals("sha256:" + HASH, digest.contentDigest()); + assertEquals(1, digest.artifactSchemaVersion()); + } + + @Test + void rejectsDigestWithoutSha256PrefixOrWithNonCanonicalHex() { + assertThrows( + IllegalArgumentException.class, + () -> + new PublishedArtifactDigest( + "logo", "BINARY", "artifacts/sha256/" + HASH, HASH, "image/png", 1)); + assertThrows( + IllegalArgumentException.class, + () -> + new PublishedArtifactDigest( + "logo", + "BINARY", + "artifacts/sha256/" + HASH.toUpperCase(), + "sha256:" + HASH.toUpperCase(), + "image/png", + 1)); + } + + @Test + void rejectsObjectKeyThatDoesNotAddressTheDigest() { + assertThrows( + IllegalArgumentException.class, + () -> + new PublishedArtifactDigest( + "logo", + "BINARY", + "artifacts/sha256/" + "f".repeat(64), + "sha256:" + HASH, + "image/png", + 1)); + } + + @Test + void rejectsIncompleteArtifactMetadata() { + assertThrows( + IllegalArgumentException.class, + () -> + new PublishedArtifactDigest( + "logo", "BINARY", "artifacts/sha256/" + HASH, "sha256:" + HASH, " ", 1)); + assertThrows( + IllegalArgumentException.class, + () -> + new PublishedArtifactDigest( + "logo", "BINARY", "artifacts/sha256/" + HASH, "sha256:" + HASH, "image/png", 0)); + } + + @Test + void rejectsControlCharactersAndMalformedUtf8Metadata() { + assertThrows(IllegalArgumentException.class, () -> artifact("logo\nname", HASH)); + assertThrows(IllegalArgumentException.class, () -> artifact("logo\ud800", HASH)); + } + + @Test + void manifestRequiresExactUniqueUtf8OrderedDigestKeysAndDefensiveLists() { + PublishedArtifactDigest privateUseBmp = artifact("\ue000", HASH); + PublishedArtifactDigest supplementary = artifact("\ud800\udc00", "f".repeat(64)); + ArrayList keys = new ArrayList<>(List.of("\ue000", "\ud800\udc00")); + ArrayList digests = + new ArrayList<>(List.of(privateUseBmp, supplementary)); + + ExportedAssetManifest manifest = new ExportedAssetManifest(MANIFEST_HASH, 1, keys, digests); + keys.clear(); + digests.clear(); + + assertEquals(List.of("\ue000", "\ud800\udc00"), manifest.requiredManifestAssetKeys()); + assertThrows(UnsupportedOperationException.class, () -> manifest.artifactDigests().clear()); + assertThrows( + IllegalArgumentException.class, + () -> + new ExportedAssetManifest( + MANIFEST_HASH, + 1, + List.of("\ud800\udc00", "\ue000"), + List.of(supplementary, privateUseBmp))); + assertThrows( + IllegalArgumentException.class, + () -> + new ExportedAssetManifest( + MANIFEST_HASH, + 1, + List.of("\ue000", "\ue000"), + List.of(privateUseBmp, privateUseBmp))); + assertThrows( + IllegalArgumentException.class, + () -> + new ExportedAssetManifest( + MANIFEST_HASH, 1, List.of("\ue000"), List.of(privateUseBmp, supplementary))); + } + + private static PublishedArtifactDigest artifact(String usageKey, String hash) { + return new PublishedArtifactDigest( + usageKey, + "BINARY", + "artifacts/sha256/" + hash, + "sha256:" + hash, + "application/octet-stream", + 1); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java index 5aa18c1ccd..3a0a45eaf5 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java @@ -35,6 +35,8 @@ import org.springframework.test.util.ReflectionTestUtils; class GameDesignGrpcServiceAuthTest { + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + @AfterEach void tearDown() { SessionContext.clear(); @@ -90,8 +92,8 @@ void launchDescriptorRejectsJwtOnlyInternalServiceIdentity() { 8, "v1", "workflow-1", - "hash-1", - List.of("manifest.json"), + MANIFEST_HASH, + List.of(), List.of(), "genrev-1", false, @@ -99,7 +101,9 @@ void launchDescriptorRejectsJwtOnlyInternalServiceIdentity() { java.time.LocalDateTime.parse("2026-04-14T12:00:00"), null, null, - null)); + null, + 1, + List.of())); GameDesignGrpcService service = new GameDesignGrpcService( Mockito.mock(PingService.class), diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java index c324059bed..f5e5f83f8f 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java @@ -1,6 +1,8 @@ package net.firedevops.firemud.gamedesign.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.protobuf.UnknownFieldSet; import io.grpc.Context; @@ -34,6 +36,7 @@ import net.firedevops.firemud.gamedesign.service.PingService; import net.firedevops.firemud.gamedesign.service.PublishAttemptPendingReconciliationException; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.RevisionService; import net.firedevops.firemud.gamedesign.service.ScriptPatchPublishFailureException; import net.firedevops.firemud.gamedesign.service.SettingsAuthorityService; @@ -92,6 +95,9 @@ import org.springframework.test.util.ReflectionTestUtils; class GameDesignGrpcServiceTest { + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final String LOGO_DIGEST = "sha256:" + "b".repeat(64); + private final PingService pingService = Mockito.mock(PingService.class); private final RevisionService revisionService = Mockito.mock(RevisionService.class); private final VersionService versionService = Mockito.mock(VersionService.class); @@ -182,9 +188,19 @@ void getPublishedReleaseBundleReturnsCanonicalAttestation() { 8, "v1", "workflow-1", - "abc123", - List.of("logo.png", "manifest.json"), + MANIFEST_HASH, + List.of("logo.png"), List.of( + new PublishParticipantDigestDto( + "GAME_LOGIC", + "7", + null, + "version:7", + "logic-aggregate-digest", + 1, + "ability-schema-v1", + null, + null), new PublishParticipantDigestDto( "GAME_DESIGN_CONTROL_PLANE", "7", "version:7", "digest-1", 1, null, null)), List.of("{\"commandId\":\"block\",\"schemaVersion\":1}"), @@ -194,7 +210,9 @@ void getPublishedReleaseBundleReturnsCanonicalAttestation() { LocalDateTime.parse("2026-04-14T12:00:00"), UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), - "opaque-owner-issued-release-reference")); + "opaque-owner-issued-release-reference", + 1, + List.of(logoProof()))); AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { @@ -211,13 +229,30 @@ void getPublishedReleaseBundleReturnsCanonicalAttestation() { assertEquals( "opaque-owner-issued-release-reference", ref.get().getBundle().getPublishedReleaseBundleRef()); - assertEquals("abc123", ref.get().getBundle().getManifestHash()); + assertEquals(MANIFEST_HASH, ref.get().getBundle().getManifestHash()); assertEquals("genrev-1", ref.get().getBundle().getGenerationConfigRevision()); - assertEquals(2, ref.get().getBundle().getRequiredManifestAssetKeysCount()); + assertEquals(1, ref.get().getBundle().getRequiredManifestAssetKeysCount()); + assertEquals("logo.png", ref.get().getBundle().getRequiredManifestAssetKeys(0)); + assertEquals(1, ref.get().getBundle().getManifestSchemaVersion()); + assertEquals(1, ref.get().getBundle().getArtifactDigestsCount()); + assertEquals("logo.png", ref.get().getBundle().getArtifactDigests(0).getUsageKey()); + assertEquals("BINARY", ref.get().getBundle().getArtifactDigests(0).getArtifactKind()); + assertEquals( + "artifacts/sha256/" + LOGO_DIGEST.substring("sha256:".length()), + ref.get().getBundle().getArtifactDigests(0).getImmutableObjectKey()); + assertEquals(LOGO_DIGEST, ref.get().getBundle().getArtifactDigests(0).getContentDigest()); + assertEquals("image/png", ref.get().getBundle().getArtifactDigests(0).getContentType()); + assertEquals(1, ref.get().getBundle().getArtifactDigests(0).getArtifactSchemaVersion()); assertEquals( List.of("{\"commandId\":\"block\",\"schemaVersion\":1}"), ref.get().getBundle().getCommandDefinitionsList()); - assertEquals(1, ref.get().getBundle().getParticipantDigestsCount()); + assertEquals(2, ref.get().getBundle().getParticipantDigestsCount()); + assertEquals("GAME_LOGIC", ref.get().getBundle().getParticipantDigests(0).getParticipantKey()); + assertTrue(ref.get().getBundle().getParticipantDigests(0).hasAbilitySchemaDigest()); + assertEquals( + "ability-schema-v1", + ref.get().getBundle().getParticipantDigests(0).getAbilitySchemaDigest()); + assertFalse(ref.get().getBundle().getParticipantDigests(1).hasAbilitySchemaDigest()); assertEquals( "67d7b75b-42d1-4ac6-9572-684c5e633cda", ref.get().getBundle().getCanonicalTenantId()); assertEquals( @@ -237,8 +272,8 @@ void getPublishedReleaseBundleRejectsPartialCanonicalIdentity() { 8, "v1", "workflow-1", - "abc123", - List.of("manifest.json"), + MANIFEST_HASH, + List.of(), List.of(), "genrev-1", false, @@ -246,7 +281,9 @@ void getPublishedReleaseBundleRejectsPartialCanonicalIdentity() { LocalDateTime.parse("2026-04-14T12:00:00"), UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), null, - null)); + null, + 1, + List.of())); AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { @@ -273,8 +310,8 @@ void getPublishedReleaseBundleRejectsNilCanonicalIdentity() { 8, "v1", "workflow-1", - "abc123", - List.of("manifest.json"), + MANIFEST_HASH, + List.of(), List.of(), "genrev-1", false, @@ -282,7 +319,9 @@ void getPublishedReleaseBundleRejectsNilCanonicalIdentity() { LocalDateTime.parse("2026-04-14T12:00:00"), UUID.fromString("00000000-0000-0000-0000-000000000000"), UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), - null)); + null, + 1, + List.of())); AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { @@ -1141,8 +1180,8 @@ void getPublishedReleaseBundleRejectsUnsupportedSchema() { 8, "v999", "workflow-1", - "abc123", - List.of("manifest.json"), + MANIFEST_HASH, + List.of(), List.of(), "genrev-1", false, @@ -1150,7 +1189,9 @@ void getPublishedReleaseBundleRejectsUnsupportedSchema() { LocalDateTime.parse("2026-04-14T12:00:00"), UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), - "opaque-owner-issued-release-reference")); + "opaque-owner-issued-release-reference", + 1, + List.of())); AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { @@ -1517,13 +1558,13 @@ void getVersionAssetArtifactStateReturnsArtifactProof() { 7L, 8, "PUBLISHED", - 2L, - "hash-1", + 3L, + MANIFEST_HASH, "workflow-1", null, null, LocalDateTime.parse("2026-04-14T12:00:00"), - List.of("logo.png", "manifest.json"))); + List.of("logo.png"))); AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { @@ -1551,8 +1592,8 @@ public void onCompleted() {} assertEquals( "ARTIFACT_STATE_PUBLISHED", ref.get().getArtifactState().getArtifactState().name()); assertEquals(8, ref.get().getArtifactState().getExportedVersionNumber()); - assertEquals("hash-1", ref.get().getArtifactState().getManifestHash()); - assertEquals(2, ref.get().getArtifactState().getExportedManifestAssetKeysCount()); + assertEquals(MANIFEST_HASH, ref.get().getArtifactState().getManifestHash()); + assertEquals(1, ref.get().getArtifactState().getExportedManifestAssetKeysCount()); } @Test @@ -1565,12 +1606,12 @@ void tombstoneVersionAssetsReturnsStructuredStateTransition() { 8, "TOMBSTONED", 4L, - "hash-1", + MANIFEST_HASH, "wf-1", null, null, LocalDateTime.parse("2026-04-14T12:00:00"), - List.of("manifest.json"))); + List.of())); AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { @@ -1674,6 +1715,16 @@ private ResolveLaunchDescriptorRequest resolveRequest(String controlPlaneRequest .build(); } + private static PublishedArtifactDigest logoProof() { + return new PublishedArtifactDigest( + "logo.png", + "BINARY", + "artifacts/sha256/" + LOGO_DIGEST.substring("sha256:".length()), + LOGO_DIGEST, + "image/png", + 1); + } + private static StreamObserver observerFor(AtomicReference ref) { return new GenericObserver<>(ref); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java index 3c446e7c56..6d51a192d8 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java @@ -57,6 +57,7 @@ class LaunchDescriptorServiceImplTest { private static final String WORLD_SLUG = "silver-march"; private static final String PRIVATE_SOURCE_TENANT_KEY = "game-owner-key-901"; private static final String PUBLISHED_RELEASE_BUNDLE_REF = "opaque-release-reference-from-owner"; + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); @Mock private GameTemplateRepository gameTemplateRepository; @Mock private LaunchDescriptorRepository launchDescriptorRepository; @@ -700,8 +701,8 @@ private PublishedReleaseBundleDto releaseBundle( 8, schemaVersion, "workflow-1", - "hash-1", - List.of("manifest.json"), + MANIFEST_HASH, + List.of(), List.of(), "genrev-1", false, @@ -709,7 +710,9 @@ private PublishedReleaseBundleDto releaseBundle( LocalDateTime.now(), CANONICAL_TENANT_ID, CANONICAL_VERSION_ID, - publishedReleaseBundleRef); + publishedReleaseBundleRef, + 1, + List.of()); } @SuppressWarnings("removal") 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 69644fa0f4..b08bca7d41 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 @@ -77,7 +77,15 @@ void collectFullVersionParticipantDigestsAcceptsEntitySchemaTwoWhenParticipantsC when(gameLogicClient.getDraftDesignDigestForVersion(any(PublicationDigestRequestBinding.class))) .thenReturn( new PublishParticipantDigestDto( - "GAME_LOGIC", "7", "version:7", "digest-logic", 1, null, null)); + "GAME_LOGIC", + "7", + null, + "version:7", + "digest-logic", + 1, + "ability-schema-1", + null, + null)); when(automationScriptingClient.getDraftDesignDigestForVersion( any(PublicationDigestRequestBinding.class))) .thenReturn( @@ -140,6 +148,40 @@ void fullVersionGateRejectsUnavailableGameLogicManifest() { assertTrue(thrown.getMessage().contains("GAME_LOGIC")); } + @Test + void fullVersionGateRequiresDedicatedGameLogicAbilitySchemaDigest() { + VersionDto version = fullVersion(); + List missingDigest = + withAbilitySchemaDigest( + fullVersionDigests(2, "digest-entity", "version:7"), "GAME_LOGIC", null); + List blankDigest = + withAbilitySchemaDigest( + fullVersionDigests(2, "digest-entity", "version:7"), "GAME_LOGIC", " "); + + for (List digests : List.of(missingDigest, blankDigest)) { + PublishGateFailureException thrown = + assertThrows( + PublishGateFailureException.class, () -> service.assertGatePassed(version, digests)); + assertEquals(PublishGateFailureCode.MISSING_ABILITY_SCHEMA_DIGEST, thrown.failureCode()); + } + } + + @Test + void fullVersionGateRejectsAbilitySchemaDigestOwnedByAnotherParticipant() { + VersionDto version = fullVersion(); + List digests = + withAbilitySchemaDigest( + fullVersionDigests(2, "digest-entity", "version:7"), + "AUTOMATION_SCRIPTING", + "legacy-aggregate-digest"); + + PublishGateFailureException thrown = + assertThrows( + PublishGateFailureException.class, () -> service.assertGatePassed(version, digests)); + + assertEquals(PublishGateFailureCode.ABILITY_SCHEMA_DIGEST_OWNER_MISMATCH, thrown.failureCode()); + } + @Test void fullVersionGateFailsClosedForUnsupportedSchema() { VersionDto version = @@ -162,7 +204,15 @@ void fullVersionGateFailsClosedForUnsupportedSchema() { new PublishParticipantDigestDto( "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 2, null, null), new PublishParticipantDigestDto( - "GAME_LOGIC", "7", "version:7", "digest-logic", 1, null, null), + "GAME_LOGIC", + "7", + null, + "version:7", + "digest-logic", + 1, + "ability-schema-1", + null, + null), new PublishParticipantDigestDto( "AUTOMATION_SCRIPTING", "7", "version:7", "digest-script", 5, null, null), new PublishParticipantDigestDto( @@ -198,7 +248,15 @@ void fullVersionGateChecksEachParticipantAgainstItsOwnDigestSchema() { new PublishParticipantDigestDto( "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 4, null, null), new PublishParticipantDigestDto( - "GAME_LOGIC", "7", "version:7", "digest-logic", 1, null, null), + "GAME_LOGIC", + "7", + null, + "version:7", + "digest-logic", + 1, + "ability-schema-1", + null, + null), new PublishParticipantDigestDto( "GAME_DESIGN_CONTROL_PLANE", "7", "version:7", "digest-design", 1, null, null)); @@ -260,7 +318,15 @@ void fullVersionGateRejectsObsoleteAutomationDigestSchema() { new PublishParticipantDigestDto( "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 2, null, null), new PublishParticipantDigestDto( - "GAME_LOGIC", "7", "version:7", "digest-logic", 1, null, null), + "GAME_LOGIC", + "7", + null, + "version:7", + "digest-logic", + 1, + "ability-schema-1", + null, + null), new PublishParticipantDigestDto( "AUTOMATION_SCRIPTING", "7", "version:7", "digest-script", 4, null, null), new PublishParticipantDigestDto( @@ -376,7 +442,15 @@ void fullVersionGateFailsClosedForDuplicateParticipantKey() { new PublishParticipantDigestDto( "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 2, null, null), new PublishParticipantDigestDto( - "GAME_LOGIC", "7", "version:7", "digest-logic", 1, null, null), + "GAME_LOGIC", + "7", + null, + "version:7", + "digest-logic", + 1, + "ability-schema-1", + null, + null), new PublishParticipantDigestDto( "AUTOMATION_SCRIPTING", "7", "version:7", "digest-script", 5, null, null), new PublishParticipantDigestDto( @@ -412,7 +486,15 @@ void fullVersionGateFailsClosedForNullParticipantObservation() { new PublishParticipantDigestDto( "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 2, null, null), new PublishParticipantDigestDto( - "GAME_LOGIC", "7", "version:7", "digest-logic", 1, null, null), + "GAME_LOGIC", + "7", + null, + "version:7", + "digest-logic", + 1, + "ability-schema-1", + null, + null), new PublishParticipantDigestDto( "AUTOMATION_SCRIPTING", "7", "version:7", "digest-script", 5, null, null), new PublishParticipantDigestDto( @@ -710,10 +792,40 @@ private List fullVersionDigests( null, null), new PublishParticipantDigestDto( - "GAME_LOGIC", "7", "version:7", "digest-logic", 1, null, null), + "GAME_LOGIC", + "7", + null, + "version:7", + "digest-logic", + 1, + "ability-schema-1", + null, + null), new PublishParticipantDigestDto( "AUTOMATION_SCRIPTING", "7", "version:7", "digest-script", 5, null, null), new PublishParticipantDigestDto( "GAME_DESIGN_CONTROL_PLANE", "7", "version:7", "digest-design", 1, null, null)); } + + private List withAbilitySchemaDigest( + List digests, + String participantKey, + String abilitySchemaDigest) { + return digests.stream() + .map( + digest -> + new PublishParticipantDigestDto( + digest.participantKey(), + digest.scopeValue(), + digest.baseVersionId(), + digest.appliedCommitId(), + digest.contentDigest(), + digest.digestSchemaVersion(), + participantKey.equals(digest.participantKey()) + ? abilitySchemaDigest + : digest.abilitySchemaDigest(), + digest.errorCode(), + digest.errorMessage())) + .toList(); + } } 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 47f0ae67bb..5aa68e052e 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 @@ -22,6 +22,7 @@ import net.firedevops.firemud.gamedesign.repository.RevisionRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; @@ -29,6 +30,9 @@ import tools.jackson.databind.ObjectMapper; class PublishedReleaseBundleServiceImplTest { + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final String LOGO_DIGEST = "sha256:" + "b".repeat(64); + @Mock private PublishedReleaseBundleRepository repository; @Mock private RevisionRepository revisionRepository; @Mock private VersionRepository versionRepository; @@ -83,19 +87,36 @@ void createFullVersionBundlePersistsImmutableAttestation() { service.createFullVersionBundle( version, "workflow-1", - new ExportedAssetManifest("abc123", List.of("logo.png", "manifest.json")), + logoManifest(), "genrev-1", List.of( + new PublishParticipantDigestDto( + "GAME_LOGIC", + "7", + null, + "version:7", + "digest-logic", + 1, + "ability-schema-v1", + null, + null), new PublishParticipantDigestDto( "GAME_DESIGN_CONTROL_PLANE", "7", "version:7", "digest-1", 1, null, null))); assertEquals(11L, dto.id()); assertEquals("tenant-1", dto.tenantId()); assertEquals(7L, dto.versionId()); - assertEquals("abc123", dto.manifestHash()); + assertEquals(MANIFEST_HASH, dto.manifestHash()); + assertEquals(1, dto.manifestSchemaVersion()); + assertEquals(List.of(logoProof()), dto.artifactDigests()); assertEquals("genrev-1", dto.generationConfigRevision()); - assertEquals(List.of("logo.png", "manifest.json"), dto.requiredManifestAssetKeys()); - assertEquals(1, dto.participantDigests().size()); + assertEquals(List.of("logo.png"), dto.requiredManifestAssetKeys()); + assertEquals(2, dto.participantDigests().size()); + assertEquals("GAME_LOGIC", dto.participantDigests().getFirst().participantKey()); + assertEquals("version:7", dto.participantDigests().getFirst().appliedCommitId()); + assertEquals("digest-logic", dto.participantDigests().getFirst().contentDigest()); + assertEquals(1, dto.participantDigests().getFirst().digestSchemaVersion()); + assertEquals("ability-schema-v1", dto.participantDigests().getFirst().abilitySchemaDigest()); assertEquals(List.of(validCommandDefinition()), dto.commandDefinitions()); assertEquals("v1", dto.attestationSchemaVersion()); assertEquals("owner-issued-reference-11", dto.publishedReleaseBundleRef()); @@ -117,6 +138,11 @@ void retainedBundleWithoutCanonicalIdentityStaysAbsent() { retained.setId(11L); retained.setTenantId("tenant-1"); retained.setVersionId(7L); + retained.setParticipantDigestsJson( + "[{\"participantKey\":\"GAME_LOGIC\",\"scopeValue\":\"7\"," + + "\"baseVersionId\":null,\"appliedCommitId\":\"version:7\"," + + "\"contentDigest\":\"legacy-aggregate\",\"digestSchemaVersion\":1," + + "\"errorCode\":null,\"errorMessage\":null}]"); when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(retained)); var dto = service.findPublishedReleaseBundle("tenant-1", 7L).orElseThrow(); @@ -124,6 +150,9 @@ void retainedBundleWithoutCanonicalIdentityStaysAbsent() { assertNull(dto.canonicalTenantId()); assertNull(dto.canonicalVersionId()); assertNull(dto.publishedReleaseBundleRef()); + assertNull(dto.manifestSchemaVersion()); + assertNull(dto.artifactDigests()); + assertNull(dto.participantDigests().getFirst().abilitySchemaDigest()); } private Version sourceIdentity() { @@ -155,11 +184,7 @@ void createFullVersionBundleRejectsDuplicateAttestation() { IllegalStateException.class, () -> service.createFullVersionBundle( - version, - "workflow-1", - new ExportedAssetManifest("abc123", List.of("manifest.json")), - "genrev-1", - List.of())); + version, "workflow-1", emptyManifest(), "genrev-1", List.of())); } @Test @@ -200,11 +225,7 @@ void createFullVersionBundleRejectsDuplicateCommandDefinitionAlias() { IllegalStateException.class, () -> service.createFullVersionBundle( - version, - "workflow-1", - new ExportedAssetManifest("abc123", List.of("manifest.json")), - "genrev-1", - List.of())); + version, "workflow-1", emptyManifest(), "genrev-1", List.of())); } @Test @@ -222,11 +243,7 @@ void createFullVersionBundleRejectsDuplicateCanonicalCommandIds() { IllegalStateException.class, () -> service.createFullVersionBundle( - version(), - "workflow-1", - new ExportedAssetManifest("abc123", List.of("manifest.json")), - "genrev-1", - List.of())); + version(), "workflow-1", emptyManifest(), "genrev-1", List.of())); } @Test @@ -244,11 +261,7 @@ void createFullVersionBundleRejectsCanonicalIdAndAliasCollisions() { IllegalStateException.class, () -> service.createFullVersionBundle( - version(), - "workflow-1", - new ExportedAssetManifest("abc123", List.of("manifest.json")), - "genrev-1", - List.of())); + version(), "workflow-1", emptyManifest(), "genrev-1", List.of())); } @Test @@ -265,11 +278,7 @@ void createFullVersionBundleRejectsMalformedCommandEffectDeclaration() { IllegalArgumentException.class, () -> service.createFullVersionBundle( - version, - "workflow-1", - new ExportedAssetManifest("abc123", List.of("manifest.json")), - "genrev-1", - List.of())); + version, "workflow-1", emptyManifest(), "genrev-1", List.of())); } private VersionDto version() { @@ -286,4 +295,22 @@ private VersionDto version() { LocalDateTime.now(), LocalDateTime.now()); } + + private static ExportedAssetManifest emptyManifest() { + return new ExportedAssetManifest(MANIFEST_HASH, 1, List.of(), List.of()); + } + + private static ExportedAssetManifest logoManifest() { + return new ExportedAssetManifest(MANIFEST_HASH, 1, List.of("logo.png"), List.of(logoProof())); + } + + private static PublishedArtifactDigest logoProof() { + return new PublishedArtifactDigest( + "logo.png", + "BINARY", + "artifacts/sha256/" + LOGO_DIGEST.substring("sha256:".length()), + LOGO_DIGEST, + "image/png", + 1); + } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java index cebbf19a8f..340fa9b6c4 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java @@ -1,11 +1,15 @@ 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.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.time.LocalDateTime; +import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; @@ -25,6 +29,7 @@ import net.firedevops.firemud.gamedesign.repository.VersionTemplateRemapSetRepository; import net.firedevops.firemud.gamedesign.service.AssetExportService; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -32,6 +37,11 @@ import org.mockito.MockitoAnnotations; class VersionAssetArtifactServiceImplTest { + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final String DIFFERENT_MANIFEST_HASH = "sha256:" + "c".repeat(64); + private static final String LOGO_DIGEST = "sha256:" + "b".repeat(64); + private static final String DIFFERENT_LOGO_DIGEST = "sha256:" + "d".repeat(64); + @Mock private VersionAssetArtifactRepository repository; @Mock private VersionAssetPurgeWorkflowRepository purgeWorkflowRepository; @Mock private VersionRepository versionRepository; @@ -60,8 +70,17 @@ void setUp() { } @Test - void markExportedUnattestedCreatesArtifactStateRow() { - when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.empty()); + void markExportedUnattestedAdvancesPersistedCandidateAndExactRetryDoesNotChurn() { + VersionAssetArtifact staged = new VersionAssetArtifact(); + staged.setTenantId("tenant-1"); + staged.setVersionId(7L); + staged.setExportedVersionNumber(8); + staged.setArtifactState(VersionAssetArtifactState.STAGED); + staged.setStateEpoch(2L); + staged.setLastWorkflowId("workflow-1"); + setArtifactCandidate(staged, MANIFEST_HASH, List.of()); + when(repository.findByTenantIdAndVersionIdForUpdate("tenant-1", 7L)) + .thenReturn(Optional.of(staged)); when(repository.save(any(VersionAssetArtifact.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -71,13 +90,22 @@ void markExportedUnattestedCreatesArtifactStateRow() { 7L, 8, "workflow-1", - new ExportedAssetManifest("hash-1", List.of("a", "b"))); + new ExportedAssetManifest(MANIFEST_HASH, 1, List.of(), List.of())); + var retry = + service.markExportedUnattested( + "tenant-1", + 7L, + 8, + "workflow-1", + new ExportedAssetManifest(MANIFEST_HASH, 1, List.of(), List.of())); assertEquals("EXPORTED_UNATTESTED", state.artifactState()); + assertEquals(state, retry); assertEquals(8, state.exportedVersionNumber()); - assertEquals(1L, state.stateEpoch()); - assertEquals("hash-1", state.manifestHash()); - assertEquals(List.of("a", "b"), state.exportedManifestAssetKeys()); + assertEquals(3L, state.stateEpoch()); + assertEquals(MANIFEST_HASH, state.manifestHash()); + assertEquals(List.of(), state.exportedManifestAssetKeys()); + verify(repository, times(1)).save(any(VersionAssetArtifact.class)); } @Test @@ -88,14 +116,93 @@ void optionalReadDistinguishesMissingArtifactWhileRequiredReadStillFails() { assertThrows(IllegalArgumentException.class, () -> service.getState("tenant-1", 7L)); } + @Test + void getExportCandidateReturnsNullForExactInitialStagedIntent() { + VersionAssetArtifact intent = initialStagedIntent(); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(intent)); + + assertNull(service.getExportCandidate("tenant-1", 7L)); + } + + @Test + void getExportCandidateReturnsRecordedCompleteCandidate() { + VersionAssetArtifact artifact = initialStagedIntent(); + setArtifactCandidate(artifact, MANIFEST_HASH, List.of(logoProof(LOGO_DIGEST))); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); + + assertEquals( + new ExportedAssetManifest( + MANIFEST_HASH, 1, List.of("logo.png"), List.of(logoProof(LOGO_DIGEST))), + service.getExportCandidate("tenant-1", 7L)); + } + + @Test + void getExportCandidateRejectsEachPartialCandidateField() { + for (int partialField = 0; partialField < 4; partialField++) { + VersionAssetArtifact partial = initialStagedIntent(); + switch (partialField) { + case 0 -> partial.setManifestSchemaVersion(1); + case 1 -> partial.setArtifactDigestsJson("[]"); + case 2 -> partial.setPublishedObjectProofsJson("[]"); + case 3 -> partial.setCandidateSnapshotVersionId(7L); + default -> throw new IllegalStateException("unexpected partial field"); + } + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(partial)); + + assertThrows(IllegalStateException.class, () -> service.getExportCandidate("tenant-1", 7L)); + } + } + + @Test + void getExportCandidateRejectsNonemptyOrMalformedInitialKeys() { + for (String keysJson : List.of("[\"logo.png\"]", "not-json", " ")) { + VersionAssetArtifact intent = initialStagedIntent(); + intent.setExportedManifestAssetKeysJson(keysJson); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(intent)); + + assertThrows(IllegalStateException.class, () -> service.getExportCandidate("tenant-1", 7L)); + } + } + + @Test + void getExportCandidateDoesNotTreatOtherStatesAsInitialIntent() { + VersionAssetArtifact artifact = initialStagedIntent(); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); + + for (VersionAssetArtifactState state : VersionAssetArtifactState.values()) { + if (state == VersionAssetArtifactState.STAGED) { + continue; + } + artifact.setArtifactState(state); + assertThrows(IllegalStateException.class, () -> service.getExportCandidate("tenant-1", 7L)); + } + } + + @Test + void getExportCandidateRejectsWrongOwnerScopeAndMissingArtifact() { + VersionAssetArtifact wrongOwner = initialStagedIntent(); + wrongOwner.setTenantId("tenant-2"); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(wrongOwner)); + assertThrows(IllegalStateException.class, () -> service.getExportCandidate("tenant-1", 7L)); + + VersionAssetArtifact wrongVersion = initialStagedIntent(); + when(repository.findByTenantIdAndVersionId("tenant-1", 8L)) + .thenReturn(Optional.of(wrongVersion)); + assertThrows(IllegalStateException.class, () -> service.getExportCandidate("tenant-1", 8L)); + + when(repository.findByTenantIdAndVersionId("tenant-1", 9L)).thenReturn(Optional.empty()); + assertThrows(IllegalArgumentException.class, () -> service.getExportCandidate("tenant-1", 9L)); + } + @Test void repairFailsClosedWhenManifestHashDrifts() { VersionAssetArtifact artifact = new VersionAssetArtifact(); artifact.setTenantId("tenant-1"); artifact.setVersionId(7L); artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); - artifact.setStateEpoch(3L); - artifact.setManifestHash("attested"); + artifact.setStateEpoch(4L); + artifact.setManifestHash(MANIFEST_HASH); + setArtifactCandidate(artifact, MANIFEST_HASH, List.of()); when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); when(repository.save(any(VersionAssetArtifact.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -122,8 +229,8 @@ void repairFailsClosedWhenManifestHashDrifts() { 8, "v1", "workflow-1", - "attested", - List.of("manifest.json"), + MANIFEST_HASH, + List.of(), List.of(), "genrev-1", false, @@ -131,23 +238,26 @@ void repairFailsClosedWhenManifestHashDrifts() { LocalDateTime.now(), UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), - "opaque-owner-issued-release-reference")); + "opaque-owner-issued-release-reference", + 1, + List.of())); when(assetExportService.exportAssets("tenant-1", 8)) - .thenReturn(new ExportedAssetManifest("different", List.of("manifest.json"))); + .thenReturn(new ExportedAssetManifest(DIFFERENT_MANIFEST_HASH, 1, List.of(), List.of())); assertThrows( IllegalStateException.class, - () -> service.repairPublishedVersionAssets("tenant-1", 7L, 3L, "repair-1")); + () -> service.repairPublishedVersionAssets("tenant-1", 7L, 4L, "repair-1")); } @Test - void repairFailsClosedWhenAttestedAssetKeysDrift() { + void repairFailsClosedWhenAttestedArtifactDigestDrifts() { VersionAssetArtifact artifact = new VersionAssetArtifact(); artifact.setTenantId("tenant-1"); artifact.setVersionId(7L); artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); - artifact.setStateEpoch(3L); - artifact.setManifestHash("attested"); + artifact.setStateEpoch(4L); + artifact.setManifestHash(MANIFEST_HASH); + setArtifactCandidate(artifact, MANIFEST_HASH, List.of(logoProof(LOGO_DIGEST))); when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); when(repository.save(any(VersionAssetArtifact.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -167,8 +277,8 @@ void repairFailsClosedWhenAttestedAssetKeysDrift() { 8, "v1", "workflow-1", - "attested", - List.of("logo.png", "manifest.json"), + MANIFEST_HASH, + List.of("logo.png"), List.of(), "genrev-1", false, @@ -176,16 +286,20 @@ void repairFailsClosedWhenAttestedAssetKeysDrift() { LocalDateTime.now(), UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), - "opaque-owner-issued-release-reference")); + "opaque-owner-issued-release-reference", + 1, + List.of(logoProof(LOGO_DIGEST)))); when(assetExportService.exportAssets("tenant-1", 8)) - .thenReturn(new ExportedAssetManifest("attested", List.of("manifest.json"))); + .thenReturn( + new ExportedAssetManifest( + MANIFEST_HASH, 1, List.of("logo.png"), List.of(logoProof(DIFFERENT_LOGO_DIGEST)))); IllegalStateException thrown = assertThrows( IllegalStateException.class, - () -> service.repairPublishedVersionAssets("tenant-1", 7L, 3L, "repair-1")); + () -> service.repairPublishedVersionAssets("tenant-1", 7L, 4L, "repair-1")); - assertEquals("REPAIR_ATTESTED_ASSET_KEY_MISMATCH", thrown.getMessage()); + assertEquals("REPAIR_ATTESTATION_MISMATCH", thrown.getMessage()); } @Test @@ -196,8 +310,8 @@ void beginAndFinalizePurgeUsesExactExportedKeyProof() { artifact.setArtifactState(VersionAssetArtifactState.TOMBSTONED); artifact.setExportedVersionNumber(8); artifact.setStateEpoch(5L); - artifact.setManifestHash("hash-1"); - artifact.setExportedManifestAssetKeysJson("[\"logo.png\",\"manifest.json\"]"); + artifact.setManifestHash(MANIFEST_HASH); + artifact.setExportedManifestAssetKeysJson("[\"logo.png\"]"); when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); when(repository.save(any(VersionAssetArtifact.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -230,7 +344,7 @@ void beginAndFinalizePurgeUsesExactExportedKeyProof() { assertEquals(VersionAssetPurgeWorkflowStatus.SUCCEEDED.name(), finished.workflowStatus()); org.mockito.Mockito.verify(assetExportService) - .deleteExportedAssets("tenant-1", 8, List.of("logo.png", "manifest.json")); + .deleteExportedAssets("tenant-1", 8, List.of("logo.png")); } @Test @@ -241,7 +355,7 @@ void finalizePurgeUsesFrozenExportVersionNumberWithoutVersionRow() { artifact.setExportedVersionNumber(8); artifact.setArtifactState(VersionAssetArtifactState.TOMBSTONED); artifact.setStateEpoch(5L); - artifact.setExportedManifestAssetKeysJson("[\"logo.png\",\"manifest.json\"]"); + artifact.setExportedManifestAssetKeysJson("[\"logo.png\"]"); when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(artifact)); when(repository.save(any(VersionAssetArtifact.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -275,7 +389,7 @@ void finalizePurgeUsesFrozenExportVersionNumberWithoutVersionRow() { service.finalizePurgeVersionAssets("tenant-1", 7L, started.purgeWorkflowId(), 6L); org.mockito.Mockito.verify(assetExportService) - .deleteExportedAssets("tenant-1", 8, List.of("logo.png", "manifest.json")); + .deleteExportedAssets("tenant-1", 8, List.of("logo.png")); } @Test @@ -358,4 +472,56 @@ void canDeleteFailsClosedWhenApprovedRemapSetStillReferencesVersion() { assertEquals(false, eligibility.deletable()); assertEquals("VERSION_ASSET_TEMPLATE_REMAP_REFERENCE_EXISTS", eligibility.failureCode()); } + + private static PublishedArtifactDigest logoProof(String digest) { + return new PublishedArtifactDigest( + "logo.png", + "BINARY", + "artifacts/sha256/" + digest.substring("sha256:".length()), + digest, + "image/png", + 1); + } + + private static VersionAssetArtifact initialStagedIntent() { + VersionAssetArtifact artifact = new VersionAssetArtifact(); + artifact.setTenantId("tenant-1"); + artifact.setVersionId(7L); + artifact.setExportedVersionNumber(8); + artifact.setArtifactState(VersionAssetArtifactState.STAGED); + artifact.setStateEpoch(1L); + artifact.setLastWorkflowId("workflow-1"); + artifact.setExportedManifestAssetKeysJson("[]"); + return artifact; + } + + private static void setArtifactCandidate( + VersionAssetArtifact artifact, String manifestHash, List digests) { + List keys = digests.stream().map(PublishedArtifactDigest::usageKey).toList(); + List objectProofs = new ArrayList<>(); + for (PublishedArtifactDigest digest : digests) { + objectProofs.add(new StoredObjectProof(digest.immutableObjectKey(), digest.contentDigest())); + } + objectProofs.add( + new StoredObjectProof( + "manifests/sha256/" + manifestHash.substring("sha256:".length()), manifestHash)); + objectProofs.sort(java.util.Comparator.comparing(StoredObjectProof::immutableObjectKey)); + + artifact.setManifestHash(manifestHash); + artifact.setManifestSchemaVersion(1); + artifact.setExportedManifestAssetKeysJson(writeJson(keys)); + artifact.setArtifactDigestsJson(writeJson(digests)); + artifact.setPublishedObjectProofsJson(writeJson(objectProofs)); + artifact.setCandidateSnapshotVersionId(artifact.getVersionId()); + } + + private static String writeJson(Object value) { + try { + return new tools.jackson.databind.ObjectMapper().writeValueAsString(value); + } catch (Exception exception) { + throw new IllegalStateException("failed to serialize artifact candidate proof", exception); + } + } + + private record StoredObjectProof(String immutableObjectKey, String contentDigest) {} } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java new file mode 100644 index 0000000000..6a32d4dead --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java @@ -0,0 +1,264 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; +import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.AssetSelection; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.service.VersionAssetPublicationService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import tools.jackson.databind.ObjectMapper; + +@ExtendWith(MockitoExtension.class) +class VersionAssetExportCandidateServiceImplTest { + private static final String TENANT_ID = "candidate-owner"; + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("8b0c1a0f-b8c9-4c4b-9021-381f57699001"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("8b0c1a0f-b8c9-4c4b-9021-381f57699002"); + + @Mock private VersionRepository versionRepository; + @Mock private VersionAssetArtifactRepository artifactRepository; + @Mock private VersionAssetPublicationService publicationService; + @Mock private PlatformTransactionManager transactionManager; + + private Version version; + private VersionAssetArtifact artifact; + private ExportSnapshot snapshot; + private ExportedAssetManifest candidate; + private VersionAssetExportCandidateServiceImpl service; + + @BeforeEach + void setUp() { + TransactionStatus transactionStatus = new SimpleTransactionStatus(); + when(transactionManager.getTransaction(any(TransactionDefinition.class))) + .thenReturn(transactionStatus); + byte[] bytes = "unit candidate bytes".getBytes(StandardCharsets.UTF_8); + String contentDigest = sha256(bytes); + version = newVersion(700L, 1); + artifact = newStagedArtifact(700L, 1L); + snapshot = + new ExportSnapshot( + TENANT_ID, + 700L, + 1, + 1L, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + List.of(new AssetSelection("logo.png", 17L, bytes, "image/png", contentDigest))); + candidate = candidate(contentDigest, "logo.png", "unit manifest bytes"); + + when(versionRepository.findByTenantIdAndVersionNumber(TENANT_ID, 1)) + .thenReturn(Optional.of(version)); + when(versionRepository.findByTenantIdAndIdForUpdate(TENANT_ID, 700L)) + .thenReturn(Optional.of(version)); + when(artifactRepository.findByTenantIdAndVersionIdForUpdate(TENANT_ID, 700L)) + .thenReturn(Optional.of(artifact)); + lenient() + .when(artifactRepository.findByTenantIdAndVersionId(TENANT_ID, 700L)) + .thenAnswer(ignored -> Optional.of(artifact)); + lenient() + .when(artifactRepository.save(any(VersionAssetArtifact.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + lenient().when(publicationService.readFrozenSnapshot(TENANT_ID, 1)).thenReturn(snapshot); + + service = + new VersionAssetExportCandidateServiceImpl( + versionRepository, + artifactRepository, + publicationService, + transactionManager, + new ObjectMapper()); + } + + @Test + void commitsCompleteCandidateEvidenceAndIndependentReadback() { + ExportedAssetManifest recorded = service.recordExportCandidate(TENANT_ID, 1, candidate); + ExportedAssetManifest readback = service.readExportCandidate(TENANT_ID, 1); + + assertThat(recorded).isEqualTo(candidate); + assertThat(readback).isEqualTo(candidate); + assertThat(artifact.getStateEpoch()).isEqualTo(2L); + assertThat(artifact.getManifestHash()).isEqualTo(candidate.manifestHash()); + assertThat(artifact.getManifestSchemaVersion()).isEqualTo(1); + assertThat(artifact.getCandidateSnapshotVersionId()).isEqualTo(700L); + assertThat(artifact.getExportedManifestAssetKeysJson()).isEqualTo("[\"logo.png\"]"); + assertThat(artifact.getPublishedObjectProofsJson()) + .contains("artifacts/sha256/", "manifests/sha256/", candidate.manifestHash()); + verify(transactionManager, times(2)).commit(any(TransactionStatus.class)); + } + + @Test + void exactRetryReadsExistingProofWithoutChangingEpochOrSavingAgain() { + service.recordExportCandidate(TENANT_ID, 1, candidate); + long committedEpoch = artifact.getStateEpoch(); + + assertThat(service.recordExportCandidate(TENANT_ID, 1, candidate)).isEqualTo(candidate); + + assertThat(artifact.getStateEpoch()).isEqualTo(committedEpoch); + verify(artifactRepository, times(1)).save(any(VersionAssetArtifact.class)); + } + + @Test + void conflictingManifestOrFabricatedSourceDigestIsDeniedWithoutMutation() { + service.recordExportCandidate(TENANT_ID, 1, candidate); + long committedEpoch = artifact.getStateEpoch(); + ExportedAssetManifest otherManifest = + new ExportedAssetManifest( + "sha256:" + "a".repeat(64), + candidate.manifestSchemaVersion(), + candidate.requiredManifestAssetKeys(), + candidate.artifactDigests()); + + assertThatThrownBy(() -> service.recordExportCandidate(TENANT_ID, 1, otherManifest)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_EXPORT_CANDIDATE_CONFLICT"); + + String fabricatedDigest = "sha256:" + "b".repeat(64); + ExportedAssetManifest fabricated = + new ExportedAssetManifest( + candidate.manifestHash(), + 1, + List.of("logo.png"), + List.of( + new PublishedArtifactDigest( + "logo.png", + "BINARY", + "artifacts/sha256/" + fabricatedDigest.substring(7), + fabricatedDigest, + "image/png", + 1))); + assertThatThrownBy(() -> service.recordExportCandidate(TENANT_ID, 1, fabricated)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_EXPORT_CANDIDATE_CONFLICT"); + assertThat(artifact.getStateEpoch()).isEqualTo(committedEpoch); + verify(artifactRepository, times(1)).save(any(VersionAssetArtifact.class)); + } + + @Test + void requiresExistingStagedArtifactAndMatchingVersionProvenance() { + when(artifactRepository.findByTenantIdAndVersionIdForUpdate(TENANT_ID, 700L)) + .thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.recordExportCandidate(TENANT_ID, 1, candidate)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_EXPORT_CANDIDATE_NOT_FOUND"); + verify(artifactRepository, never()).save(any(VersionAssetArtifact.class)); + + when(artifactRepository.findByTenantIdAndVersionIdForUpdate(TENANT_ID, 700L)) + .thenReturn(Optional.of(artifact)); + version.setCanonicalVersionId(NIL_UUID); + assertThatThrownBy(() -> service.recordExportCandidate(TENANT_ID, 1, candidate)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_EXPORT_CANDIDATE_CONFLICT"); + verify(artifactRepository, never()).save(any(VersionAssetArtifact.class)); + + version.setCanonicalVersionId(CANONICAL_VERSION_ID); + version.setCanonicalTenantId(UUID.randomUUID()); + assertThatThrownBy(() -> service.recordExportCandidate(TENANT_ID, 1, candidate)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_EXPORT_CANDIDATE_CONFLICT"); + verify(artifactRepository, never()).save(any(VersionAssetArtifact.class)); + } + + @Test + void rejectsEpochOverflowAndProofReadbackDrift() { + artifact.setStateEpoch(Long.MAX_VALUE); + assertThatThrownBy(() -> service.recordExportCandidate(TENANT_ID, 1, candidate)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_EXPORT_CANDIDATE_CONFLICT"); + verify(artifactRepository, never()).save(any(VersionAssetArtifact.class)); + + artifact.setStateEpoch(1L); + service.recordExportCandidate(TENANT_ID, 1, candidate); + artifact.setPublishedObjectProofsJson("[]"); + assertThatThrownBy(() -> service.readExportCandidate(TENANT_ID, 1)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_EXPORT_CANDIDATE_CONFLICT"); + } + + private static Version newVersion(long id, int number) { + Version value = new Version(); + value.setId(id); + value.setTenantId(TENANT_ID); + value.setVersionNumber(number); + value.setVersionState(VersionLifecycleState.DRAFT); + value.setVersionStateEpoch(1L); + value.setCanonicalTenantId(CANONICAL_TENANT_ID); + value.setCanonicalVersionId(CANONICAL_VERSION_ID); + value.setIdentitySourceGameRowId(80L); + value.setIdentitySourceGameTenantKey(TENANT_ID); + value.setIdentitySourceProvenanceKind("NEW_GAME_ROW"); + return value; + } + + private static VersionAssetArtifact newStagedArtifact(long versionId, long epoch) { + VersionAssetArtifact value = new VersionAssetArtifact(); + value.setId(90L); + value.setTenantId(TENANT_ID); + value.setVersionId(versionId); + value.setExportedVersionNumber(1); + value.setArtifactState(VersionAssetArtifactState.STAGED); + value.setStateEpoch(epoch); + value.setLastWorkflowId("stable-workflow"); + value.setExportedManifestAssetKeysJson("[]"); + return value; + } + + private static ExportedAssetManifest candidate( + String contentDigest, String usageKey, String manifestBytes) { + String manifestHash = sha256(manifestBytes.getBytes(StandardCharsets.UTF_8)); + return new ExportedAssetManifest( + manifestHash, + 1, + List.of(usageKey), + List.of( + new PublishedArtifactDigest( + usageKey, + "BINARY", + "artifacts/sha256/" + contentDigest.substring(7), + contentDigest, + "image/png", + 1))); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static final UUID NIL_UUID = new UUID(0L, 0L); +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetPublicationServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetPublicationServiceImplTest.java new file mode 100644 index 0000000000..17780953e5 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetPublicationServiceImplTest.java @@ -0,0 +1,143 @@ +package unit.net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.AssetSelection; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; +import net.firedevops.firemud.gamedesign.service.impl.VersionAssetPublicationServiceImpl; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; + +class VersionAssetPublicationServiceImplTest { + private static final String TENANT_ID = "owner-key"; + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + + @Test + void commitsSnapshotInRequiresNewThenReadsItBackInIndependentRepeatableReadTransaction() { + RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + VersionAssetPublicationRepository repository = mock(VersionAssetPublicationRepository.class); + ExportSnapshot persisted = snapshot(bytes("exact source")); + when(repository.freezeOrReadSnapshot(TENANT_ID, 3)).thenReturn(persisted); + when(repository.readFrozenSnapshot(TENANT_ID, 3)).thenReturn(snapshot(bytes("exact source"))); + VersionAssetPublicationServiceImpl service = + new VersionAssetPublicationServiceImpl(transactionManager, repository); + + ExportSnapshot result = service.freezeOrReadSnapshot(TENANT_ID, 3); + + assertThat(result.items().get(0).bytes()).isEqualTo(bytes("exact source")); + assertThat(transactionManager.commitCount).isEqualTo(2); + assertThat(transactionManager.definitions).hasSize(2); + assertThat(transactionManager.definitions) + .allSatisfy( + definition -> + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW)); + assertThat(transactionManager.definitions.get(0).isReadOnly()).isFalse(); + assertThat(transactionManager.definitions.get(1).isReadOnly()).isTrue(); + assertThat(transactionManager.definitions.get(1).getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); + verify(repository).freezeOrReadSnapshot(TENANT_ID, 3); + verify(repository).readFrozenSnapshot(TENANT_ID, 3); + } + + @Test + void failsClosedWhenIndependentReadbackDiffersFromCommittedSnapshot() { + RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + VersionAssetPublicationRepository repository = mock(VersionAssetPublicationRepository.class); + when(repository.freezeOrReadSnapshot(TENANT_ID, 3)).thenReturn(snapshot(bytes("first"))); + when(repository.readFrozenSnapshot(TENANT_ID, 3)).thenReturn(snapshot(bytes("changed"))); + VersionAssetPublicationServiceImpl service = + new VersionAssetPublicationServiceImpl(transactionManager, repository); + + assertThatThrownBy(() -> service.freezeOrReadSnapshot(TENANT_ID, 3)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("did not match independent readback"); + assertThat(transactionManager.commitCount).isEqualTo(2); + } + + @Test + void associationUsesItsOwnCommittedOwnerTransaction() { + RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + VersionAssetPublicationRepository repository = mock(VersionAssetPublicationRepository.class); + VersionAssetPublicationServiceImpl service = + new VersionAssetPublicationServiceImpl(transactionManager, repository); + + service.associateDraftAsset(TENANT_ID, 17L, 29L, "logo"); + + verify(repository).associateDraftAsset(TENANT_ID, 17L, 29L, "logo"); + assertThat(transactionManager.commitCount).isEqualTo(1); + assertThat(transactionManager.definitions).hasSize(1); + assertThat(transactionManager.definitions.get(0).getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + } + + @Test + void snapshotAndAssetSelectionDefensivelyCopyBytesAndFreezeTheItemList() { + byte[] source = bytes("immutable"); + AssetSelection item = new AssetSelection("logo.png", 29L, source, "image/png", "sha256:abc"); + source[0] = 0; + byte[] exposed = item.bytes(); + exposed[1] = 0; + List items = new ArrayList<>(List.of(item)); + ExportSnapshot snapshot = + new ExportSnapshot(TENANT_ID, 17L, 3, 4L, CANONICAL_TENANT_ID, CANONICAL_VERSION_ID, items); + items.clear(); + + assertThat(snapshot.items()).hasSize(1); + assertThat(snapshot.items().get(0).bytes()).isEqualTo(bytes("immutable")); + assertThatThrownBy(() -> snapshot.items().clear()) + .isInstanceOf(UnsupportedOperationException.class); + } + + private static ExportSnapshot snapshot(byte[] bytes) { + return new ExportSnapshot( + TENANT_ID, + 17L, + 3, + 4L, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + List.of(new AssetSelection("logo.png", 29L, bytes, "image/png", "sha256:abc"))); + } + + private static byte[] bytes(String value) { + return value.getBytes(java.nio.charset.StandardCharsets.UTF_8); + } + + private static final class RecordingTransactionManager + extends AbstractPlatformTransactionManager { + private final List definitions = new ArrayList<>(); + private int commitCount; + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) { + definitions.add(definition); + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + commitCount++; + } + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} 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 5b00e7df3f..fb4dc917df 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 @@ -15,6 +15,7 @@ import java.util.List; import java.util.Optional; import java.util.UUID; +import java.util.stream.Stream; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; @@ -32,25 +33,34 @@ import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.AssetExportOutcomePendingException; 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.PublishAttemptService; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; import net.firedevops.firemud.gamedesign.service.PublishGateService; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import net.firedevops.firemud.gamedesign.service.RecordedParticipantDigestService; import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.MethodSource; import org.mapstruct.factory.Mappers; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; class VersionPublishCommandServiceImplTest { + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final String OTHER_MANIFEST_HASH = "sha256:" + "c".repeat(64); + private static final String LOGO_DIGEST = "sha256:" + "b".repeat(64); + private static final String OTHER_LOGO_DIGEST = "sha256:" + "d".repeat(64); + @Mock private VersionRepository versionRepository; @Mock private GameRepository gameRepository; @Mock private PublishAttemptRepository publishAttemptRepository; @@ -125,6 +135,7 @@ void publishFullVersionUsesTenantScopedVersionSequence() { savedDraft.setVersionState(VersionLifecycleState.DRAFT); savedDraft.setVersionStateEpoch(1L); savedDraft.setUpdatedAt(LocalDateTime.now()); + setCanonicalSource(savedDraft); Version savedPublished = new Version(); savedPublished.setId(10L); savedPublished.setTenantId("tenant-1"); @@ -133,6 +144,7 @@ void publishFullVersionUsesTenantScopedVersionSequence() { savedPublished.setVersionState(VersionLifecycleState.PUBLISHED); savedPublished.setVersionStateEpoch(2L); savedPublished.setUpdatedAt(LocalDateTime.now()); + setCanonicalSource(savedPublished); when(versionRepository.save(any(Version.class))).thenReturn(savedDraft, savedPublished); PublishAttempt attempt = new PublishAttempt(); @@ -154,8 +166,7 @@ void publishFullVersionUsesTenantScopedVersionSequence() { Optional.of(savedDraft), Optional.of(savedPublished)); - ExportedAssetManifest exportedManifest = - new ExportedAssetManifest("abc123", List.of("logo.png", "manifest.json")); + ExportedAssetManifest exportedManifest = logoManifest(); when(assetExportService.exportAssets("tenant-1", 8)).thenReturn(exportedManifest); List participantDigests = List.of( @@ -178,13 +189,13 @@ void publishFullVersionUsesTenantScopedVersionSequence() { 10L, 8, "EXPORTED_UNATTESTED", - 1L, - "abc123", + 3L, + MANIFEST_HASH, "workflow-1", null, null, LocalDateTime.now(), - List.of("logo.png", "manifest.json"))); + List.of("logo.png"))); when(publishedReleaseBundleService.createFullVersionBundle( any(VersionDto.class), any(String.class), @@ -199,8 +210,8 @@ void publishFullVersionUsesTenantScopedVersionSequence() { 8, "v1", "publish:tenant-1:publish-request:workflow-1", - "abc123", - List.of("logo.png", "manifest.json"), + MANIFEST_HASH, + List.of("logo.png"), participantDigests, "genrev-tenant-1-10", false, @@ -208,7 +219,9 @@ void publishFullVersionUsesTenantScopedVersionSequence() { LocalDateTime.now(), UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), - "opaque-owner-issued-release-reference")); + "opaque-owner-issued-release-reference", + 1, + List.of(logoProof()))); when(versionAssetArtifactService.markPublished( any(String.class), any(Long.class), @@ -221,13 +234,15 @@ void publishFullVersionUsesTenantScopedVersionSequence() { 10L, 8, "PUBLISHED", - 2L, - "abc123", + 4L, + MANIFEST_HASH, "workflow-1", null, null, LocalDateTime.now(), - List.of("logo.png", "manifest.json"))); + List.of("logo.png"))); + + mockStagedExport(10L, 8, "publish:tenant-1:publish-request:workflow-1"); VersionDto dto = service.publishFullVersion( @@ -379,7 +394,7 @@ void publishFullVersionGateRejectionDoesNotRecordDigestsOrExportAssets() { } @Test - void publishFullVersionDeletesExportedAssetsWhenAttestationWriteFails() { + void publishFullVersionBundleWriteFailureLeavesAttemptPendingAndRetainsExportedAssets() { Game game = new Game(); game.setId(1L); game.setTenantId("tenant-1"); @@ -409,8 +424,7 @@ void publishFullVersionDeletesExportedAssetsWhenAttestationWriteFails() { .thenReturn(Optional.empty(), Optional.of(attempt)); when(versionRepository.findByTenantIdAndId("tenant-1", 10L)) .thenReturn(Optional.of(savedDraft)); - when(assetExportService.exportAssets("tenant-1", 1)) - .thenReturn(new ExportedAssetManifest("abc123", List.of("manifest.json"))); + when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(logoManifest()); when(publishGateService.collectFullVersionParticipantDigests( any(VersionDto.class), any(String.class), any(String.class))) .thenReturn( @@ -431,13 +445,13 @@ void publishFullVersionDeletesExportedAssetsWhenAttestationWriteFails() { 10L, 1, "EXPORTED_UNATTESTED", - 1L, - "abc123", + 3L, + MANIFEST_HASH, "workflow-1", null, null, LocalDateTime.now(), - List.of("manifest.json"))); + List.of("logo.png"))); org.mockito.Mockito.doThrow(new IllegalStateException("bundle failed")) .when(publishedReleaseBundleService) .createFullVersionBundle( @@ -447,13 +461,17 @@ void publishFullVersionDeletesExportedAssetsWhenAttestationWriteFails() { any(String.class), any(List.class)); + mockStagedExport(10L, 1, "publish:tenant-1:publish-request:workflow-1"); assertThrows( - IllegalStateException.class, + VersionPublishCommandServiceImpl.PendingReconciliationException.class, () -> service.publishFullVersion( "tenant-1", "notes", "workflow-1", "publish:tenant-1:publish-request:workflow-1")); - - verify(assetExportService).deleteExportedAssets("tenant-1", 1, List.of("manifest.json")); + assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + verify(assetExportService, never()) + .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); } @Test @@ -479,8 +497,8 @@ void succeededReplayUsesStoredBundleAfterLifecycleDriftWithoutWritesOrGates() { 1, "v1", workflowId, - "manifest-hash", - List.of("manifest.json"), + MANIFEST_HASH, + List.of(), driftedParticipantDigests, "generation-revision", false, @@ -488,7 +506,9 @@ void succeededReplayUsesStoredBundleAfterLifecycleDriftWithoutWritesOrGates() { LocalDateTime.now(), UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), - "opaque-owner-issued-release-reference"); + "opaque-owner-issued-release-reference", + 1, + List.of()); VersionAssetArtifactStateDto driftedArtifact = new VersionAssetArtifactStateDto( "tenant-1", @@ -496,17 +516,19 @@ void succeededReplayUsesStoredBundleAfterLifecycleDriftWithoutWritesOrGates() { 1, "PURGED", 8L, - "different-manifest-hash", + OTHER_MANIFEST_HASH, "different-workflow", null, null, LocalDateTime.now(), - List.of("manifest.json")); + List.of()); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.of(bundle)); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) + .thenReturn(emptyManifest()); when(versionAssetArtifactService.findState("tenant-1", 10L)) .thenReturn(Optional.of(driftedArtifact)); @@ -555,8 +577,8 @@ void succeededReplayRejectsMismatchedCommittedBundleIdentity() { 1, "v1", workflowId, - "manifest-hash", - List.of("manifest.json"), + MANIFEST_HASH, + List.of(), participantDigests(), "generation-revision", false, @@ -564,7 +586,9 @@ void succeededReplayRejectsMismatchedCommittedBundleIdentity() { LocalDateTime.now(), UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), - "opaque-owner-issued-release-reference"); + "opaque-owner-issued-release-reference", + 1, + List.of()); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) @@ -648,8 +672,8 @@ void legacySucceededAttemptReplaysWithoutBackfillOrMutableReads() { 1, "v1", workflowId, - "manifest-hash", - List.of("manifest.json"), + MANIFEST_HASH, + List.of(), participantDigests(), "generation-revision", false, @@ -657,7 +681,9 @@ void legacySucceededAttemptReplaysWithoutBackfillOrMutableReads() { LocalDateTime.now(), UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), - "opaque-owner-issued-release-reference"); + "opaque-owner-issued-release-reference", + null, + null); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.of(bundle)); @@ -728,13 +754,13 @@ void readbackWithArtifactButNoBundleRemainsPartial() { 10L, 1, "EXPORTED_UNATTESTED", - 1L, - "manifest-hash", + 3L, + MANIFEST_HASH, workflowId, null, null, LocalDateTime.now(), - List.of("manifest.json")); + List.of()); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); @@ -771,8 +797,8 @@ void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { 1, "v1", workflowId, - "manifest-hash", - List.of("manifest.json"), + MANIFEST_HASH, + List.of(), participantDigests, "generation-revision", false, @@ -780,20 +806,22 @@ void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { LocalDateTime.now(), UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), - "opaque-owner-issued-release-reference"); + "opaque-owner-issued-release-reference", + 1, + List.of()); VersionAssetArtifactStateDto artifact = new VersionAssetArtifactStateDto( "tenant-1", 10L, 1, "PUBLISHED", - 2L, - "manifest-hash", + 4L, + MANIFEST_HASH, workflowId, null, null, LocalDateTime.now(), - List.of("manifest.json")); + List.of()); Game game = new Game(); game.setTenantId("tenant-1"); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) @@ -803,6 +831,8 @@ void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.of(bundle)); when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.of(artifact)); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) + .thenReturn(emptyManifest()); PublishWorkflowSnapshot snapshot = service.reconcileFullVersionPublish( @@ -980,7 +1010,7 @@ void mismatchedRequestDigestCannotReplaySucceededAttempt() { } @Test - void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { + void postBundleFailureAfterRollbackMarksFailureAndRetainsExportedAssets() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); @@ -988,8 +1018,7 @@ void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { game.setTenantId("tenant-1"); when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); List participantDigests = participantDigests(); - ExportedAssetManifest manifest = - new ExportedAssetManifest("manifest-hash", List.of("manifest.json")); + ExportedAssetManifest manifest = logoManifest(); PublishedReleaseBundleDto bundle = new PublishedReleaseBundleDto( 1L, @@ -998,8 +1027,8 @@ void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { 1, "v1", workflowId, - "manifest-hash", - List.of("manifest.json"), + MANIFEST_HASH, + List.of("logo.png"), participantDigests, "generation-revision", false, @@ -1007,7 +1036,9 @@ void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { LocalDateTime.now(), UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), - "opaque-owner-issued-release-reference"); + "opaque-owner-issued-release-reference", + 1, + List.of(logoProof())); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); @@ -1029,13 +1060,13 @@ void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { 10L, 1, "EXPORTED_UNATTESTED", - 1L, - "manifest-hash", + 3L, + MANIFEST_HASH, workflowId, null, null, LocalDateTime.now(), - List.of("manifest.json"))); + List.of("logo.png"))); when(publishedReleaseBundleService.createFullVersionBundle( any(VersionDto.class), any(String.class), @@ -1045,7 +1076,6 @@ void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { .thenReturn(bundle); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.empty()); - when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.empty()); org.mockito.Mockito.doAnswer( invocation -> { // The production transaction rolls managed entity changes back before readback. @@ -1056,6 +1086,42 @@ void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { .when(versionRepository) .save(any(Version.class)); + VersionAssetArtifactStateDto stagedIntent = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "STAGED", + 1L, + null, + workflowId, + null, + null, + LocalDateTime.parse("2026-04-14T12:00:00"), + List.of()); + when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, workflowId)) + .thenReturn(stagedIntent); + VersionAssetArtifactStateDto retainedCandidate = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "STAGED", + 2L, + MANIFEST_HASH, + workflowId, + null, + null, + LocalDateTime.now(), + List.of("logo.png")); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn( + Optional.empty(), + Optional.of(stagedIntent), + Optional.of(retainedCandidate), + Optional.of(retainedCandidate)); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) + .thenReturn(null, logoManifest(), logoManifest()); PublishWorkflowSnapshot snapshot = service.reconcileFullVersionPublish( new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId)); @@ -1064,7 +1130,256 @@ void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { verify(publishAttemptService) .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); verify(versionRepository, never()).delete(any(Version.class)); - verify(assetExportService).deleteExportedAssets("tenant-1", 1, List.of("manifest.json")); + } + + @Test + void exactRetryResumesVerifiedStagedCandidateWithoutRestaging() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + VersionAssetArtifactStateDto stagedCandidate = + stagedArtifact("tenant-1", 10L, 1, 2L, MANIFEST_HASH, workflowId, List.of("logo.png")); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); + when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn(Optional.of(stagedCandidate)); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) + .thenReturn(logoManifest()); + when(publishGateService.collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class))) + .thenReturn(participantDigests()); + when(assetExportService.exportAssets("tenant-1", 1)) + .thenThrow(new AssetExportOutcomePendingException("export readback is still pending")); + + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + + verify(versionAssetArtifactService, never()) + .stageExport(any(String.class), any(Long.class), any(Integer.class), any(String.class)); + verify(assetExportService).exportAssets("tenant-1", 1); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + } + + @Test + void participantGateFailureWithPriorStagedCandidateRemainsPending() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + Game game = new Game(); + game.setTenantId("tenant-1"); + VersionAssetArtifactStateDto stagedCandidate = + stagedArtifact("tenant-1", 10L, 1, 2L, MANIFEST_HASH, workflowId, List.of("logo.png")); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); + when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); + when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn(Optional.of(stagedCandidate)); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) + .thenReturn(logoManifest()); + when(publishGateService.collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.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)); + + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + + verify(versionRepository).findByTenantIdAndIdForUpdate("tenant-1", 10L); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + } + + @ParameterizedTest + @MethodSource("invalidStagedRetryEvidence") + void invalidStagedRetryEvidenceRemainsPendingWithoutExport( + VersionAssetArtifactStateDto stagedArtifact, ExportedAssetManifest candidate) { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); + when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn(Optional.of(stagedArtifact)); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)).thenReturn(candidate); + + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + } + + private static Stream invalidStagedRetryEvidence() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + return Stream.of( + Arguments.of( + stagedArtifact("tenant-2", 10L, 1, 2L, MANIFEST_HASH, workflowId, List.of("logo.png")), + logoManifest()), + Arguments.of( + stagedArtifact("tenant-1", 11L, 1, 2L, MANIFEST_HASH, workflowId, List.of("logo.png")), + logoManifest()), + Arguments.of( + stagedArtifact("tenant-1", 10L, 2, 2L, MANIFEST_HASH, workflowId, List.of("logo.png")), + logoManifest()), + Arguments.of( + stagedArtifact( + "tenant-1", 10L, 1, 2L, MANIFEST_HASH, "other-workflow", List.of("logo.png")), + logoManifest()), + Arguments.of( + stagedArtifact("tenant-1", 10L, 1, 0L, MANIFEST_HASH, workflowId, List.of("logo.png")), + logoManifest()), + Arguments.of( + stagedArtifact("tenant-1", 10L, 1, 2L, MANIFEST_HASH, workflowId, List.of("logo.png")), + emptyManifest()), + Arguments.of( + stagedArtifact("tenant-1", 10L, 1, 2L, MANIFEST_HASH, workflowId, List.of("logo.png")), + new ExportedAssetManifest( + MANIFEST_HASH, 2, List.of("logo.png"), List.of(logoProof())))); + } + + private static VersionAssetArtifactStateDto stagedArtifact( + String tenantId, + long versionId, + int versionNumber, + long stateEpoch, + String manifestHash, + String workflowId, + List assetKeys) { + return new VersionAssetArtifactStateDto( + tenantId, + versionId, + versionNumber, + "STAGED", + stateEpoch, + manifestHash, + workflowId, + null, + null, + LocalDateTime.parse("2026-04-14T12:00:00"), + assetKeys); + } + + @Test + void changedArtifactDigestKeepsProofBearingPublicationPending() { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + Version version = fullVersion(10L, 1, VersionLifecycleState.PUBLISHED); + List digests = participantDigests(); + PublishedReleaseBundleDto bundle = + new PublishedReleaseBundleDto( + 1L, + "tenant-1", + 10L, + 1, + "v1", + workflowId, + MANIFEST_HASH, + List.of("logo.png"), + digests, + "generation-revision", + false, + null, + LocalDateTime.now(), + UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), + "opaque-owner-issued-release-reference", + 1, + List.of(logoProof())); + VersionAssetArtifactStateDto artifact = + new VersionAssetArtifactStateDto( + "tenant-1", + 10L, + 1, + "PUBLISHED", + 4L, + MANIFEST_HASH, + workflowId, + null, + null, + LocalDateTime.now(), + List.of("logo.png")); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); + when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) + .thenReturn(Optional.of(bundle)); + when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.of(artifact)); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) + .thenReturn( + new ExportedAssetManifest( + MANIFEST_HASH, 1, List.of("logo.png"), List.of(logoProof(OTHER_LOGO_DIGEST)))); + + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + + assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + verify(publishAttemptService, never()).markFullVersionSucceeded(any(String.class)); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + } + + @Test + void lostExporterAcknowledgementLeavesAttemptPendingForExactReadback() { + assertExporterFailureLeavesPending( + new AssetExportOutcomePendingException("manifest write acknowledgement lost")); + } + + @Test + void laterExporterConflictLeavesAttemptPendingForEarlierWriteReadback() { + assertExporterFailureLeavesPending( + new IllegalStateException("later immutable object key conflict after an earlier write")); + } + + private void assertExporterFailureLeavesPending(RuntimeException exportFailure) { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); + when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(publishGateService.collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class))) + .thenReturn(participantDigests()); + when(assetExportService.exportAssets("tenant-1", 1)).thenThrow(exportFailure); + mockStagedExport(10L, 1, workflowId); + + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + + assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + verify(assetExportService, never()) + .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); } @Test @@ -1072,8 +1387,7 @@ void finalizationFailureWithFailedReadbackLeavesAttemptPending() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); - ExportedAssetManifest manifest = - new ExportedAssetManifest("manifest-hash", List.of("manifest.json")); + ExportedAssetManifest manifest = emptyManifest(); IllegalStateException operationFailure = new IllegalStateException("version finalization failed"); IllegalStateException readFailure = new IllegalStateException("publication read failed"); @@ -1092,6 +1406,7 @@ void finalizationFailureWithFailedReadbackLeavesAttemptPending() { .when(publishAttemptService) .executeFullVersionTransaction(any()); + mockStagedExport(10L, 1, workflowId); VersionPublishCommandServiceImpl.PendingReconciliationException thrown = assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, @@ -1146,8 +1461,7 @@ void ambiguousFinalizationLeavesPendingAttemptAndDoesNotCleanAssets() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); - ExportedAssetManifest manifest = - new ExportedAssetManifest("manifest-hash", List.of("manifest.json")); + ExportedAssetManifest manifest = emptyManifest(); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); @@ -1162,6 +1476,7 @@ void ambiguousFinalizationLeavesPendingAttemptAndDoesNotCleanAssets() { .when(publishAttemptService) .executeFullVersionTransaction(any()); + mockStagedExport(10L, 1, workflowId); assertThrows( IllegalStateException.class, () -> @@ -1181,8 +1496,7 @@ void ambiguousFinalizationWithFailedReadbackLeavesAttemptPending() { String workflowId = "publish:tenant-1:publish-request:workflow-1"; PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); - ExportedAssetManifest manifest = - new ExportedAssetManifest("manifest-hash", List.of("manifest.json")); + ExportedAssetManifest manifest = emptyManifest(); IllegalStateException ambiguousCommit = new IllegalStateException("commit outcome unknown"); IllegalStateException readFailure = new IllegalStateException("publication read failed"); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) @@ -1199,6 +1513,7 @@ void ambiguousFinalizationWithFailedReadbackLeavesAttemptPending() { .when(publishAttemptService) .executeFullVersionTransaction(any()); + mockStagedExport(10L, 1, workflowId); VersionPublishCommandServiceImpl.PendingReconciliationException thrown = assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, @@ -1225,8 +1540,7 @@ void failureMarkingCommitUncertaintyLeavesAttemptPendingAndDoesNotCleanAssets() Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); Game game = new Game(); game.setTenantId("tenant-1"); - ExportedAssetManifest manifest = - new ExportedAssetManifest("manifest-hash", List.of("manifest.json")); + ExportedAssetManifest manifest = emptyManifest(); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); @@ -1237,7 +1551,6 @@ void failureMarkingCommitUncertaintyLeavesAttemptPendingAndDoesNotCleanAssets() when(assetExportService.exportAssets("tenant-1", 1)).thenReturn(manifest); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.empty()); - when(versionAssetArtifactService.findState("tenant-1", 10L)).thenReturn(Optional.empty()); java.util.concurrent.atomic.AtomicInteger transactionCalls = new java.util.concurrent.atomic.AtomicInteger(); org.mockito.Mockito.doAnswer( @@ -1252,6 +1565,20 @@ void failureMarkingCommitUncertaintyLeavesAttemptPendingAndDoesNotCleanAssets() .when(publishAttemptService) .executeFullVersionTransaction(any()); + VersionAssetArtifactStateDto stagedIntent = + stagedArtifact("tenant-1", 10L, 1, 1L, null, workflowId, List.of()); + VersionAssetArtifactStateDto retainedCandidate = + stagedArtifact("tenant-1", 10L, 1, 2L, manifest.manifestHash(), workflowId, List.of()); + when(versionAssetArtifactService.stageExport("tenant-1", 10L, 1, workflowId)) + .thenReturn(stagedIntent); + when(versionAssetArtifactService.findState("tenant-1", 10L)) + .thenReturn( + Optional.empty(), + Optional.of(stagedIntent), + Optional.of(retainedCandidate), + Optional.of(retainedCandidate)); + when(versionAssetArtifactService.getExportCandidate("tenant-1", 10L)) + .thenReturn(null, manifest, manifest); VersionPublishCommandServiceImpl.PendingReconciliationException thrown = assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, @@ -1261,6 +1588,7 @@ void failureMarkingCommitUncertaintyLeavesAttemptPendingAndDoesNotCleanAssets() assertTrue(thrown.getMessage().contains("failure marking commit outcome is unknown")); assertEquals(PublishAttemptStatus.PENDING, attempt.getStatus()); + verify(versionRepository).findByTenantIdAndIdForUpdate("tenant-1", 10L); verify(publishAttemptService) .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); verify(assetExportService, never()) @@ -1290,9 +1618,60 @@ private Version fullVersion(long versionId, int versionNumber, VersionLifecycleS version.setVersionState(state); version.setVersionStateEpoch(state == VersionLifecycleState.PUBLISHED ? 2L : 1L); version.setUpdatedAt(LocalDateTime.now()); + setCanonicalSource(version); return version; } + private void mockStagedExport(long versionId, int versionNumber, String workflowId) { + VersionAssetArtifactStateDto staged = + new VersionAssetArtifactStateDto( + "tenant-1", + versionId, + versionNumber, + "STAGED", + 1L, + null, + workflowId, + null, + null, + LocalDateTime.parse("2026-04-14T12:00:00"), + List.of()); + when(versionAssetArtifactService.stageExport("tenant-1", versionId, versionNumber, workflowId)) + .thenReturn(staged); + when(versionAssetArtifactService.findState("tenant-1", versionId)) + .thenReturn(Optional.empty(), Optional.of(staged), Optional.empty()); + } + + private static void setCanonicalSource(Version version) { + version.setCanonicalTenantId(UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda")); + version.setCanonicalVersionId(UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8")); + version.setIdentitySourceGameRowId(1L); + version.setIdentitySourceGameTenantKey(version.getTenantId()); + version.setIdentitySourceProvenanceKind("NEW_GAME_ROW"); + } + + private static ExportedAssetManifest emptyManifest() { + return new ExportedAssetManifest(MANIFEST_HASH, 1, List.of(), List.of()); + } + + private static ExportedAssetManifest logoManifest() { + return new ExportedAssetManifest(MANIFEST_HASH, 1, List.of("logo.png"), List.of(logoProof())); + } + + private static PublishedArtifactDigest logoProof() { + return logoProof(LOGO_DIGEST); + } + + private static PublishedArtifactDigest logoProof(String digest) { + return new PublishedArtifactDigest( + "logo.png", + "BINARY", + "artifacts/sha256/" + digest.substring("sha256:".length()), + digest, + "image/png", + 1); + } + private List participantDigests() { return List.of( new PublishParticipantDigestDto( diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java index d549ce9eb9..ab0f7786ac 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java @@ -74,6 +74,7 @@ class VersionServiceImplTest { private static final String PUBLISH_REQUEST_ID = "publish-request-1"; + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); @Mock private VersionRepository versionRepository; @Mock private GameRepository gameRepository; @@ -1172,7 +1173,7 @@ private VersionServiceImpl serviceWithPublishGate(PublishGateService gate) { } @Test - void publishPluginVersionRequiresPublishedBaseVersionAbilityDigestMatch() { + void publishPluginVersionMarksValidationFailedWhenBaseGameLogicAbilityDigestDiffers() { Version version = new Version(); version.setId(7L); version.setTenantId("tenant-1"); @@ -1209,6 +1210,44 @@ void publishPluginVersionRequiresPublishedBaseVersionAbilityDigestMatch() { "notes")); assertTrue(thrown.getMessage().contains("VALIDATION_FAILED_DESIGN")); + assertTrue( + thrown.getMessage().contains("does not match the published Game Logic release proof")); + assertEquals(VersionLifecycleState.VALIDATION_FAILED_DESIGN, uploaded.getPublicationState()); + assertEquals( + "abilitySchemaDigest_does_not_match_the_published_Game_Logic_release_proof", + uploaded.getStatusReason()); + verify(publishedPluginVersionRepository).save(uploaded); + verify(pluginVersionStatusEventRepository).save(any()); + verify(pluginBundleStorageService, org.mockito.Mockito.never()) + .exportPluginAssets(any(), any(), any(), any()); + } + + @Test + void publishPluginVersionRejectsLegacyAggregateAloneWithoutMutation() { + assertPluginBaseProofFailureWithoutMutation( + List.of( + new PublishParticipantDigestDto( + "AUTOMATION_SCRIPTING", "7", "version:7", "digest-requested", 5, null, null)), + "missing one exact Game Logic participant record"); + } + + @Test + void publishPluginVersionRejectsAbilitySchemaProofOwnedByAutomationWithoutMutation() { + assertPluginBaseProofFailureWithoutMutation( + List.of( + new PublishParticipantDigestDto( + "AUTOMATION_SCRIPTING", + "7", + null, + "version:7", + "automation-aggregate", + 5, + "digest-requested", + null, + null), + new PublishParticipantDigestDto( + "GAME_LOGIC", "7", null, "version:7", "logic-aggregate", 1, null, null, null)), + "owned by a non-Game Logic participant"); } @Test @@ -1782,32 +1821,98 @@ void listVersionsUsesTenantScopedOrdering() { } private PublishedReleaseBundleDto publishedReleaseBundle( - String tenantId, long versionId, String automationDigest) { - return new PublishedReleaseBundleDto( - 1L, + String tenantId, long versionId, String gameLogicAbilitySchemaDigest) { + return publishedReleaseBundleWithParticipants( tenantId, versionId, - 7, - "v1", - "workflow-1", - "manifest-1", - List.of("manifest.json"), List.of( new PublishParticipantDigestDto( "AUTOMATION_SCRIPTING", String.valueOf(versionId), "version:" + versionId, - automationDigest, + "legacy-aggregate-digest", + 5, + null, + null), + new PublishParticipantDigestDto( + "GAME_LOGIC", + String.valueOf(versionId), + null, + "version:" + versionId, + "logic-aggregate-digest", 1, + gameLogicAbilitySchemaDigest, null, - null)), + null))); + } + + private PublishedReleaseBundleDto publishedReleaseBundleWithParticipants( + String tenantId, long versionId, List participantDigests) { + return new PublishedReleaseBundleDto( + 1L, + tenantId, + versionId, + 7, + "v1", + "workflow-1", + MANIFEST_HASH, + List.of(), + participantDigests, "genrev-1", false, null, LocalDateTime.parse("2026-04-26T10:00:00"), UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), - "opaque-owner-issued-release-reference"); + "opaque-owner-issued-release-reference", + 1, + List.of()); + } + + private void assertPluginBaseProofFailureWithoutMutation( + List participantDigests, String expectedMessage) { + Version version = new Version(); + version.setId(7L); + version.setTenantId("tenant-1"); + when(versionRepository.findByTenantIdAndId("tenant-1", 7L)).thenReturn(Optional.of(version)); + PublishedPluginVersion uploaded = uploadedPluginVersion("tenant-1", "plugin-1", "plugin-v1"); + uploaded.setAbilitySchemaDigest("digest-requested"); + when(publishedPluginVersionRepository.findByTenantIdAndPluginIdAndPluginVersionId( + "tenant-1", "plugin-1", "plugin-v1")) + .thenReturn(Optional.of(uploaded)); + when(pluginBundleStorageService.loadPluginBundle("tenant-1", "plugin-1", "plugin-v1")) + .thenReturn(new byte[] {1, 2, 3}); + when(pluginBundleIntakeService.parseAndVerify(any())) + .thenReturn(parsedPluginBundle("plugin-1", "plugin-v1", 7L, "digest-requested")); + when(publishedReleaseBundleService.getPublishedReleaseBundle("tenant-1", 7L)) + .thenReturn(publishedReleaseBundleWithParticipants("tenant-1", 7L, participantDigests)); + + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, + () -> + service.publishPluginVersion( + "tenant-1", + "plugin-1", + "plugin-v1", + 7L, + "digest-requested", + "bundle-1", + 1, + "", + "", + "signer-1", + false, + "ALLOWED", + "notes")); + + assertTrue(thrown.getMessage().contains(expectedMessage)); + assertEquals(VersionLifecycleState.SIGNATURE_VERIFIED, uploaded.getPublicationState()); + verify(publishedPluginVersionRepository, org.mockito.Mockito.never()) + .save(any(PublishedPluginVersion.class)); + verify(pluginVersionStatusEventRepository, org.mockito.Mockito.never()).save(any()); + verify(pluginBundleStorageService, org.mockito.Mockito.never()) + .exportPluginAssets(any(), any(), any(), any()); } private PublishedPluginVersion uploadedPluginVersion( 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..4961e87675 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 @@ -16,5 +16,15 @@ record GameLogicDraftDesignDigest( String scopeValue, String appliedCommitId, String contentDigest, - int digestSchemaVersion) {} + int digestSchemaVersion, + String abilitySchemaDigest) { + public GameLogicDraftDesignDigest( + String tenantId, + String scopeValue, + String appliedCommitId, + String contentDigest, + int digestSchemaVersion) { + this(tenantId, scopeValue, appliedCommitId, contentDigest, digestSchemaVersion, null); + } + } } 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..b022766fe9 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 @@ -196,14 +196,17 @@ public void getDraftDesignDigest( gameLogicDraftDesignDigestService.getDraftDesignDigest( request.getTenantId(), request.getVersionId()); binding.requireOwnerScope(digest.tenantId(), digest.scopeValue()); - responseObserver.onNext( + var responseBuilder = GetDraftDesignDigestResponse.newBuilder() .setTenantId(binding.tenantId()) .setVersionId(binding.versionId()) .setAppliedCommitId(digest.appliedCommitId()) .setContentDigest(digest.contentDigest()) - .setDigestSchemaVersion(digest.digestSchemaVersion()) - .build()); + .setDigestSchemaVersion(digest.digestSchemaVersion()); + if (digest.abilitySchemaDigest() != null) { + responseBuilder.setAbilitySchemaDigest(digest.abilitySchemaDigest()); + } + responseObserver.onNext(responseBuilder.build()); responseObserver.onCompleted(); } catch (AdminAuthorizationException ex) { responseObserver.onNext( 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 1647d1925a..dbcbcb59c5 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,6 +1,7 @@ package net.firedevops.firemud.gamelogic.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; @@ -314,6 +315,7 @@ public void onCompleted() {} assertEquals("", ref.get().getAppliedCommitId()); assertEquals("", ref.get().getContentDigest()); assertEquals(0, ref.get().getDigestSchemaVersion()); + assertFalse(ref.get().hasAbilitySchemaDigest()); } @Test @@ -443,7 +445,7 @@ void getDraftDesignDigestFailsClosedWhenWorkloadNamespaceIsMissingOrInvalid() { Mockito.when(configuredDigestService.getDraftDesignDigest("1", "7")) .thenReturn( new GameLogicDraftDesignDigestService.GameLogicDraftDesignDigest( - "1", "7", "version:7", "digest-game-logic", 1)); + "1", "7", "version:7", "digest-game-logic", 1, "ability-schema-v1")); GameLogicGrpcService configuredService = newDigestService(configuredDigestService, TEST_NAMESPACE); AtomicReference configuredResponse = new AtomicReference<>(); @@ -453,6 +455,8 @@ void getDraftDesignDigestFailsClosedWhenWorkloadNamespaceIsMissingOrInvalid() { assertTrue(configuredResponse.get().getError().getCode().isEmpty()); assertEquals("1", configuredResponse.get().getTenantId()); assertEquals("7", configuredResponse.get().getVersionId()); + assertTrue(configuredResponse.get().hasAbilitySchemaDigest()); + assertEquals("ability-schema-v1", configuredResponse.get().getAbilitySchemaDigest()); Mockito.verify(configuredDigestService).getDraftDesignDigest("1", "7"); }