diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index da3c0c8ee9..c49b242894 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: @@ -952,20 +951,47 @@ jobs: --tests net.firedevops.firemud.gamedesign.service.EntityDigestBaselineMigrationIntegrationTest \ --tests integration.net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepositoryIntegrationTest \ --tests integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepositoryIntegrationTest \ + --tests integration.net.firedevops.firemud.gamedesign.repository.VersionCanonicalIdentityIntegrationTest \ + --tests integration.net.firedevops.firemud.gamedesign.repository.PublishedReleaseCanonicalIdentityIntegrationTest \ -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 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()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest#concurrentExactFirstWritersReturnOneImmutableReceipt()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest#ownerRollbackLeavesNoClaimAndLostAcknowledgementRetryReadsExactReceipt()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest#databaseRejectsAssociationUpdatesDeletesTruncatesAndContradictorySourceInsert()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.VersionCanonicalIdentityIntegrationTest#v35_1PreservesRetainedVersionHistoryAndLeavesIdentityUnmapped()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.VersionCanonicalIdentityIntegrationTest#savePersistsAndReadsBackFreshCanonicalIdentityAcrossUpdate()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.VersionCanonicalIdentityIntegrationTest#newVersionIdentityUsesExactRetainedGameSourceProvenance()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.VersionCanonicalIdentityIntegrationTest#canonicalLookupRejectsWrongTenantMissingAndNilIdsWithoutMutation()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.VersionCanonicalIdentityIntegrationTest#databaseRejectsIdentityMutationNilIdentityAndMismatchedSource()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.VersionCanonicalIdentityIntegrationTest#canonicalIdentityRejectsTruncateWhileUnmappedRetainedVersionRemainsDeletable()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.PublishedReleaseCanonicalIdentityIntegrationTest#migrationLeavesRetainedReleaseTupleAndXminUnchangedAndUnmapped()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.PublishedReleaseCanonicalIdentityIntegrationTest#normalSavePersistsExactVersionAndVerifiedGameIdentityAndReadsBackWithinTransaction()' \ + --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 'net.firedevops.firemud.gamedesign.service.EntityDigestBaselineMigrationIntegrationTest#exactRetryReadsCommittedEvidenceWithoutCallingEntityAgain()' \ --require-case 'net.firedevops.firemud.gamedesign.service.EntityDigestBaselineMigrationIntegrationTest#databaseMigrationRolesHaveOnlyTheirDirectTablePrivileges()' \ 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 + with: + name: game-design-owner-component-proof-${{ github.sha }}-${{ github.run_attempt }} + # A later integrationTest invocation may replace these reports, even after failure. + path: | + services/game-design-service/build/test-results/integrationTest/*.xml + services/game-design-service/build/reports/tests/integrationTest/** + if-no-files-found: error + retention-days: 7 + - name: Run Game Design authored-source launch descriptor PostgreSQL and socket mTLS proof if: ${{ matrix.module == 'game-design-service' }} run: | @@ -1040,6 +1066,47 @@ jobs: if-no-files-found: warn retention-days: 7 + - name: Run source-qualified Game Design version-state PostgreSQL and socket proof + if: ${{ !cancelled() && matrix.module == 'game-design-service' }} + run: | + ./gradlew :game-design-service:integrationTest \ + --tests integration.net.firedevops.firemud.gamedesign.service.AuthoredWorldVersionStateIntegrationTest \ + --tests integration.net.firedevops.firemud.gamedesign.service.AuthoredWorldVersionStateMtlsIntegrationTest \ + :game-design-service:test \ + --tests net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldVersionStateMtlsTest \ + --continue -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.gamedesign.service.AuthoredWorldVersionStateIntegrationTest \ + --require-suite integration.net.firedevops.firemud.gamedesign.service.AuthoredWorldVersionStateMtlsIntegrationTest \ + --require-suite net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldVersionStateMtlsTest \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.AuthoredWorldVersionStateIntegrationTest#readsCompletePersistedSourceAndCurrentVersionWithoutMutatingOwnerRows()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.AuthoredWorldVersionStateIntegrationTest#rejectsStaleSourceDigestAndARealVersionOwnedByAnotherGame()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.AuthoredWorldVersionStateIntegrationTest#freshOwnerSnapshotDoesNotJoinAnAmbientRepeatableReadSnapshot()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.AuthoredWorldVersionStateIntegrationTest#versionChangeDuringOwnerReadRemainsOneRepeatableReadSnapshot()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.AuthoredWorldVersionStateMtlsIntegrationTest#returnsCompletePersistedSourceAndVersionStateOverSocketWithoutMutation(Path)' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.AuthoredWorldVersionStateMtlsIntegrationTest#changedSourceDigestAndForeignPersistedVersionFailClosedWithoutMutation(Path)' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.AuthoredWorldVersionStateMtlsIntegrationTest#sameReadIdentityObservesFreshCommittedLifecycleAndEpochSnapshot(Path)' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldVersionStateMtlsTest#exactSameNamespaceWorldWorkloadReceivesCompleteVersionStateEvidenceOverSocket(Path)' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldVersionStateMtlsTest#wrongServiceNamespaceAndSharedCertificatesAreRejectedBeforeProducerRead()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldVersionStateMtlsTest#missingClientCertificateCannotSupplyAnAuthenticatedPeerToProducer()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldVersionStateMtlsTest#unknownClosedRequestFieldsAreRejectedBeforeProducerRead()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldVersionStateMtlsTest#worldClientRejectsWrongSameCaServerIdentityBeforeSendingAnyRpc(Path)' \ + --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldVersionStateMtlsTest#worldClientRejectsMismatchedCompleteEvidenceOverPhysicalSocket(Path)' \ + game-design-service + + - name: Upload source-qualified Game Design version-state proof results + if: ${{ always() && matrix.module == 'game-design-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: game-design-authored-world-version-state-proof-${{ github.sha }} + path: | + services/game-design-service/build/test-results/integrationTest/TEST-*AuthoredWorldVersionStateIntegrationTest.xml + services/game-design-service/build/test-results/integrationTest/TEST-*AuthoredWorldVersionStateMtlsIntegrationTest.xml + services/game-design-service/build/test-results/test/TEST-*AuthoredWorldVersionStateMtlsTest.xml + if-no-files-found: warn + retention-days: 7 + - name: Run World authored-source intake PostgreSQL component proof if: ${{ matrix.module == 'world-management-service' }} run: | @@ -1057,6 +1124,11 @@ jobs: --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeIntegrationTest#concurrentExactRetriesReturnTheSingleCommittedReceipt()' \ --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeIntegrationTest#concurrentLegacyNumericClaimSerializesBeforeFreshSelectorAllocation()' \ --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeIntegrationTest#concurrentLegacyClaimAfterAllocationCannotTakeTheReservedSelector()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeIntegrationTest#canonicalReservationsGuardEveryWorldRowMutationTrigger()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeIntegrationTest#readBySourceReturnsExactCommittedReceiptOnRepeatedCallsWithoutGrowth()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeIntegrationTest#readBySourceRejectsAnyChangedBindingAndRetainedOrUnmappedEvidence()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeIntegrationTest#readBySourceRejectsMalformedBinding()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeIntegrationTest#readBySourceDoesNotExposeUncommittedOwnerEvidence()' \ world-management-service - name: Upload World authored-source intake proof results @@ -1068,6 +1140,32 @@ jobs: if-no-files-found: warn retention-days: 7 + - name: Run World shared publication-fence PostgreSQL prerequisite proof + if: ${{ !cancelled() && matrix.module == 'world-management-service' }} + run: | + ./gradlew :world-management-service:integrationTest \ + --tests net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#rollbackAndCommittedExactReadbackRetainOneImmutableAttempt()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#sameCanonicalTenantAndVersionRowCanBeLockedThroughDifferentIntakes()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#concurrentExactFreezeRetryReturnsTheSameFenceAndCheckpoint()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#writerHoldingTheOpenLockCommitsBeforeFreezeCapturesItsCheckpoint()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#freezeHoldingTheLockMakesAWaitingOrdinaryWriterFailClosed()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#changedAssociationSourceRequestDigestEpochAndMissingCheckpointDoNotMutate()' \ + world-management-service + + - name: Upload World shared publication-fence prerequisite proof results + if: ${{ always() && matrix.module == 'world-management-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: world-publication-fence-prerequisite-proof-${{ github.sha }} + path: services/world-management-service/build/test-results/integrationTest/TEST-*WorldDesignPublicationFenceIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + - name: Run World authored-source intake socket mTLS proof if: ${{ !cancelled() && matrix.module == 'world-management-service' }} run: | @@ -1123,7 +1221,9 @@ jobs: with: name: game-design-owner-migration-proof-${{ github.sha }} # Gradle may shorten long report filenames; strict verification binds suite/class names. - path: services/game-design-service/build/test-results/integrationTest/*.xml + path: | + services/game-design-service/build/test-results/integrationTest/*.xml + services/game-design-service/build/test-results/integrationTest/TEST-*VersionCanonicalIdentityIntegrationTest.xml if-no-files-found: error - name: Run Game Session authored-world intake PostgreSQL component proof @@ -2223,7 +2323,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/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 8704952921..b8f4cef2de 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -48,6 +48,8 @@ The committed descriptor retains those source fields and the exact resolved temp The complete immutable resolved launch binding consists of this unchanged closed descriptor and a separately authenticated full release attestation produced through Game Design's normal owner workflow. The attestation binds the exact descriptor and authored-source identity, plus the canonical UUID version identity, to the resolved release and its required participant, ability-schema, artifact and manifest evidence under the [version-resolution predicate](../../system-architecture-versioning-runtime.md#launch-descriptor-version-resolution-rules). The descriptor alone is not full release evidence, and a caller-supplied or operator-maintained sidecar is not an attestation. Consumers authenticate and verify the exact attestation against the descriptor before retaining or using the pair. The attestation's wire representation and durable association with the descriptor are not specified by the closed v1 contract and remain to be settled; this requirement does not extend or reinterpret its schema or digest. +Normal release creation preserves the actual persisted canonical tenant and Version UUIDs with the release bundle. Game Design derives this pair only from the exact Version's immutable, verified Game source association and reads it back in the publication transaction; private row keys, selector similarity and caller-supplied replacements cannot establish it. Release readback carries that stored pair separately from the legacy private Version selector. A retained bundle with no proved association remains unmapped, never backfilled by inference, and cannot satisfy canonical launch evidence. The identity pair does not supply missing participant, ability, artifact, manifest or descriptor-association proof. + The closed binding schema has `schemaVersion=1`. Its request preimage begins with the segment `game-design-authored-world-launch-descriptor-request/v1`, followed by field-name/value segment pairs in this order: `schemaVersion`, `targetNamespace`, `controlPlaneRequestId`, `canonicalTenantId`, `worldSlug`, `authoredWorldSourceOperationId`, `authoredWorldSourceEvidenceDigest`, `gameTemplateId`, then presence/value pairs for `requestedScriptPatchVersion`, `sourceVersionId`, `targetVersionId` and `requestedRuntimeFlagsJson`. Each optional pair uses the exact field names `.present` and `.value`; presence is lowercase `true` or `false`, absent values are empty, and present-empty text is distinct from absence. The result preimage begins with `game-design-authored-world-launch-descriptor-result/v1`, carries the same ordered request pairs, then `requestDigest`, `launchDescriptorId`, `versionId`, presence/value for `scriptPatchVersion`, `runtimeFlagsJson`, `generationConfigRevision`, `versionStateEpoch`, `releaseBundleId`, `publishedReleaseBundleRef`, and presence/value for `remapSetId`. Only `resultDigest` is excluded from that result preimage. Every segment is decimal UTF-8 byte length, `:`, and its exact strict UTF-8 bytes; no trimming, case folding or Unicode normalization occurs. UUIDs are canonical non-nil text, counters use positive canonical decimal text, and each digest is `sha256:` plus 64 lowercase hexadecimal digits. Numeric template/version/release representation in this candidate remains the explicitly tracked owner-graph limitation, not a new canonical identity rule. Only the exact same-namespace Game Session workload may resolve a new canonical descriptor. Its request claim and immutable result commit atomically in the existing descriptor family. An identical retry returns the stored descriptor without resolving changed defaults, another version or another release. Conflicting source, scope or request input denies without replacing the original. Retained unbound or unmapped rows cannot be interpreted as canonical evidence. Exact committed readback is non-mutating and checks the complete stored binding; it cannot create a descriptor or repair an association. Only the exact same-namespace Game Session and World workloads may consume that owner readback, and consumers authenticate Game Design rather than trusting a forwarded digest or JWT service claim. Both resolution and read clients prove the exact same-namespace Game Design workload from the negotiated TLS transport before releasing request metadata or body and independently verify the response; a trusted certificate for another workload or namespace cannot receive the request. @@ -58,6 +60,16 @@ Before reporting `PREPARING`, World verifies that exact descriptor against its r **Implementation and proof status:** This extension is being prepared behind the canonical JOIN/audit checkpoint. Current numeric template/version and owner graph representations remain the separate drift recorded by [Versioning Runtime](../../system-architecture-versioning-runtime.md#implementation-status); this binding is not proof of their completed canonical migration. The separate attestation producer, its wire and durable pair representation, receiver verification, substitution, concurrent exact-retry, immutable readback, fresh/retained isolation and actual PostgreSQL proof remain required. No runtime, catalog or credential activation is authorized. Capability evidence belongs to the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md) and [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md), not this target contract. +### Source-qualified version-state read + +World's canonical Draft writer reads Game Design's current version authority for the exact already-intaken authored source; it must not send World's private tenant key to Game Design or reinterpret a legacy numeric read as that proof. The closed `GetAuthoredWorldVersionState` read carries `schemaVersion=1`, target namespace, a separate canonical non-nil read request UUID, canonical tenant UUID, world slug, exact source operation UUID, expected source evidence digest and positive version ID. Only the exact same-namespace World workload may use this read, before decoding or owner access; it is not an additional allowance for the legacy generic `GetVersionState` internal-service branch. World proves the exact Game Design server before releasing metadata/body and validates the complete closed response. + +Game Design reads the complete persisted source, its actual game-row provenance, and the exact version belonging to that source game from one owner snapshot. The version's private owner tenant key comes only from the proved Game Design source row, never from a World key or numeric equality. The response echoes the complete read context and contains the original closed source receipt, exact version ID, current lifecycle state, positive version-state epoch and derived evidence digest. Missing or contradictory source/version ownership, changed scope/echo/digest, unsupported schema, unknown fields and unavailable owner storage fail closed without mutation. This is a current snapshot read, not a stable mutation outcome: a later read may observe a later version epoch, while the immutable source receipt remains unchanged. + +The version-state evidence digest uses strict UTF-8 decimal byte-length `:` framing and SHA-256, rendered as `sha256:` plus 64 lower-case hexadecimal digits. Its fixed-order segments are `game-design-authored-world-version-state/v1`, canonical decimal schema version, target namespace, read request UUID, canonical tenant UUID, world slug, source operation UUID, verified source evidence digest, canonical positive decimal version ID, exact persisted lifecycle token (for example `DRAFT`, without the protobuf `VERSION_LIFECYCLE_STATE_` prefix) and canonical positive decimal version-state epoch. The complete source receipt is independently validated against its own exhaustive digest before this outer binding is accepted. The digest supplies integrity, not authentication or a publication fence. + +This read does not lock another owner, freeze publication, attest released content or authorize launch/admission. World must take the same local version fence for canonical mutation and publication; the [publication freeze and handoff](./version-control.md#publication-freeze-and-owner-handoff) remains necessary before any Published-content or `PREPARING` claim. Its producer/consumer, migration and negative proof are implementation gates, not implied by this contract. + ### Audited retained Game Session tenant association This is a distinct, one-time retained-data association, not the Account migration manifest or the normal fresh-creation path. Game Design's approved tenant owner must explicitly attest that one retained Game Session tenant key denotes its persisted canonical tenant. Existing source rows on either side, similar selectors or numeric values do not establish that relation. With no such attestation, the association remains absent and denied. Normal new creation and source intake remain automated owner work; this retained-data approval does not introduce a routine creation-time operator step. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index a4deb6347f..c4cfb7d116 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -28,6 +28,8 @@ Current script-patch publication also fails closed before finalization. Game Des ### History and Provenance Across Services +Under [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md), Game Design persists the opaque, non-nil UUID `versionId` separately from its private numeric `version.id`, bound immutably to the exact Version row and its canonical tenant/source-game tuple. Retained versions without an owner-persisted mapping remain unmapped and fail closed; their logical IDs are never derived from numeric keys. + The Game Design Service is the canonical history store for world and entity content even though domain services own the runtime templates: diff --git a/design/architecture/microservices/game-logic-service/runtime-and-data.md b/design/architecture/microservices/game-logic-service/runtime-and-data.md index 268ba9f5ff..375cc8f220 100644 --- a/design/architecture/microservices/game-logic-service/runtime-and-data.md +++ b/design/architecture/microservices/game-logic-service/runtime-and-data.md @@ -6,7 +6,7 @@ This document defines the Game Logic Service runtime model, dependency ownership The sections below define the target-state runtime contract. Current implementation and proof status is: -- The current implementation attests an empty owned-rule manifest and returns synthetic `appliedCommitId = "version:"` because Game Logic does not yet own version-scoped draft rule tables. The empty-manifest digest is intentional and does not represent hidden service state. +- The current full-version digest producer fails closed because Game Logic lacks the owner-local rule-input manifest and provenance needed to attest the selected version. It does not turn missing rule inputs into an empty manifest or synthetic commit identity. The publication binding and participant consequence are recorded in [API Contracts](api-contracts.md); the normal owner manifest and dedicated ability-schema producer remain required implementation work. - Same-type Game Logic takeover behind an existing edge connection is target behavior, but suppression of a client-visible reconnect after an ordinary qualifying Game Logic restart remains implementation or proof debt under ADR 0013. - Target: `SendCommunication` and every other player-delegated gameplay RPC propagate one complete, validated typed `PlayerExecutionContext` from Game Session through Game Logic and onward. Game Logic validates the context against request and owner evidence, never treats caller-supplied identifiers as authority, remains stateless, and owns semantic gameplay outcomes; Game Session owns session, reconnect, and presentation state. This is the ADR 0024 target contract. - Current implementation gap: the live `SendCommunicationRequest` is still a flat schema with tenant/session/character/account, communication/text and target metadata, room, game-instance, speaker, and effect fields plus legacy `session_attestation`; its current proto does not carry typed `playableStateNamespaceId`, `playableStateScope`, region/epoch, pointer, or admitted-bundle fields. Complete typed-context propagation is therefore not current behavior or proof. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 4970896a8d..a682f35fc6 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -7,7 +7,7 @@ This API contract is target-state canonical; implementation coverage is partial - The current World Management gameplay bridge serializes runtime room ids as `R-` and rejects scoped decimal `roomInstanceId` values such as `1021`. That storage-derived encoding is not the canonical target identity defined by the [Identifier Glossary](../../system-architecture-identifier-glossary.md). - The bridge, cross-service callers, examples, and focused proof have not migrated together to the scoped decimal `roomInstanceId` contract. The checked-in proof still exercises the legacy encoding. - The typed `ApplyRoomAmbientStatePatch` contract below is target-state: the current service has no complete handler or durable operation/digest-bound guard, so player-significant ambient mutations remain on the fenced Game Session admission/reconciliation path and are not direct table writes. -- `GetDraftDesignDigest` currently has only shared bearer parsing and no owner/method authorization or exact Game Design publication binding. The current `GetDraftDesignDigestRequest` proto carries only `tenant_id` plus a `oneof` `version_id`/`script_patch_version`; neither the proto nor handler carries or validates the target `publishRequestId`, derived workflow identity, or canonical `requestDigest`, and no wrong-workload, cross-tenant, or exact-replay proof exists. The target exact Game Design workload, tenant/scope/request/workflow/digest context and denial proof are canonical in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity). +- `GetDraftDesignDigest` requires the verified same-namespace Game Design workload peer and validates the complete typed publication-read request/workflow/digest binding before reading owner content. Wrong-workload and changed-binding unit denial proof exists. Its current content resolver still uses numeric tenant/version storage, and this read supplies neither canonical-source-qualified write authorization nor a publication-freeze acknowledgement or terminal result. The target owner-to-owner read contract remains canonical in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity); current capability and proof limits belong in the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). - The current typed `ApplyWorldDesignMutation` owner-write boundary also has no method/workload or tenant authorization beyond shared JWT parsing: its gRPC handler forwards any authenticated bearer to the mutation service, whose current checks cover request shape and Draft state but not caller identity or tenant access. This is separate from the digest-read gap and the legacy REST generation-rule gap; the target authenticated Game Design caller and tenant authorization remain defined by the design-time contract below, and wrong-workload/cross-tenant denial is not implemented or proved. - Required executable migration/proof gate: `./gradlew :world-management-service:test :game-logic-service:test :game-session-service:test :tcp-proxy-service:crossServiceTest`. This gate must update the bridge, callers, examples, and checked-in proof together and pass before the target examples below may be treated as current. This document does not claim that the gate exists or passes. @@ -72,7 +72,7 @@ World Management exposes design-time APIs used by Game Design to write Draft tem ### Publication freeze and terminal handoff (target state) -The publication-freeze operations are target contract surfaces. They are deliberately specified here as the World Management owner contract; the current proto, DTOs, client adapter, persistence schema, handler, and focused proof do not exist. No current caller may infer a freeze, publication, or terminal owner result from a digest, a remote `GetVersionState` read, or a Temporal run identity. +The publication-freeze operations remain unavailable target contract surfaces. The internal owner-lock persistence prerequisite is not an authenticated freeze producer or terminal handoff; the [World implementation tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status) records its current code and proof limits. No current caller may infer a freeze, publication, or terminal owner result from a digest, a remote `GetVersionState` read, or a Temporal run identity. `BeginVersionPublicationFreeze` accepts exactly: @@ -261,7 +261,11 @@ The success response echoes the complete original intake binding and adds World' Retained World rows use a separate owner-approved, audited association operation, following the existing provenance-backed association pattern but binding World's exact retained-row evidence. World verifies and durably reads back that evidence and the one-to-one canonical association. Account's migration manifest, matching numeric keys, selector similarity and absent history are not World ownership proof. Unmapped, ambiguous or contradictory retained rows remain denied. This exceptional retained-data migration is not part of routine fresh intake, and no association is inferred or repaired during a launch retry. -World reserves a fresh private selector durably with its canonical association. Every legacy numeric writer must fail closed rather than take that selector, including a concurrent writer with an older transaction snapshot; existing legacy selectors remain usable but cannot acquire a canonical association through numeric equality. Reservation and intake rollback together, and committed associations, reservations and receipts cannot be rewritten or deleted to make another binding appear valid. This reservation is not permission for a legacy content writer to populate canonical content: the canonical-source-qualified writer and its owner evidence remain separate prerequisites. +World reserves a fresh private selector durably with its canonical association. Every legacy numeric writer must fail closed rather than take that selector, including a concurrent writer with an older transaction snapshot; existing legacy selectors remain usable but cannot acquire a canonical association through numeric equality. That isolation covers inserts, payload-only updates, deletes and attempts to move a canonical-owned row to another tenant key; checking only a changed `tenant_id` column is insufficient. Reservation and intake rollback together, and committed associations, reservations and receipts cannot be rewritten or deleted to make another binding appear valid. This reservation is not permission for a legacy content writer to populate canonical content: the canonical-source-qualified writer and its owner evidence remain separate prerequisites. + +Unqualified whole-table `TRUNCATE` is not a tenant-scoped owner mutation and must be denied on these tenant-bearing content/runtime tables; row-level guards alone do not intercept it. Qualified owner cleanup and separately authorized retained-data migrations keep their existing proof obligations. A reservation's absence from a caller's older transaction snapshot is not permission to erase another tenant's committed state. + +For a canonical Draft mutation, World obtains the [source-qualified Game Design version-state read](../game-design-service/api-contracts.md#source-qualified-version-state-read) for the exact retained source binding and compares it with the complete local intake and tenant association. World resolves its private storage key locally; it never sends that key to Game Design or treats equality with a Game Design source key as ownership. A current Draft read is only a precondition, not a lock or publication acknowledgement. The mutation and publication must still serialize through the same [owner-local version fence](#publication-freeze-and-terminal-handoff-target-state) before Published-content or canonical preparation is admitted. The producer, authenticated receiver, exact local content readback, rollback/concurrent retry and fresh/retained isolation proof must pass before this boundary is used by canonical preparation. Private numeric selectors remain internal. Implementation and proof status is recorded in [World Runtime and Movement](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). 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 ef28e63b16..07ef045c43 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,6 +6,14 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +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. + +The fresh Version identity prerequisite now allocates and reads back a persisted non-nil UUID with the exact canonical tenant and source-game provenance for normal owner repository inserts. V35.1 leaves retained Version rows unchanged and unmapped; the focused PostgreSQL fixture and strict CI cases cover retained denial, exact fresh read/update, tenant/source mismatch, nil identity and immutability. The cumulative seven-module checks, five boot JARs, schema generation and documentation gate passed at `12d6cf5cfab437c0d69583566a6aa0738a644986`, with reused task results disclosed in the PR evidence. All six new PostgreSQL methods skipped locally without Docker. Exact-head [CI37218116041](https://github.com/benhook1013/FireMUD/actions/runs/37218116041) is terminal `FAILURE`: `newVersionIdentityUsesExactRetainedGameSourceProvenance` failed during forward migration, and the raw report was unavailable after later test selectors replaced the files. The other five methods are not individually established by that summary. The corrected workflow captures the complete component XML and HTML immediately, including failures, before later selectors; failed SQL and complete migration execution remain required proof, not guessed fixture or production disposition. The closed numeric descriptor/API representation, full release attestation, and runtime activation remain separate open work; no UUID is inferred for retained rows. + +The owner-local release association candidate now persists and reads back the actual canonical tenant/Version pair from the immutable Game/Version source, rather than dropping that identity at bundle creation or reconstructing it from private keys. V35.2 preserves retained bundle rows and their NULL identities without backfill. Repository saves of existing bundles and all database UPDATEs are denied; the opt-in demo seeder reuses the stored row without rewriting its metadata. Focused unit coverage exercises exact identity readback and substitution/no-mutation rejection. Five PostgreSQL methods cover retained tuple/xmin preservation, exact source persistence, publisher transaction rollback, negative source identity, and immutable metadata; compilation or local Docker-free skips do not establish their execution. The retained Version fixture's schema name was shortened from 70 to 61 bytes to avoid PostgreSQL identifier truncation; that evidence-backed fixture correction still requires exact-head PostgreSQL migration execution, and the earlier uncaptured failing statement is not claimed as proved. This source-identity correction is not full release proof: the dedicated Game Logic rule/ability producer, canonical immutable manifest and actual-byte artifact digests, exact descriptor/release association and World lifecycle consumer remain open. No empty participant or aggregate Automation digest substitutes for those missing owner sources. + +**Source-qualified World version-state prerequisite:** The dedicated, explicitly unregistered `GetAuthoredWorldVersionState` handler and shared closed codec/client bind the exact persisted authored-world source receipt to its source-owned version, current lifecycle and epoch. The producer uses a fresh owner-local read-only `REPEATABLE_READ` snapshot; the receiver authenticates the exact same-namespace World peer before decoding, and the client authenticates Game Design before releasing a request. At exact `cd7751371e999360091e6ed70c99d45acee88d76`, [CI37130036974](https://github.com/benhook1013/FireMUD/actions/runs/37130036974) was terminal `FAILURE`, while independent raw-XML parsing and rehashing verified the focused source/version suites clean, including four PostgreSQL snapshot/concurrency methods, three real producer/repository/transaction/physical-mTLS composition methods and the six version-read unit/socket methods. The composition uses a synthetic authored-source fixture. The earlier `eec587c1db74f4059ddaf060c1ef9fa41486c452` proof had socket tests with a mocked producer; that limitation is superseded by the executed composition evidence. The [Game Design API contract](../../architecture/microservices/game-design-service/api-contracts.md#source-qualified-version-state-read) owns the binding; this read is neither publication-freeze acknowledgement nor release, launch or admission authorization. Automatic delivery, World content writes and the full publication handoff remain open; no runtime path is enabled by this prerequisite. + The normal source-to-launch reconciliation preserves the committed Game Design descriptor under retries with changed template defaults, Game Session's short writable `REQUIRES_NEW` intake transaction with independent committed readback, and the parent's lifecycle, retry and owner-identity guards. Legacy numeric launch entry points still reject with `AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED` before dependencies or mutation. Parent successful run-owned launch, activation, ambiguous-outcome recovery and World descriptor-readback tests therefore cannot establish positive runtime proof on this candidate; their current no-mutation denial assertions are not equivalent coverage. Those positive obligations remain open under the owning launch contract. World intake moves mechanically from V23 to V23.1 after the parent's V23 hold, with original SQL bytes preserved; applied migration inventory/checksums and retained readback remain rollout gates. The accepted complete resolved launch binding is the unchanged closed descriptor/v1 plus a separately authenticated exact release attestation, not extra fields silently added to the descriptor. The normal Game Design producer, canonical version/content identity association, complete participant/ability/artifact evidence, World atomic retention/readback of both components and current commit authorization remain implementation/proof prerequisites. Source-only or mocked transport proof does not complete those handoffs, and no runtime activation is authorized. diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index f6e00d0a63..52be2cd1bc 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for world runtime and movement. C The current normal reconciliation preserves the incoming V23 initial-admission hold and mechanically places fresh-source intake at V23.1 with byte-identical SQL. The original intake SHA-256 remains `a7ac30d48da1911eb3395716e827ac0f0ec612970d4f40b5a27530d634430445`; its PostgreSQL fixture now explicitly requires the hold-before-intake applied script order. This is an unapplied candidate, not authority to rename applied migrations or invoke repair/out-of-order execution. Exact environment history/checksums and retained-row readback remain rollout gates; the historical V23 source proof below does not execute the newly composed sequence. +The owner-local source-qualified receipt lookup is implemented as a read-only prerequisite and is not yet called by the lifecycle path. Its four new PostgreSQL cases are required by the focused suite selector but remain unexecuted. The earlier eight-case intake proof and subsequent V24 guard proof predate the composed V23 hold → V23.1 intake → V24 sequence and do not prove the four lookup cases; the V24 fixture now seeds after V23.1 and applies V24 explicitly. No activation or source-qualified lifecycle composition is claimed. + **Canonical launch prerequisite:** Current World design/materialization rows and `PrepareWorldInstance` still use World's private numeric tenant key. V23 and the explicitly unwired owner-local fresh-source intake service/repository persist complete authenticated Game Design `NEW_GAME_ROW` evidence, a private World tenant association, numeric-key reservation and immutable intake receipt together, with exact independent readback. Legacy numeric writes cannot take a reserved canonical selector; existing legacy keys are reserved without inventing UUID associations. Exact [CI37111727823](https://github.com/benhook1013/FireMUD/actions/runs/37111727823) at `73ab357d694618a56c65129394fd324b38ad652e` proves all eight intake PostgreSQL cases and nine Game Design source-read socket cases executed cleanly without skips. Independent raw-XML verification confirms the reservation rejection, SQL state `23514`, unchanged legacy row and no-region assertions. That prior checkpoint does not prove the newer World receiver. The newer transport is explicitly unregistered: closed shared codec/client, exact Game Design peer guard before decoding or owner access, exact namespace enforcement, and non-mutating committed-receipt readback. The client verifies World's exact workload before releasing requests, not merely before accepting replies. Seven physical socket cases execute cleanly locally with a mocked owner, including wrong-server intake/read rejection with no owner interaction. The full Core/Account/World gate, both affected boot JARs, formatting, static analysis, coverage and documentation checks pass; Core208 and World146 unit cases are clean. All eighteen World integration nodes compile but skip locally without Docker, including three new real World PostgreSQL-through-socket composition cases for committed readback, lost acknowledgement/exact retry and denial without mutation. Their upstream Game Design source answer is synthetic; even successful execution would not prove its producer or automatic delivery. CI strictly requires and captures both new socket suites. @@ -16,7 +18,17 @@ The Game Design source/descriptor consumers now use the same pre-send exact-serv Exact `00285d5a9474a01970293d5a225ad0c63ce1a611` [CI37118817841](https://github.com/benhook1013/FireMUD/actions/runs/37118817841) independently proves all seven physical socket and eight owner-local PostgreSQL cases executed cleanly, with zero skips. All three newer PostgreSQL/socket methods executed but failed during source-fixture construction: `source-key-` plus a full random UUID exceeded Game Design's unchanged 36-code-point key bound. The test-only correction uses `src-` plus an independently random hyphenless UUID, exactly 36 characters; it neither derives a tenant association nor changes the owner validator. Corrected database/socket execution remains required, rather than claiming the failed setup exercised its socket or owner assertions. The aggregate run is red on this fixture, Account's terminal-diagnostic constraint and concrete other-owner failures. Live deployment and all activation gates remain unproved/denied. -Exact corrected `202c58f1605018f6bf51277ac4f431497eca9a34` [CI37121026340](https://github.com/benhook1013/FireMUD/actions/runs/37121026340) now proves all three World PostgreSQL/socket methods, all eight owner-local PostgreSQL methods and all seven World socket methods executed cleanly without skips. Root independently parsed and rehashed their raw XML. The three composed methods use real World persistence, service, transaction manager, handler and transport but synthetic upstream Game Design source evidence; they are not automatic creation/delivery or live deployment. Aggregate CI remains red on concrete other-owner checks and Game Session's20-minute packaging timeout; none is relabeled flaky or presumed fixed. This run precedes the subsequent Game Design client pre-send guard correction above, which has local socket proof and still needs its own corrected-state runner. +Exact corrected `ab0b055a5c25b418cf5b29ab127e2f806118fea6` [CI37122999109](https://github.com/benhook1013/FireMUD/actions/runs/37122999109) proves all three World PostgreSQL/socket methods, all eight owner-local PostgreSQL methods and all seven World socket methods executed cleanly without skips, plus the corrected Game Design pre-send guard cases. Root independently parsed and rehashed nine raw XML suites totaling63 clean executions. The three composed World methods use real local persistence, service, transaction manager, handler and transport but synthetic upstream Game Design source evidence; they are not automatic creation/delivery or live deployment. Broader Game Session checks and packaging succeeded under the explicit30-minute budget; combined coverage verification skipped. Aggregate CI remains red on concrete Ruff, dev-demo validator, Automation formatting and unchanged Game Design duplicate-fixture failures; none is relabeled flaky or presumed fixed. + +**Source-qualified content prerequisite:** The dedicated, explicitly unregistered Game Design current-version read validates the complete persisted source, exact source-owned version and lifecycle/epoch in one fresh owner snapshot; its closed World client authenticates the exact server before sending a request. At exact `cd7751371e999360091e6ed70c99d45acee88d76`, [CI37130036974](https://github.com/benhook1013/FireMUD/actions/runs/37130036974) was terminal `FAILURE`, while independent raw-XML parsing and rehashing verified all 11 focused suites clean: 75 executed, 75 passed, zero skips/errors/failures. This includes four source/snapshot PostgreSQL methods and the dedicated producer/handler/socket cases. The earlier `eec587c1db74f4059ddaf060c1ef9fa41486c452` checkpoint had one World fixture-setup failure; that historical failure is corrected and is not current proof status. Exact source-read and owner/client composition is now executed, but the authored-source fixture is synthetic. See the [Game Design owner contract](../../architecture/microservices/game-design-service/api-contracts.md#source-qualified-version-state-read); this read does not supply publication-freeze acknowledgement or make canonical content writable. + +V24 closes V23's legacy mutation bypasses: all16 tenant-bearing tables reject canonical reserved-key inserts, payload-only updates, movement away from the canonical key, deletes and unqualified table truncation. Legacy row updates/deletes remain available; the immutable reservation is not removed by deletion. Its PostgreSQL case, including all16 table guards and truncation assertions, executed cleanly in CI37130036974. The fixture uses synthetic retained canonical rows to test isolation, not a completed canonical writer or retained migration. Local Docker unavailability still skips the 61 Game Design and 25 World PostgreSQL tests; those are local skips, not skips in the runner evidence. The authenticated source-qualified writer, transaction-bound mutation authorization and shared mutation/publication fence remain required before canonical content or lifecycle preparation is admitted. + +An earlier runner attempt executed all nine World intake cases: eight passed, while the all-table case failed during setup because its isolated Flyway configuration omitted the common-saga `serviceSchema` placeholder. The fixture correction is now exercised: all nine World intake PostgreSQL cases passed in CI37130036974, including the complete16-table guard and truncation assertions. The same exact-head run passed World socket7, World PostgreSQL/socket3, Game Design source socket9 and descriptor socket13/PostgreSQL7. Aggregate CI remains `FAILURE` on concrete shared Ruff, dev-demo validator, Automation formatting and unchanged Game Design `EntityDigestBaselineMigrationIntegrationTest` duplicate-key fixture failures. Those failures are not relabeled flaky or resolved. + +V25 adds the internal shared tenant/version owner row and immutable freeze attempts. Ordinary locks and freeze claims use that same row; checkpoints are captured after lock acquisition, while exact retries return the stored fence/checkpoint without recapturing server-derived output. Multiple exact source receipts may use the same global tenant/version row. The full publication-attempt digest remains distinct from the separate publication-read binding used for workflow identity. Four evidence unit methods passed locally; all six PostgreSQL rollback, concurrency, lock-order and immutable-readback methods executed cleanly in CI37130036974. The freeze-checkpoint fixture is synthetic: it does not exercise a real content writer, complete-commit/digest producer, authenticated freeze acknowledgement, terminal producer/handoff or activation. The store remains unconnected to a public handler or RPC route. Canonical payload guards and runtime denial gates remain unchanged. + +The composed-read proof now executes at exact `cd7751371e999360091e6ed70c99d45acee88d76`: CI37130036974 passed the three real-producer/database/physical-mTLS version-read methods, four source/snapshot PostgreSQL methods, six version-read unit/socket methods, and six V25 freeze persistence methods with no skips. The composition uses persisted repositories, transaction manager, producer, handler, exact-peer interceptor and client, with a synthetic authored-source fixture. All 61 Game Design and 25 World PostgreSQL tests skip locally because Docker is unavailable; the exact runner evidence above establishes execution of the named focused methods, not a clean broad integration suite. This proof does not establish automatic delivery, a canonical World content writer, public handler registration, publication handoff or runtime activation. Aggregate CI remains failed on the concrete unrelated checks recorded above. Schema generation has bounded indexed tokens and an explicit complete-binding unique constraint; production uniqueness and immutability are not suppressed. The automatic normal Game Design registration/delivery producer, canonical-source-qualified content writer, exact content/descriptor/release readback, separate audited retained-World association and canonical lifecycle composition remain required. The [World API contract](../../architecture/microservices/world-management-service/api-contracts.md#authenticated-authored-content-intake-and-tenant-association) owns this boundary. Numeric similarity, selectors and Account's migration manifest are not substitutes, and no runtime activation is authorized. The prior World full CI job passed while aggregate CI failed on identified Game Design fixture, Automation formatting and shared-tooling checks; no aggregate-green claim follows from focused proof. 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/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/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/protos/game-design/v1/game_design_service.proto b/protos/game-design/v1/game_design_service.proto index 67079e8d13..c7e5d50ded 100644 --- a/protos/game-design/v1/game_design_service.proto +++ b/protos/game-design/v1/game_design_service.proto @@ -31,6 +31,9 @@ service GameDesignService { rpc GetPublishedReleaseBundle(GetPublishedReleaseBundleRequest) returns (GetPublishedReleaseBundleResponse); rpc GetVersionState(GetVersionStateRequest) returns (GetVersionStateResponse); + // Exact current version state for one already-registered authored-world source. + rpc GetAuthoredWorldVersionState(GetAuthoredWorldVersionStateRequest) + returns (GetAuthoredWorldVersionStateResponse); rpc CompareAndSetVersionState(CompareAndSetVersionStateRequest) returns (CompareAndSetVersionStateResponse); rpc ResolveLaunchDescriptor(ResolveLaunchDescriptorRequest) @@ -323,6 +326,53 @@ message GetVersionStateResponse { shared.v1.ErrorDetail error = 2; } +message GetAuthoredWorldVersionStateRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + string canonical_tenant_id = 4; + string world_slug = 5; + string source_operation_id = 6; + string expected_source_evidence_digest = 7; + int64 version_id = 8; +} + +message GetAuthoredWorldVersionStateResponse { + AuthoredWorldVersionStateEvidence evidence = 1; +} + +message AuthoredWorldVersionStateEvidence { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + string canonical_tenant_id = 4; + string world_slug = 5; + string source_operation_id = 6; + string expected_source_evidence_digest = 7; + int64 version_id = 8; + AuthoredWorldSourceReceipt source_evidence = 9; + VersionLifecycleState version_state = 10; + int64 version_state_epoch = 11; + string evidence_digest = 12; +} + +// Complete immutable registration receipt, without another RPC's transient read request ID. +message AuthoredWorldSourceReceipt { + int32 schema_version = 1; + string target_namespace = 2; + string registration_request_id = 3; + string operation_id = 4; + string request_digest = 5; + string canonical_tenant_id = 6; + string tenant_slug = 7; + string world_slug = 8; + string world_display_name = 9; + int64 source_game_row_id = 10; + string source_game_tenant_key = 11; + string provenance_kind = 12; + string evidence_digest = 13; +} + message CompareAndSetVersionStateRequest { string tenant_id = 1; int64 version_id = 2; @@ -510,6 +560,8 @@ message PublishedReleaseBundle { string workflow_status = 14; string workflow_family = 15; repeated string command_definitions = 16; + string canonical_tenant_id = 18; + string canonical_version_id = 19; } message LaunchDescriptor { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateClient.java new file mode 100644 index 0000000000..dbeb0b0b1f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateClient.java @@ -0,0 +1,157 @@ +package net.firedevops.firemud.common.gamedesign; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; + +/** Explicit mTLS client for exact source-qualified current Game Design version-state reads. */ +public final class AuthoredWorldVersionStateClient + extends AbstractReloadingBlockingGrpcClient< + GameDesignServiceGrpc.GameDesignServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AuthoredWorldVersionStateClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AuthoredWorldVersionStateClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when an owning service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Authored-world version-state client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException( + "Authored-world version-state client did not initialize a gRPC stub"); + } + initialized = true; + } + + /** Reads current state for the exact already-intaken source and source-owned version. */ + public AuthoredWorldVersionStateEvidence read(AuthoredWorldVersionStateEvidence.Request request) { + Objects.requireNonNull(request, "request"); + requireNamespace(request.targetNamespace()); + GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub = requireStub(); + var response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .getAuthoredWorldVersionState(AuthoredWorldVersionStateGrpcCodec.toRequest(request)); + try { + return AuthoredWorldVersionStateGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design returned invalid authored-world version-state evidence", exception); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected GameDesignServiceGrpc.GameDesignServiceBlockingStub buildStub(ManagedChannel channel) { + String expectedGameDesignPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + return GameDesignServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedGameDesignPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedGameDesignPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private GameDesignServiceGrpc.GameDesignServiceBlockingStub requireStub() { + GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Authored-world version-state client is not initialized and available"); + } + return currentStub; + } + + private void requireNamespace(String targetNamespace) { + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "Version-state request must use the configured workload namespace"); + } + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null) { + throw new IllegalArgumentException("gRPC mTLS configuration is required"); + } + if (tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Version-state reads require workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Version-state reads require file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Version-state reads require file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException exception) { + throw new IllegalArgumentException( + "Version-state " + label + " must be a readable file-backed path", exception); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Version-state " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateEvidence.java new file mode 100644 index 0000000000..f7b5632fc4 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateEvidence.java @@ -0,0 +1,195 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; + +/** Closed, source-qualified current Game Design version-state evidence for World Management. */ +public record AuthoredWorldVersionStateEvidence( + Request request, + AuthoredWorldSourceEvidence sourceEvidence, + VersionLifecycleState versionState, + long versionStateEpoch, + String evidenceDigest) { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final String EVIDENCE_DOMAIN = "game-design-authored-world-version-state/v1"; + + /** The exact selector and caller-owned read identity for one current version-state read. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest, + long versionId) { + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported authored-world version-state schema"); + } + Objects.requireNonNull(readRequestId, "readRequestId"); + Objects.requireNonNull(sourceOperationId, "sourceOperationId"); + if (NIL_UUID.equals(readRequestId) || NIL_UUID.equals(sourceOperationId)) { + throw new IllegalArgumentException("Read and source operation IDs must be non-nil UUIDs"); + } + if (readRequestId.equals(sourceOperationId)) { + throw new IllegalArgumentException("readRequestId must be separate from sourceOperationId"); + } + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + if (expectedSourceEvidenceDigest == null + || !SHA256.matcher(expectedSourceEvidenceDigest).matches()) { + throw new IllegalArgumentException( + "Expected source evidence digest must be canonical SHA-256 text"); + } + if (versionId <= 0) { + throw new IllegalArgumentException("versionId must be positive"); + } + } + } + + public AuthoredWorldVersionStateEvidence { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(sourceEvidence, "sourceEvidence"); + requireLifecycleState(versionState); + if (versionStateEpoch <= 0) { + throw new IllegalArgumentException("versionStateEpoch must be positive"); + } + if (!request.targetNamespace().equals(sourceEvidence.targetNamespace()) + || !request.canonicalTenantId().equals(sourceEvidence.canonicalTenantId()) + || !request.worldSlug().equals(sourceEvidence.worldSlug()) + || !request.sourceOperationId().equals(sourceEvidence.operationId()) + || !request.expectedSourceEvidenceDigest().equals(sourceEvidence.evidenceDigest())) { + throw new IllegalArgumentException( + "Complete authored-world source receipt does not match the exact version-state request"); + } + if (request.readRequestId().equals(sourceEvidence.registrationRequestId())) { + throw new IllegalArgumentException( + "readRequestId must be separate from the original source registration request"); + } + if (evidenceDigest == null || !SHA256.matcher(evidenceDigest).matches()) { + throw new IllegalArgumentException("evidenceDigest must be canonical SHA-256 text"); + } + if (!evidenceDigest.equals(evidenceDigest(request, versionState, versionStateEpoch))) { + throw new IllegalArgumentException( + "Version-state evidence digest does not match the exact current-state tuple"); + } + } + + public static AuthoredWorldVersionStateEvidence create( + Request request, + AuthoredWorldSourceEvidence sourceEvidence, + VersionLifecycleState versionState, + long versionStateEpoch) { + Objects.requireNonNull(request, "request"); + requireLifecycleState(versionState); + return new AuthoredWorldVersionStateEvidence( + request, + sourceEvidence, + versionState, + versionStateEpoch, + evidenceDigest(request, versionState, versionStateEpoch)); + } + + /** Recomputes the complete outer binding after construction or wire decoding. */ + public void requireValid() { + if (!evidenceDigest.equals(evidenceDigest(request, versionState, versionStateEpoch))) { + throw new IllegalArgumentException("Version-state evidence digest is invalid"); + } + } + + public static String evidenceDigest( + Request request, VersionLifecycleState versionState, long versionStateEpoch) { + Objects.requireNonNull(request, "request"); + requireLifecycleState(versionState); + if (versionStateEpoch <= 0) { + throw new IllegalArgumentException("versionStateEpoch must be positive"); + } + return sha256(evidencePreimage(request, versionState, versionStateEpoch)); + } + + /** Fixed-order UTF-8 length-framed preimage owned by the Game Design API contract. */ + public static byte[] evidencePreimage( + Request request, VersionLifecycleState versionState, long versionStateEpoch) { + Objects.requireNonNull(request, "request"); + requireLifecycleState(versionState); + if (versionStateEpoch <= 0) { + throw new IllegalArgumentException("versionStateEpoch must be positive"); + } + return frame( + EVIDENCE_DOMAIN, + Integer.toString(request.schemaVersion()), + request.targetNamespace(), + request.readRequestId().toString(), + request.canonicalTenantId().toString(), + request.worldSlug(), + request.sourceOperationId().toString(), + request.expectedSourceEvidenceDigest(), + Long.toString(request.versionId()), + lifecycleStateName(versionState), + Long.toString(versionStateEpoch)); + } + + private static String lifecycleStateName(VersionLifecycleState value) { + return value.name().substring("VERSION_LIFECYCLE_STATE_".length()); + } + + private static byte[] frame(String... segments) { + ByteArrayOutputStream preimage = new ByteArrayOutputStream(); + for (String segment : segments) { + byte[] bytes = strictUtf8(segment); + preimage.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.UTF_8)); + preimage.write(':'); + preimage.writeBytes(bytes); + } + return preimage.toByteArray(); + } + + private static byte[] strictUtf8(String value) { + Objects.requireNonNull(value, "digest segment"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Digest segments must contain valid Unicode", exception); + } + } + + private static String sha256(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void requireLifecycleState(VersionLifecycleState value) { + if (value == null + || value == VersionLifecycleState.VERSION_LIFECYCLE_STATE_UNSPECIFIED + || value == VersionLifecycleState.UNRECOGNIZED) { + throw new IllegalArgumentException("A recognized version lifecycle state is required"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateGrpcCodec.java new file mode 100644 index 0000000000..489cb77e44 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateGrpcCodec.java @@ -0,0 +1,189 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.AuthoredWorldSourceReceipt; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateResponse; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; + +/** Closed request mapping and exact response validation for authored-world version-state reads. */ +public final class AuthoredWorldVersionStateGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private AuthoredWorldVersionStateGrpcCodec() {} + + /** Encodes exactly the schema-v1 source-qualified read tuple. */ + public static GetAuthoredWorldVersionStateRequest toRequest( + AuthoredWorldVersionStateEvidence.Request request) { + Objects.requireNonNull(request, "request"); + return GetAuthoredWorldVersionStateRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setSourceOperationId(request.sourceOperationId().toString()) + .setExpectedSourceEvidenceDigest(request.expectedSourceEvidenceDigest()) + .setVersionId(request.versionId()) + .build(); + } + + /** Decodes a strict request after the authenticated handler has checked its peer. */ + public static AuthoredWorldVersionStateEvidence.Request fromRequest( + GetAuthoredWorldVersionStateRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "GetAuthoredWorldVersionStateRequest"); + try { + return new AuthoredWorldVersionStateEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + parseCanonicalNonNilUuid(request.getReadRequestId(), "readRequestId"), + parseCanonicalNonNilUuid(request.getCanonicalTenantId(), "canonicalTenantId"), + request.getWorldSlug(), + parseCanonicalNonNilUuid(request.getSourceOperationId(), "sourceOperationId"), + request.getExpectedSourceEvidenceDigest(), + request.getVersionId()); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + "Authored-world version-state request is invalid", exception); + } + } + + /** Encodes the complete validated source receipt and exact current-state evidence. */ + public static GetAuthoredWorldVersionStateResponse toResponse( + net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + evidence.requireValid(); + AuthoredWorldSourceEvidence source = evidence.sourceEvidence(); + var request = evidence.request(); + AuthoredWorldSourceReceipt sourceReceipt = + AuthoredWorldSourceReceipt.newBuilder() + .setSchemaVersion(source.schemaVersion()) + .setTargetNamespace(source.targetNamespace()) + .setRegistrationRequestId(source.registrationRequestId().toString()) + .setOperationId(source.operationId().toString()) + .setRequestDigest(source.requestDigest()) + .setCanonicalTenantId(source.canonicalTenantId().toString()) + .setTenantSlug(source.tenantSlug()) + .setWorldSlug(source.worldSlug()) + .setWorldDisplayName(source.worldDisplayName()) + .setSourceGameRowId(source.sourceGameRowId()) + .setSourceGameTenantKey(source.sourceGameTenantKey()) + .setProvenanceKind(source.provenanceKind()) + .setEvidenceDigest(source.evidenceDigest()) + .build(); + return GetAuthoredWorldVersionStateResponse.newBuilder() + .setEvidence( + net.firedevops.firemud.gamedesign.v1.AuthoredWorldVersionStateEvidence.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setSourceOperationId(request.sourceOperationId().toString()) + .setExpectedSourceEvidenceDigest(request.expectedSourceEvidenceDigest()) + .setVersionId(request.versionId()) + .setSourceEvidence(sourceReceipt) + .setVersionState(evidence.versionState()) + .setVersionStateEpoch(evidence.versionStateEpoch()) + .setEvidenceDigest(evidence.evidenceDigest())) + .build(); + } + + /** Validates every response carrier and binds every echo to the exact read request. */ + public static net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence + fromResponse( + AuthoredWorldVersionStateEvidence.Request request, + GetAuthoredWorldVersionStateResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "GetAuthoredWorldVersionStateResponse"); + if (!response.hasEvidence()) { + throw new IllegalArgumentException("Version-state response has no evidence"); + } + var wireEvidence = response.getEvidence(); + requireNoUnknownFields(wireEvidence, "AuthoredWorldVersionStateEvidence"); + if (!wireEvidence.hasSourceEvidence()) { + throw new IllegalArgumentException("Version-state evidence has no complete source receipt"); + } + AuthoredWorldSourceReceipt wireSource = wireEvidence.getSourceEvidence(); + requireNoUnknownFields(wireSource, "AuthoredWorldSourceReceipt"); + + net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence evidence; + try { + var echoedRequest = + new AuthoredWorldVersionStateEvidence.Request( + wireEvidence.getSchemaVersion(), + wireEvidence.getTargetNamespace(), + parseCanonicalNonNilUuid(wireEvidence.getReadRequestId(), "readRequestId"), + parseCanonicalNonNilUuid(wireEvidence.getCanonicalTenantId(), "canonicalTenantId"), + wireEvidence.getWorldSlug(), + parseCanonicalNonNilUuid(wireEvidence.getSourceOperationId(), "sourceOperationId"), + wireEvidence.getExpectedSourceEvidenceDigest(), + wireEvidence.getVersionId()); + if (!request.equals(echoedRequest)) { + throw new IllegalArgumentException( + "Version-state response does not echo the exact read request"); + } + AuthoredWorldSourceEvidence sourceEvidence = + new AuthoredWorldSourceEvidence( + wireSource.getSchemaVersion(), + wireSource.getTargetNamespace(), + parseCanonicalNonNilUuid( + wireSource.getRegistrationRequestId(), "registrationRequestId"), + parseCanonicalNonNilUuid(wireSource.getOperationId(), "source operationId"), + wireSource.getRequestDigest(), + parseCanonicalNonNilUuid( + wireSource.getCanonicalTenantId(), "source canonicalTenantId"), + wireSource.getTenantSlug(), + wireSource.getWorldSlug(), + wireSource.getWorldDisplayName(), + wireSource.getSourceGameRowId(), + wireSource.getSourceGameTenantKey(), + wireSource.getProvenanceKind(), + wireSource.getEvidenceDigest()); + VersionLifecycleState versionState = + VersionLifecycleState.forNumber(wireEvidence.getVersionStateValue()); + if (versionState == null) { + throw new IllegalArgumentException("Version-state enum value is unsupported"); + } + evidence = + new net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence( + echoedRequest, + sourceEvidence, + versionState, + wireEvidence.getVersionStateEpoch(), + wireEvidence.getEvidenceDigest()); + evidence.requireValid(); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + "Game Design authored-world version-state response is invalid", exception); + } + return evidence; + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required", exception); + } + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); + } + return parsed; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateClientTest.java new file mode 100644 index 0000000000..fb62cfed6a --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateClientTest.java @@ -0,0 +1,138 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class AuthoredWorldVersionStateClientTest { + private static final String NAMESPACE = "test"; + private static final UUID READ_REQUEST_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + + @Test + void rejectsPlaintextClasspathAndUnreadableTlsBeforeChannelCreation(@TempDir Path directory) + throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + + CommonGrpcClientProperties plaintext = fileBackedMtls(directory); + plaintext.setPlaintext(true); + assertThatThrownBy(() -> newClient(plaintext, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + assertThatThrownBy(() -> newClient(new CommonGrpcClientProperties(), channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties classpath = fileBackedMtls(directory); + classpath.setPrivateKey("classpath:certs/client.key"); + assertThatThrownBy(() -> newClient(classpath, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties missingFiles = new CommonGrpcClientProperties(); + missingFiles.setCertChain(directory.resolve("missing-client.crt").toString()); + missingFiles.setPrivateKey(directory.resolve("missing-client.key").toString()); + missingFiles.setCaCert(directory.resolve("missing-ca.crt").toString()); + assertThatThrownBy(() -> newClient(missingFiles, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("existing readable file"); + + verifyNoInteractions(channelFactory); + } + + @Test + void requiresExplicitInitializationAndRejectsOtherNamespaces(@TempDir Path directory) + throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + AuthoredWorldVersionStateClient client = newClient(fileBackedMtls(directory), channelFactory); + try { + assertThatThrownBy(() -> client.read(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy(() -> client.read(request("other"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + verifyNoInteractions(channelFactory); + } finally { + client.close(); + } + } + + @Test + void initializesOnlyConfiguredTargetFromFileBackedTls(@TempDir Path directory) throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("game-design.internal:6565"); + CommonGrpcClientProperties tls = fileBackedMtls(directory); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true))) + .thenReturn(channel); + AuthoredWorldVersionStateClient client = + new AuthoredWorldVersionStateClient(endpoints, tls, channelFactory, NAMESPACE); + + try { + client.init(); + verify(channelFactory) + .buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + } finally { + client.close(); + } + } + + private static AuthoredWorldVersionStateClient newClient( + CommonGrpcClientProperties tls, GrpcChannelFactory channelFactory) { + return new AuthoredWorldVersionStateClient( + new ServiceEndpointsProperties(), tls, channelFactory, NAMESPACE); + } + + private static CommonGrpcClientProperties fileBackedMtls(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private key").toString()); + tls.setCaCert( + Files.writeString(directory.resolve("server-ca.crt"), "CA certificate").toString()); + return tls; + } + + private static AuthoredWorldVersionStateEvidence.Request request() { + return request(NAMESPACE); + } + + private static AuthoredWorldVersionStateEvidence.Request request(String namespace) { + return new AuthoredWorldVersionStateEvidence.Request( + 1, + namespace, + READ_REQUEST_ID, + TENANT_ID, + "cafe-coast", + SOURCE_OPERATION_ID, + "sha256:" + "a".repeat(64), + 19L); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateEvidenceTest.java new file mode 100644 index 0000000000..1d1d58bb89 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateEvidenceTest.java @@ -0,0 +1,228 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import org.junit.jupiter.api.Test; + +class AuthoredWorldVersionStateEvidenceTest { + private static final UUID READ_REQUEST_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID REGISTRATION_REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final String SOURCE_DIGEST = "sha256:" + "a".repeat(64); + + @Test + void evidenceDigestMatchesFixedLengthFramedVector() { + var request = independentVectorRequest(); + var evidence = + AuthoredWorldVersionStateEvidence.create( + request, + independentVectorSource(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 9_223_372_036_854_775_804L); + + assertThat(evidence.evidenceDigest()) + .isEqualTo("sha256:b17f213002a2ee26d4ccd7aeaf33b50e36ef7cc9d59684913d7916844fde14bd"); + assertThat(evidence.sourceEvidence().requestDigest()) + .isEqualTo("sha256:c8853aa8d2fbdf1bc7905c80d931bdedf32b16c89e49a2c08e821a039b175e23"); + assertThat(evidence.sourceEvidence().evidenceDigest()) + .isEqualTo("sha256:75961752d010261b637ece6ce33eeb714ea032986836bf118397473cc8a2895b"); + } + + @Test + void changedRequestStateAndEpochChangeTheOuterDigest() { + var original = request("cafe-coast", 19L); + String originalDigest = + AuthoredWorldVersionStateEvidence.evidenceDigest( + original, VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, 7L); + + assertThat( + AuthoredWorldVersionStateEvidence.evidenceDigest( + request("cafe-cliff", 19L), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 7L)) + .isNotEqualTo(originalDigest); + assertThat( + AuthoredWorldVersionStateEvidence.evidenceDigest( + request("cafe-coast", 20L), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 7L)) + .isNotEqualTo(originalDigest); + assertThat( + AuthoredWorldVersionStateEvidence.evidenceDigest( + original, VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, 7L)) + .isNotEqualTo(originalDigest); + assertThat( + AuthoredWorldVersionStateEvidence.evidenceDigest( + original, VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, 8L)) + .isNotEqualTo(originalDigest); + } + + @Test + void completeUnicodeSourceReceiptUsesItsIndependentCanonicalDigest() { + AuthoredWorldSourceEvidence source = sourceEvidence("Café 🐉"); + + assertThat(source.worldDisplayName()).isEqualTo("Café 🐉"); + assertThat(source.requestDigest()) + .isEqualTo("sha256:c40306b291f9cb7dfbdb0c78520bd71cb795883a4e1a66feb8588222566542fd"); + assertThat(source.evidenceDigest()) + .isEqualTo("sha256:c1e76186517dbcefaa2ac5b3f4903b324cab7f6c8fdc14b29b81f3d664cf3a82"); + } + + @Test + void rejectsInvalidCountersStateAndSourceEchoes() { + assertThatThrownBy(() -> request("cafe-coast", 0L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("versionId"); + assertThatThrownBy( + () -> + AuthoredWorldVersionStateEvidence.evidenceDigest( + request("cafe-coast", 19L), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_UNSPECIFIED, + 7L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("lifecycle state"); + assertThatThrownBy( + () -> + AuthoredWorldVersionStateEvidence.create( + request("cafe-coast", 19L), + sourceEvidence("Café 🐉"), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 0L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("versionStateEpoch"); + assertThatThrownBy( + () -> + AuthoredWorldVersionStateEvidence.create( + request("other-world", 19L), + sourceEvidence("Café 🐉"), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 7L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("source receipt"); + AuthoredWorldSourceEvidence source = sourceEvidence("Café 🐉"); + AuthoredWorldVersionStateEvidence.Request reusedRegistrationIdentity = + new AuthoredWorldVersionStateEvidence.Request( + 1, + "test", + REGISTRATION_REQUEST_ID, + TENANT_ID, + "cafe-coast", + SOURCE_OPERATION_ID, + source.evidenceDigest(), + 19L); + assertThatThrownBy( + () -> + AuthoredWorldVersionStateEvidence.create( + reusedRegistrationIdentity, + source, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 7L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("original source registration request"); + } + + private static AuthoredWorldVersionStateEvidence.Request request( + String worldSlug, long versionId) { + return new AuthoredWorldVersionStateEvidence.Request( + 1, + "test", + READ_REQUEST_ID, + TENANT_ID, + worldSlug, + SOURCE_OPERATION_ID, + SOURCE_DIGEST, + versionId); + } + + private static AuthoredWorldSourceEvidence sourceEvidence(String displayName) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + "test", REGISTRATION_REQUEST_ID, TENANT_ID, "tenant-one", "cafe-coast", displayName); + return new AuthoredWorldSourceEvidence( + 1, + "test", + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + "tenant-one", + "cafe-coast", + displayName, + 42L, + "game-owner-tenant", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + "test", + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + "tenant-one", + "cafe-coast", + displayName, + 42L, + "game-owner-tenant", + "NEW_GAME_ROW")); + } + + private static AuthoredWorldVersionStateEvidence.Request independentVectorRequest() { + return new AuthoredWorldVersionStateEvidence.Request( + 1, + "firemud", + uuid("33333333-3333-4333-8333-333333333333"), + uuid("11111111-1111-4111-8111-111111111111"), + "violet-wilds", + uuid("22222222-2222-4222-8222-222222222222"), + "sha256:75961752d010261b637ece6ce33eeb714ea032986836bf118397473cc8a2895b", + 9_223_372_036_854_775_805L); + } + + private static AuthoredWorldSourceEvidence independentVectorSource() { + UUID canonicalTenantId = uuid("11111111-1111-4111-8111-111111111111"); + UUID registrationRequestId = uuid("44444444-4444-4444-8444-444444444444"); + UUID sourceOperationId = uuid("22222222-2222-4222-8222-222222222222"); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + "firemud", + registrationRequestId, + canonicalTenantId, + "corpus-demo", + "violet-wilds", + "Café 🐉"); + return new AuthoredWorldSourceEvidence( + 1, + "firemud", + registrationRequestId, + sourceOperationId, + requestDigest, + canonicalTenantId, + "corpus-demo", + "violet-wilds", + "Café 🐉", + 9_223_372_036_854_775_806L, + "source-owner-key", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + "firemud", + registrationRequestId, + sourceOperationId, + requestDigest, + canonicalTenantId, + "corpus-demo", + "violet-wilds", + "Café 🐉", + 9_223_372_036_854_775_806L, + "source-owner-key", + "NEW_GAME_ROW")); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateGrpcCodecTest.java new file mode 100644 index 0000000000..f0bbde988b --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateGrpcCodecTest.java @@ -0,0 +1,222 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateResponse; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import org.junit.jupiter.api.Test; + +class AuthoredWorldVersionStateGrpcCodecTest { + private static final UUID READ_REQUEST_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID REGISTRATION_REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + + @Test + void requestAndCompleteEvidenceRoundTrip() { + var request = request(); + var wireRequest = AuthoredWorldVersionStateGrpcCodec.toRequest(request); + var decodedRequest = AuthoredWorldVersionStateGrpcCodec.fromRequest(wireRequest); + var evidence = evidence(request); + var response = AuthoredWorldVersionStateGrpcCodec.toResponse(evidence); + + assertThat(decodedRequest).isEqualTo(request); + assertThat(AuthoredWorldVersionStateGrpcCodec.fromResponse(request, response)) + .isEqualTo(evidence); + } + + @Test + void requestRejectsUnknownFieldsUnsupportedSchemaAndInvalidCounters() { + GetAuthoredWorldVersionStateRequest valid = + AuthoredWorldVersionStateGrpcCodec.toRequest(request()); + + assertThatThrownBy( + () -> + AuthoredWorldVersionStateGrpcCodec.fromRequest( + valid.toBuilder().setUnknownFields(unknownFields()).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + AuthoredWorldVersionStateGrpcCodec.fromRequest( + valid.toBuilder().setSchemaVersion(2).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("request is invalid"); + assertThatThrownBy( + () -> + AuthoredWorldVersionStateGrpcCodec.fromRequest( + valid.toBuilder().setVersionId(0L).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("request is invalid"); + assertThatThrownBy( + () -> + AuthoredWorldVersionStateGrpcCodec.fromRequest( + valid.toBuilder() + .setReadRequestId("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA") + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("request is invalid"); + } + + @Test + void responseRejectsUnknownFieldsAtEveryCarrierAndContradictoryEchoes() { + var request = request(); + GetAuthoredWorldVersionStateResponse valid = + AuthoredWorldVersionStateGrpcCodec.toResponse(evidence(request)); + var wireEvidence = valid.getEvidence(); + + assertInvalidResponse( + request, valid.toBuilder().setUnknownFields(unknownFields()).build(), "unsupported fields"); + assertInvalidResponse( + request, + valid.toBuilder() + .setEvidence(wireEvidence.toBuilder().setUnknownFields(unknownFields())) + .build(), + "unsupported fields"); + assertInvalidResponse( + request, + valid.toBuilder() + .setEvidence( + wireEvidence.toBuilder() + .setSourceEvidence( + wireEvidence.getSourceEvidence().toBuilder() + .setUnknownFields(unknownFields()))) + .build(), + "unsupported fields"); + assertInvalidResponse( + request, + valid.toBuilder() + .setEvidence( + wireEvidence.toBuilder() + .setReadRequestId(uuid("55555555-5555-4555-8555-555555555555").toString())) + .build(), + "response is invalid"); + } + + @Test + void responseRejectsMissingReceiptBadDigestStateAndEpoch() { + var request = request(); + GetAuthoredWorldVersionStateResponse valid = + AuthoredWorldVersionStateGrpcCodec.toResponse(evidence(request)); + var wireEvidence = valid.getEvidence(); + + assertThatThrownBy( + () -> + AuthoredWorldVersionStateGrpcCodec.fromResponse( + request, GetAuthoredWorldVersionStateResponse.getDefaultInstance())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("no evidence"); + assertInvalidResponse( + request, + valid.toBuilder().setEvidence(wireEvidence.toBuilder().clearSourceEvidence()).build(), + "complete source receipt"); + assertInvalidResponse( + request, + valid.toBuilder() + .setEvidence(wireEvidence.toBuilder().setEvidenceDigest("sha256:" + "f".repeat(64))) + .build(), + "response is invalid"); + assertInvalidResponse( + request, + valid.toBuilder() + .setEvidence( + wireEvidence.toBuilder() + .setVersionState(VersionLifecycleState.VERSION_LIFECYCLE_STATE_UNSPECIFIED)) + .build(), + "response is invalid"); + assertInvalidResponse( + request, + valid.toBuilder().setEvidence(wireEvidence.toBuilder().setVersionStateValue(99)).build(), + "response is invalid"); + assertInvalidResponse( + request, + valid.toBuilder().setEvidence(wireEvidence.toBuilder().setVersionStateEpoch(0L)).build(), + "response is invalid"); + assertInvalidResponse( + request, + valid.toBuilder() + .setEvidence( + wireEvidence.toBuilder() + .setSourceEvidence( + wireEvidence.getSourceEvidence().toBuilder() + .setWorldDisplayName("Changed café"))) + .build(), + "response is invalid"); + } + + private static void assertInvalidResponse( + AuthoredWorldVersionStateEvidence.Request request, + GetAuthoredWorldVersionStateResponse response, + String message) { + assertThatThrownBy(() -> AuthoredWorldVersionStateGrpcCodec.fromResponse(request, response)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(message); + } + + private static AuthoredWorldVersionStateEvidence.Request request() { + AuthoredWorldSourceEvidence source = sourceEvidence(); + return new AuthoredWorldVersionStateEvidence.Request( + 1, + "test", + READ_REQUEST_ID, + TENANT_ID, + "cafe-coast", + SOURCE_OPERATION_ID, + source.evidenceDigest(), + 19L); + } + + private static AuthoredWorldVersionStateEvidence evidence( + AuthoredWorldVersionStateEvidence.Request request) { + return AuthoredWorldVersionStateEvidence.create( + request, sourceEvidence(), VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, 7L); + } + + private static AuthoredWorldSourceEvidence sourceEvidence() { + String displayName = "Café 🐉"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + "test", REGISTRATION_REQUEST_ID, TENANT_ID, "tenant-one", "cafe-coast", displayName); + return new AuthoredWorldSourceEvidence( + 1, + "test", + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + "tenant-one", + "cafe-coast", + displayName, + 42L, + "game-owner-tenant", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + "test", + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + "tenant-one", + "cafe-coast", + displayName, + 42L, + "game-owner-tenant", + "NEW_GAME_ROW")); + } + + private static UnknownFieldSet unknownFields() { + return UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} 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 8498f9933e..7ac0ba3aaf 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 @@ -106,20 +106,23 @@ public void run(ApplicationArguments args) { PublishedReleaseBundle bundle = publishedReleaseBundleRepository .findByTenantIdAndVersionId(DEMO_TENANT_ID, versionId) - .orElseGet(PublishedReleaseBundle::new); - bundle.setTenantId(DEMO_TENANT_ID); - bundle.setVersionId(versionId); - bundle.setVersionNumber(version.getVersionNumber()); - bundle.setAttestationSchemaVersion("v1"); - bundle.setPublishWorkflowId(DEMO_PUBLISH_WORKFLOW_ID); - bundle.setManifestHash(DEMO_MANIFEST_HASH); - bundle.setGenerationConfigRevision(DEMO_GENERATION_CONFIG_REVISION); - bundle.setRequiredManifestAssetKeysJson("[]"); - bundle.setParticipantDigestsJson("[]"); - bundle.setCommandDefinitionsJson("[]"); - bundle.setScriptOnly(false); - bundle.setScriptPatchVersion(null); - bundle = publishedReleaseBundleRepository.save(bundle); + .orElse(null); + if (bundle == null) { + bundle = new PublishedReleaseBundle(); + bundle.setTenantId(DEMO_TENANT_ID); + bundle.setVersionId(versionId); + bundle.setVersionNumber(version.getVersionNumber()); + bundle.setAttestationSchemaVersion("v1"); + bundle.setPublishWorkflowId(DEMO_PUBLISH_WORKFLOW_ID); + bundle.setManifestHash(DEMO_MANIFEST_HASH); + bundle.setGenerationConfigRevision(DEMO_GENERATION_CONFIG_REVISION); + bundle.setRequiredManifestAssetKeysJson("[]"); + bundle.setParticipantDigestsJson("[]"); + bundle.setCommandDefinitionsJson("[]"); + bundle.setScriptOnly(false); + bundle.setScriptPatchVersion(null); + bundle = publishedReleaseBundleRepository.save(bundle); + } VersionAssetArtifact artifact = versionAssetArtifactRepository 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 a510179f25..c7144da440 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 @@ -2,6 +2,7 @@ import java.time.LocalDateTime; import java.util.List; +import java.util.UUID; public record PublishedReleaseBundleDto( Long id, @@ -17,7 +18,9 @@ public record PublishedReleaseBundleDto( String generationConfigRevision, boolean scriptOnly, String scriptPatchVersion, - LocalDateTime publishedAt) { + LocalDateTime publishedAt, + UUID canonicalTenantId, + UUID canonicalVersionId) { public PublishedReleaseBundleDto { requiredManifestAssetKeys = List.copyOf(requiredManifestAssetKeys == null ? List.of() : requiredManifestAssetKeys); @@ -38,7 +41,9 @@ public PublishedReleaseBundleDto( String generationConfigRevision, boolean scriptOnly, String scriptPatchVersion, - LocalDateTime publishedAt) { + LocalDateTime publishedAt, + UUID canonicalTenantId, + UUID canonicalVersionId) { this( id, tenantId, @@ -53,6 +58,8 @@ public PublishedReleaseBundleDto( generationConfigRevision, scriptOnly, scriptPatchVersion, - publishedAt); + publishedAt, + canonicalTenantId, + canonicalVersionId); } } 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 9fd7a4f5ed..a65dc230f8 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 @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamedesign.entity; import java.time.LocalDateTime; +import java.util.UUID; import lombok.Data; @Data @@ -8,6 +9,8 @@ public class PublishedReleaseBundle { private Long id; private String tenantId; private Long versionId; + private UUID canonicalTenantId; + private UUID canonicalVersionId; private int versionNumber; private String attestationSchemaVersion; private String publishWorkflowId; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Version.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Version.java index 9be9dded8b..760243d04c 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Version.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Version.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamedesign.entity; import java.time.LocalDateTime; +import java.util.UUID; import lombok.Data; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; @@ -8,6 +9,11 @@ public class Version { private Long id; private String tenantId; + private UUID canonicalVersionId; + private UUID canonicalTenantId; + private Long identitySourceGameRowId; + private String identitySourceGameTenantKey; + private String identitySourceProvenanceKind; private int versionNumber; private VersionLifecycleState versionState = VersionLifecycleState.DRAFT; private Long versionStateEpoch = 1L; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java index 7507fa590d..0b619a4179 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java @@ -5,12 +5,15 @@ import java.util.UUID; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import org.jooq.DSLContext; import org.jooq.Field; import org.jooq.Record; import org.jooq.Table; import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; +import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -78,6 +81,15 @@ public class GameAuthoredWorldSourceRepository { DSL.field(DSL.name("provenance_kind"), String.class); private static final Field EVIDENCE_DIGEST = DSL.field(DSL.name("evidence_digest"), String.class); + + private static final Table VERSION = DSL.table(DSL.name("version")); + private static final Field VERSION_ID = DSL.field(DSL.name("id"), Long.class); + private static final Field VERSION_TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final Field VERSION_STATE = + DSL.field(DSL.name("version_state"), String.class); + private static final Field VERSION_STATE_EPOCH = + DSL.field(DSL.name("version_state_epoch"), Long.class); private final DSLContext dsl; public GameAuthoredWorldSourceRepository(DSLContext dsl) { @@ -223,6 +235,92 @@ public Optional read( return Optional.of(receipt); } + /** + * Reads the exact source receipt and its source-owned version from the caller's owner snapshot. + * + *

This method is intentionally separate from {@link #read}: the latter suspends any ambient + * transaction to read a committed outcome, while this owner-current read requires the dedicated + * read-only REPEATABLE_READ transaction opened by AuthoredWorldVersionStateService. + */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Optional readVersionStateSnapshot( + String targetNamespace, + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest, + long versionId) { + requireOwnerSnapshot(); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(readRequestId, "readRequestId"); + requireNonNil(sourceOperationId, "sourceOperationId"); + if (readRequestId.equals(sourceOperationId)) { + throw new IllegalArgumentException("readRequestId must be separate from sourceOperationId"); + } + if (!GameTenantCreationDigest.isDigest(expectedSourceEvidenceDigest)) { + throw new IllegalArgumentException("Expected source evidence digest is not canonical"); + } + if (versionId <= 0) { + throw new IllegalArgumentException("versionId must be positive"); + } + + Record sourceRecord = + dsl.selectFrom(OPERATION).where(OPERATION_ID.eq(sourceOperationId)).fetchOne(); + if (sourceRecord == null) { + return Optional.empty(); + } + AuthoredWorldSourceEvidence receipt = toEvidence(sourceRecord); + if (!targetNamespace.equals(receipt.targetNamespace()) + || !canonicalTenantId.equals(receipt.canonicalTenantId()) + || !worldSlug.equals(receipt.worldSlug()) + || !sourceOperationId.equals(receipt.operationId())) { + throw new InvalidSourceEvidenceException( + "Authored-world source operation does not match the exact requested scope"); + } + if (!expectedSourceEvidenceDigest.equals(receipt.evidenceDigest())) { + throw new InvalidSourceEvidenceException( + "Authored-world source evidence digest no longer matches the requested binding"); + } + + GameSource source = findGameSourceByRow(receipt.sourceGameRowId()); + if (source == null) { + throw new InvalidSourceEvidenceException("Authored-world source game row is missing"); + } + requireConsistentGameSource(source); + requireReceiptSource(receipt, source); + requireTenantBinding(receipt); + + Record versionRecord = + dsl.select(VERSION_ID, VERSION_TENANT_ID, VERSION_STATE, VERSION_STATE_EPOCH) + .from(VERSION) + .where(VERSION_ID.eq(versionId)) + .fetchOne(); + if (versionRecord == null) { + return Optional.empty(); + } + String versionTenantId = versionRecord.get(VERSION_TENANT_ID); + if (versionTenantId == null || !source.sourceGameTenantKey().equals(versionTenantId)) { + throw new InvalidSourceEvidenceException( + "Requested version is not owned by the exact Game Design source game"); + } + + VersionLifecycleState versionState; + Long versionStateEpoch = versionRecord.get(VERSION_STATE_EPOCH); + try { + String versionStateName = versionRecord.get(VERSION_STATE); + if (versionStateName == null || versionStateEpoch == null || versionStateEpoch <= 0) { + throw new IllegalArgumentException("Version lifecycle state or epoch is invalid"); + } + versionState = VersionLifecycleState.valueOf(versionStateName); + } catch (IllegalArgumentException exception) { + throw new InvalidSourceEvidenceException( + "Persisted version lifecycle state or epoch is invalid", exception); + } + return Optional.of( + new AuthoredWorldVersionStateSnapshot(receipt, versionState, versionStateEpoch)); + } + private void ensureTenantSlugBinding( String targetNamespace, String tenantSlug, GameSource source) { Record existing = @@ -427,6 +525,27 @@ private void requireActiveOwnerTransaction() { } } + private void requireOwnerSnapshot() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Authored-world version-state read requires a read-only REPEATABLE_READ owner snapshot"); + } + } + + private void requireNonNil(UUID value, String label) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } + + public record AuthoredWorldVersionStateSnapshot( + AuthoredWorldSourceEvidence sourceEvidence, + VersionLifecycleState versionState, + long versionStateEpoch) {} + private record GameSource( long sourceGameRowId, UUID canonicalTenantId, 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 f57a7af717..8af3da647d 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 @@ -3,7 +3,9 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.sql.Timestamp; import java.time.LocalDateTime; +import java.util.Objects; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import org.jooq.DSLContext; import org.jooq.Field; @@ -18,9 +20,16 @@ justification = "Injected DSLContext is an internal Spring collaborator.") public class PublishedReleaseBundleRepository { private static final Table TABLE_REF = DSL.table(DSL.name("published_release_bundle")); + private static final Table VERSION_SOURCE = + DSL.table(DSL.name("version")).as("source_version"); + private static final Table GAME_SOURCE = DSL.table(DSL.name("game")).as("source_game"); private static final Field ID = DSL.field(DSL.name("id"), Long.class); private static final Field TENANT_ID = DSL.field(DSL.name("tenant_id"), String.class); private static final Field VERSION_ID = DSL.field(DSL.name("version_id"), Long.class); + private static final Field CANONICAL_TENANT_ID = + 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 VERSION_NUMBER = DSL.field(DSL.name("version_number"), Integer.class); private static final Field ATTESTATION_SCHEMA_VERSION = @@ -44,6 +53,35 @@ public class PublishedReleaseBundleRepository { private static final Field PUBLISHED_AT = DSL.field(DSL.name("published_at"), Timestamp.class); + private static final Field SOURCE_VERSION_ID = + DSL.field(DSL.name("source_version", "id"), Long.class); + private static final Field SOURCE_VERSION_TENANT_ID = + DSL.field(DSL.name("source_version", "tenant_id"), String.class); + private static final Field SOURCE_VERSION_CANONICAL_TENANT_ID = + DSL.field(DSL.name("source_version", "canonical_tenant_id"), UUID.class); + private static final Field SOURCE_VERSION_CANONICAL_VERSION_ID = + DSL.field(DSL.name("source_version", "canonical_version_id"), UUID.class); + private static final Field SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_version", "identity_source_game_row_id"), Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_version", "identity_source_game_tenant_key"), String.class); + private static final Field SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("source_version", "identity_source_provenance_kind"), String.class); + private static final Field SOURCE_GAME_ID = + DSL.field(DSL.name("source_game", "id"), Long.class); + private static final Field SOURCE_GAME_TENANT_ID = + DSL.field(DSL.name("source_game", "tenant_id"), String.class); + private static final Field SOURCE_GAME_CANONICAL_TENANT_ID = + DSL.field(DSL.name("source_game", "canonical_tenant_id"), UUID.class); + private static final Field SOURCE_GAME_PROVENANCE_KIND = + DSL.field(DSL.name("source_game", "tenant_identity_provenance_kind"), String.class); + private static final Field SOURCE_GAME_SOURCE_ROW_ID = + DSL.field(DSL.name("source_game", "tenant_identity_source_game_id"), Long.class); + private static final Field SOURCE_GAME_SOURCE_TENANT_KEY = + DSL.field(DSL.name("source_game", "tenant_identity_source_legacy_tenant_id"), String.class); + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private final DSLContext dsl; public PublishedReleaseBundleRepository(DSLContext dsl) { @@ -60,45 +98,118 @@ public Optional findByTenantIdAndVersionId( } public PublishedReleaseBundle save(PublishedReleaseBundle bundle) { - LocalDateTime publishedAt = - bundle.getPublishedAt() == null ? LocalDateTime.now() : bundle.getPublishedAt(); - if (bundle.getId() == null) { - Long generatedId = - dsl.insertInto(TABLE_REF) - .set(TENANT_ID, bundle.getTenantId()) - .set(VERSION_ID, bundle.getVersionId()) - .set(VERSION_NUMBER, bundle.getVersionNumber()) - .set(ATTESTATION_SCHEMA_VERSION, bundle.getAttestationSchemaVersion()) - .set(PUBLISH_WORKFLOW_ID, bundle.getPublishWorkflowId()) - .set(MANIFEST_HASH, bundle.getManifestHash()) - .set(GENERATION_CONFIG_REVISION, bundle.getGenerationConfigRevision()) - .set(REQUIRED_MANIFEST_ASSET_KEYS_JSON, bundle.getRequiredManifestAssetKeysJson()) - .set(PARTICIPANT_DIGESTS_JSON, bundle.getParticipantDigestsJson()) - .set(COMMAND_DEFINITIONS_JSON, bundle.getCommandDefinitionsJson()) - .set(SCRIPT_ONLY, bundle.isScriptOnly()) - .set(SCRIPT_PATCH_VERSION, bundle.getScriptPatchVersion()) - .set(PUBLISHED_AT, Timestamp.valueOf(publishedAt)) - .returningResult(ID) - .fetchOne(ID); - return dsl.selectFrom(TABLE_REF).where(ID.eq(generatedId)).fetchOne(this::toEntity); + Objects.requireNonNull(bundle, "bundle"); + if (bundle.getId() != null) { + throw new IllegalStateException( + "Published release bundle is immutable; read the stored row instead of saving it again"); + } + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + LocalDateTime publishedAt = + bundle.getPublishedAt() == null ? LocalDateTime.now() : bundle.getPublishedAt(); + return insertNewBundle(tx, bundle, publishedAt); + }); + } + + private PublishedReleaseBundle insertNewBundle( + DSLContext tx, PublishedReleaseBundle bundle, LocalDateTime publishedAt) { + CanonicalSource source = findExactCanonicalSource(tx, bundle); + rejectCallerIdentitySubstitution(bundle, source); + + Long generatedId = + tx.insertInto(TABLE_REF) + .set(TENANT_ID, bundle.getTenantId()) + .set(VERSION_ID, bundle.getVersionId()) + .set(CANONICAL_TENANT_ID, source.canonicalTenantId()) + .set(CANONICAL_VERSION_ID, source.canonicalVersionId()) + .set(VERSION_NUMBER, bundle.getVersionNumber()) + .set(ATTESTATION_SCHEMA_VERSION, bundle.getAttestationSchemaVersion()) + .set(PUBLISH_WORKFLOW_ID, bundle.getPublishWorkflowId()) + .set(MANIFEST_HASH, bundle.getManifestHash()) + .set(GENERATION_CONFIG_REVISION, bundle.getGenerationConfigRevision()) + .set(REQUIRED_MANIFEST_ASSET_KEYS_JSON, bundle.getRequiredManifestAssetKeysJson()) + .set(PARTICIPANT_DIGESTS_JSON, bundle.getParticipantDigestsJson()) + .set(COMMAND_DEFINITIONS_JSON, bundle.getCommandDefinitionsJson()) + .set(SCRIPT_ONLY, bundle.isScriptOnly()) + .set(SCRIPT_PATCH_VERSION, bundle.getScriptPatchVersion()) + .set(PUBLISHED_AT, Timestamp.valueOf(publishedAt)) + .returningResult(ID) + .fetchOne(ID); + if (generatedId == null) { + throw new IllegalStateException("Published release bundle insert returned no row id"); } - dsl.update(TABLE_REF) - .set(TENANT_ID, bundle.getTenantId()) - .set(VERSION_ID, bundle.getVersionId()) - .set(VERSION_NUMBER, bundle.getVersionNumber()) - .set(ATTESTATION_SCHEMA_VERSION, bundle.getAttestationSchemaVersion()) - .set(PUBLISH_WORKFLOW_ID, bundle.getPublishWorkflowId()) - .set(MANIFEST_HASH, bundle.getManifestHash()) - .set(GENERATION_CONFIG_REVISION, bundle.getGenerationConfigRevision()) - .set(REQUIRED_MANIFEST_ASSET_KEYS_JSON, bundle.getRequiredManifestAssetKeysJson()) - .set(PARTICIPANT_DIGESTS_JSON, bundle.getParticipantDigestsJson()) - .set(COMMAND_DEFINITIONS_JSON, bundle.getCommandDefinitionsJson()) - .set(SCRIPT_ONLY, bundle.isScriptOnly()) - .set(SCRIPT_PATCH_VERSION, bundle.getScriptPatchVersion()) - .set(PUBLISHED_AT, Timestamp.valueOf(publishedAt)) - .where(ID.eq(bundle.getId())) - .execute(); - return findByTenantIdAndVersionId(bundle.getTenantId(), bundle.getVersionId()).orElseThrow(); + + PublishedReleaseBundle persisted = findById(tx, generatedId).orElseThrow(); + verifyPersistedSource(persisted, bundle, source); + return persisted; + } + + private CanonicalSource findExactCanonicalSource(DSLContext tx, PublishedReleaseBundle bundle) { + if (bundle.getTenantId() == null || bundle.getVersionId() == null) { + throw new IllegalArgumentException( + "Published release bundle requires tenant and Version row"); + } + + Record source = + tx.select(SOURCE_VERSION_CANONICAL_TENANT_ID, SOURCE_VERSION_CANONICAL_VERSION_ID) + .from(VERSION_SOURCE.join(GAME_SOURCE).on(SOURCE_GAME_ROW_ID.eq(SOURCE_GAME_ID))) + .where( + SOURCE_VERSION_ID + .eq(bundle.getVersionId()) + .and(SOURCE_VERSION_TENANT_ID.eq(bundle.getTenantId())) + .and(SOURCE_VERSION_CANONICAL_TENANT_ID.isNotNull()) + .and(SOURCE_VERSION_CANONICAL_TENANT_ID.ne(NIL_UUID)) + .and(SOURCE_VERSION_CANONICAL_VERSION_ID.isNotNull()) + .and(SOURCE_VERSION_CANONICAL_VERSION_ID.ne(NIL_UUID)) + .and(SOURCE_VERSION_TENANT_ID.eq(SOURCE_GAME_TENANT_ID)) + .and(SOURCE_GAME_TENANT_KEY.eq(SOURCE_GAME_TENANT_ID)) + .and(SOURCE_VERSION_CANONICAL_TENANT_ID.eq(SOURCE_GAME_CANONICAL_TENANT_ID)) + .and(SOURCE_PROVENANCE_KIND.eq(SOURCE_GAME_PROVENANCE_KIND)) + .and(SOURCE_PROVENANCE_KIND.in("NEW_GAME_ROW", "RETAINED_GAME_V30")) + .and(SOURCE_GAME_SOURCE_ROW_ID.eq(SOURCE_GAME_ID)) + .and(SOURCE_GAME_SOURCE_TENANT_KEY.eq(SOURCE_GAME_TENANT_ID))) + .fetchOne(); + if (source == null) { + throw new IllegalStateException( + "No exact canonical Game Design source association exists for the requested Version"); + } + + UUID canonicalTenantId = source.get(SOURCE_VERSION_CANONICAL_TENANT_ID); + UUID canonicalVersionId = source.get(SOURCE_VERSION_CANONICAL_VERSION_ID); + if (canonicalTenantId == null + || NIL_UUID.equals(canonicalTenantId) + || canonicalVersionId == null + || NIL_UUID.equals(canonicalVersionId)) { + throw new IllegalStateException("Exact Game Design source has an invalid canonical identity"); + } + return new CanonicalSource(canonicalTenantId, canonicalVersionId); + } + + private void rejectCallerIdentitySubstitution( + PublishedReleaseBundle bundle, CanonicalSource source) { + if ((bundle.getCanonicalTenantId() != null + && !bundle.getCanonicalTenantId().equals(source.canonicalTenantId())) + || (bundle.getCanonicalVersionId() != null + && !bundle.getCanonicalVersionId().equals(source.canonicalVersionId()))) { + throw new IllegalArgumentException( + "Caller-supplied canonical release identity does not match the exact Version source"); + } + } + + private void verifyPersistedSource( + PublishedReleaseBundle persisted, PublishedReleaseBundle requested, CanonicalSource source) { + if (!Objects.equals(persisted.getTenantId(), requested.getTenantId()) + || !Objects.equals(persisted.getVersionId(), requested.getVersionId()) + || !Objects.equals(persisted.getCanonicalTenantId(), source.canonicalTenantId()) + || !Objects.equals(persisted.getCanonicalVersionId(), source.canonicalVersionId())) { + throw new IllegalStateException( + "Published release bundle readback does not match its exact Version source"); + } + } + + private Optional findById(DSLContext tx, Long id) { + return Optional.ofNullable(tx.selectFrom(TABLE_REF).where(ID.eq(id)).fetchOne(this::toEntity)); } private PublishedReleaseBundle toEntity(Record record) { @@ -109,6 +220,8 @@ private PublishedReleaseBundle toEntity(Record record) { bundle.setId(record.get(ID)); bundle.setTenantId(record.get(TENANT_ID)); bundle.setVersionId(record.get(VERSION_ID)); + bundle.setCanonicalTenantId(record.get(CANONICAL_TENANT_ID)); + bundle.setCanonicalVersionId(record.get(CANONICAL_VERSION_ID)); bundle.setVersionNumber(record.get(VERSION_NUMBER)); bundle.setAttestationSchemaVersion(record.get(ATTESTATION_SCHEMA_VERSION)); bundle.setPublishWorkflowId(record.get(PUBLISH_WORKFLOW_ID)); @@ -123,4 +236,6 @@ private PublishedReleaseBundle toEntity(Record record) { bundle.setPublishedAt(publishedAt == null ? null : publishedAt.toLocalDateTime()); return bundle; } + + private record CanonicalSource(UUID canonicalTenantId, UUID canonicalVersionId) {} } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java index 774bb6fa9a..e380b3a794 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java @@ -6,6 +6,7 @@ import java.util.List; import java.util.Objects; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.common.config.PostgresProperties; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; @@ -15,6 +16,7 @@ import org.jooq.Table; import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; @Repository @SuppressFBWarnings( @@ -24,8 +26,40 @@ public class VersionRepository { private static final String ENTITY_DIGEST_BASELINE_MIGRATION_VERSION_LOCK_FUNCTION_NAME = "lock_version_for_entity_digest_baseline_migration"; private static final Table VERSION_TABLE = DSL.table(DSL.name("version")); + private static final Table GAME_TABLE = DSL.table(DSL.name("game")); private static final Field ID = DSL.field(DSL.name("id"), Long.class); private static final Field TENANT_ID = DSL.field(DSL.name("tenant_id"), String.class); + private static final Field CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field IDENTITY_SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("identity_source_game_row_id"), Long.class); + private static final Field IDENTITY_SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("identity_source_game_tenant_key"), String.class); + private static final Field IDENTITY_SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("identity_source_provenance_kind"), String.class); + private static final Field VERSION_TENANT_ID = + DSL.field(DSL.name("version", "tenant_id"), String.class); + private static final Field VERSION_CANONICAL_TENANT_ID = + DSL.field(DSL.name("version", "canonical_tenant_id"), UUID.class); + private static final Field VERSION_IDENTITY_SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("version", "identity_source_game_row_id"), Long.class); + private static final Field VERSION_IDENTITY_SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("version", "identity_source_game_tenant_key"), String.class); + private static final Field VERSION_IDENTITY_SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("version", "identity_source_provenance_kind"), String.class); + private static final Field GAME_ID = DSL.field(DSL.name("game", "id"), Long.class); + private static final Field GAME_TENANT_ID = + DSL.field(DSL.name("game", "tenant_id"), String.class); + private static final Field GAME_CANONICAL_TENANT_ID = + DSL.field(DSL.name("game", "canonical_tenant_id"), UUID.class); + private static final Field GAME_TENANT_PROVENANCE_KIND = + DSL.field(DSL.name("game", "tenant_identity_provenance_kind"), String.class); + private static final Field GAME_TENANT_SOURCE_GAME_ID = + DSL.field(DSL.name("game", "tenant_identity_source_game_id"), Long.class); + private static final Field GAME_TENANT_SOURCE_LEGACY_KEY = + DSL.field(DSL.name("game", "tenant_identity_source_legacy_tenant_id"), String.class); private static final Field VERSION_NUMBER = DSL.field(DSL.name("version_number"), Integer.class); private static final Field VERSION_STATE = @@ -43,6 +77,7 @@ public class VersionRepository { DSL.field(DSL.name("created_at"), Timestamp.class); private static final Field UPDATED_AT = DSL.field(DSL.name("updated_at"), Timestamp.class); + private static final UUID NIL_UUID = new UUID(0L, 0L); private final DSLContext dsl; private final String postgresSchema; @@ -118,6 +153,47 @@ public Optional findByTenantIdAndIdForEntityDigestBaselineMigration( + "(?, ?)", tenantId, id) + .fetchOne(this::toEntityWithoutCanonicalIdentity)); + } + + /** + * Resolves only a canonical version UUID whose persisted tenant/source provenance still matches + * the exact Game Design owner row. Numeric Version IDs remain private to owner-local callers. + */ + public Optional findByCanonicalTenantIdAndCanonicalVersionId( + UUID canonicalTenantId, UUID canonicalVersionId) { + if (canonicalTenantId == null + || canonicalVersionId == null + || canonicalTenantId.equals(NIL_UUID) + || canonicalVersionId.equals(NIL_UUID)) { + return Optional.empty(); + } + + return Optional.ofNullable( + dsl.selectFrom(VERSION_TABLE) + .where( + CANONICAL_VERSION_ID + .eq(canonicalVersionId) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and( + DSL.exists( + DSL.selectOne() + .from(GAME_TABLE) + .where( + GAME_ID + .eq(VERSION_IDENTITY_SOURCE_GAME_ROW_ID) + .and( + GAME_TENANT_ID.eq( + VERSION_IDENTITY_SOURCE_GAME_TENANT_KEY)) + .and(GAME_TENANT_ID.eq(VERSION_TENANT_ID)) + .and( + GAME_CANONICAL_TENANT_ID.eq( + VERSION_CANONICAL_TENANT_ID)) + .and( + GAME_TENANT_PROVENANCE_KIND.eq( + VERSION_IDENTITY_SOURCE_PROVENANCE_KIND)) + .and(GAME_TENANT_SOURCE_GAME_ID.eq(GAME_ID)) + .and(GAME_TENANT_SOURCE_LEGACY_KEY.eq(GAME_TENANT_ID)))))) .fetchOne(this::toEntity)); } @@ -177,16 +253,24 @@ public long count() { return dsl.fetchCount(VERSION_TABLE); } + @Transactional public Version save(Version version) { LocalDateTime createdAt = version.getCreatedAt() == null ? LocalDateTime.now() : version.getCreatedAt(); LocalDateTime updatedAt = version.getUpdatedAt() == null ? LocalDateTime.now() : version.getUpdatedAt(); if (version.getId() == null) { + VersionSource source = findExactGameSource(version.getTenantId()); + UUID canonicalVersionId = newNonNilUuid(); Record record = Objects.requireNonNull( dsl.insertInto(VERSION_TABLE) .set(TENANT_ID, version.getTenantId()) + .set(CANONICAL_VERSION_ID, canonicalVersionId) + .set(CANONICAL_TENANT_ID, source.canonicalTenantId()) + .set(IDENTITY_SOURCE_GAME_ROW_ID, source.sourceGameRowId()) + .set(IDENTITY_SOURCE_GAME_TENANT_KEY, source.sourceGameTenantKey()) + .set(IDENTITY_SOURCE_PROVENANCE_KIND, source.provenanceKind()) .set(VERSION_NUMBER, version.getVersionNumber()) .set(VERSION_STATE, version.getVersionState().name()) .set(VERSION_STATE_EPOCH, version.getVersionStateEpoch()) @@ -199,6 +283,11 @@ public Version save(Version version) { .returning( ID, TENANT_ID, + CANONICAL_VERSION_ID, + CANONICAL_TENANT_ID, + IDENTITY_SOURCE_GAME_ROW_ID, + IDENTITY_SOURCE_GAME_TENANT_KEY, + IDENTITY_SOURCE_PROVENANCE_KIND, VERSION_NUMBER, VERSION_STATE, VERSION_STATE_EPOCH, @@ -209,7 +298,10 @@ public Version save(Version version) { CREATED_AT, UPDATED_AT) .fetchOne()); - return toEntity(record); + Version inserted = toEntity(record); + Version persisted = findById(inserted.getId()).orElseThrow(); + requireIssuedIdentityReadback(persisted, inserted.getTenantId(), canonicalVersionId, source); + return persisted; } dsl.update(VERSION_TABLE) .set(TENANT_ID, version.getTenantId()) @@ -234,9 +326,25 @@ public void delete(Version version) { } private Version toEntity(Record record) { + return toEntity(record, true); + } + + /** The restricted baseline-lock function intentionally returns only its historical projection. */ + private Version toEntityWithoutCanonicalIdentity(Record record) { + return toEntity(record, false); + } + + private Version toEntity(Record record, boolean includeCanonicalIdentity) { Version version = new Version(); version.setId(record.get(ID)); version.setTenantId(record.get(TENANT_ID)); + if (includeCanonicalIdentity) { + version.setCanonicalVersionId(record.get(CANONICAL_VERSION_ID)); + version.setCanonicalTenantId(record.get(CANONICAL_TENANT_ID)); + version.setIdentitySourceGameRowId(record.get(IDENTITY_SOURCE_GAME_ROW_ID)); + version.setIdentitySourceGameTenantKey(record.get(IDENTITY_SOURCE_GAME_TENANT_KEY)); + version.setIdentitySourceProvenanceKind(record.get(IDENTITY_SOURCE_PROVENANCE_KIND)); + } version.setVersionNumber(record.get(VERSION_NUMBER)); String versionState = record.get(VERSION_STATE); version.setVersionState( @@ -254,4 +362,74 @@ private Version toEntity(Record record) { version.setUpdatedAt(updatedAt == null ? null : updatedAt.toLocalDateTime()); return version; } + + private VersionSource findExactGameSource(String tenantId) { + if (tenantId == null || tenantId.isBlank()) { + throw new IllegalStateException( + "New Version requires an exact Game Design source tenant key"); + } + Record source = + dsl.select( + GAME_ID, + GAME_TENANT_ID, + GAME_CANONICAL_TENANT_ID, + GAME_TENANT_PROVENANCE_KIND, + GAME_TENANT_SOURCE_GAME_ID, + GAME_TENANT_SOURCE_LEGACY_KEY) + .from(GAME_TABLE) + .where(GAME_TENANT_ID.eq(tenantId)) + .fetchOne(); + if (source == null) { + throw new IllegalStateException("New Version tenant has no exact Game Design source row"); + } + + Long sourceGameRowId = source.get(GAME_ID); + String sourceGameTenantKey = source.get(GAME_TENANT_ID); + UUID canonicalTenantId = source.get(GAME_CANONICAL_TENANT_ID); + String provenanceKind = source.get(GAME_TENANT_PROVENANCE_KIND); + Long tenantSourceGameRowId = source.get(GAME_TENANT_SOURCE_GAME_ID); + String tenantSourceGameTenantKey = source.get(GAME_TENANT_SOURCE_LEGACY_KEY); + if (sourceGameRowId == null + || sourceGameRowId <= 0 + || !tenantId.equals(sourceGameTenantKey) + || canonicalTenantId == null + || canonicalTenantId.equals(NIL_UUID) + || provenanceKind == null + || !("NEW_GAME_ROW".equals(provenanceKind) || "RETAINED_GAME_V30".equals(provenanceKind)) + || !sourceGameRowId.equals(tenantSourceGameRowId) + || !tenantId.equals(tenantSourceGameTenantKey)) { + throw new IllegalStateException( + "New Version tenant source provenance is incomplete or invalid"); + } + return new VersionSource( + canonicalTenantId, sourceGameRowId, sourceGameTenantKey, provenanceKind); + } + + private void requireIssuedIdentityReadback( + Version persisted, String requestedTenantKey, UUID canonicalVersionId, VersionSource source) { + if (persisted.getId() == null + || persisted.getId() <= 0 + || !requestedTenantKey.equals(persisted.getTenantId()) + || !canonicalVersionId.equals(persisted.getCanonicalVersionId()) + || !source.canonicalTenantId().equals(persisted.getCanonicalTenantId()) + || !source.sourceGameRowId().equals(persisted.getIdentitySourceGameRowId()) + || !source.sourceGameTenantKey().equals(persisted.getIdentitySourceGameTenantKey()) + || !source.provenanceKind().equals(persisted.getIdentitySourceProvenanceKind())) { + throw new IllegalStateException("Persisted Version identity did not match owner issuance"); + } + } + + private UUID newNonNilUuid() { + UUID uuid; + do { + uuid = UUID.randomUUID(); + } while (NIL_UUID.equals(uuid)); + return uuid; + } + + private record VersionSource( + UUID canonicalTenantId, + Long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) {} } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java new file mode 100644 index 0000000000..8484c9dd2d --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java @@ -0,0 +1,110 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateResponse; +import org.springframework.dao.DataAccessException; +import org.springframework.transaction.TransactionException; + +/** + * Standalone handler for the source-qualified version-state RPC. + * + *

This handler is deliberately not registered as a Spring gRPC service. The authenticated World + * intake remains disabled until the owning orchestrator explicitly wires and proves this boundary. + */ +public final class AuthoredWorldVersionStateGrpcService + extends GameDesignServiceGrpc.GameDesignServiceImplBase { + private final AuthoredWorldVersionStateService service; + private final String workloadNamespace; + + public AuthoredWorldVersionStateGrpcService( + AuthoredWorldVersionStateService service, String workloadNamespace) { + this.service = Objects.requireNonNull(service, "service"); + this.workloadNamespace = workloadNamespace; + } + + @Override + public void getAuthoredWorldVersionState( + GetAuthoredWorldVersionStateRequest request, + StreamObserver responseObserver) { + if (!isWorldManagementPeer()) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified same-namespace World Management identity is required") + .asRuntimeException()); + return; + } + + final net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence.Request + decodedRequest; + try { + decodedRequest = AuthoredWorldVersionStateGrpcCodec.fromRequest(request); + if (!workloadNamespace.equals(decodedRequest.targetNamespace())) { + throw new IllegalArgumentException( + "Target namespace does not match this Game Design owner"); + } + } catch (IllegalArgumentException exception) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical authored-world version-state request is required") + .asRuntimeException()); + return; + } + + try { + var evidence = service.read(decodedRequest); + responseObserver.onNext(AuthoredWorldVersionStateGrpcCodec.toResponse(evidence)); + responseObserver.onCompleted(); + } catch (AuthoredWorldVersionStateService.NotFoundException exception) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No version state exists for the exact authored-world source") + .asRuntimeException()); + } catch (GameAuthoredWorldSourceRepository.InvalidSourceEvidenceException + | IllegalArgumentException exception) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Authored-world source or version ownership is inconsistent") + .asRuntimeException()); + } catch (org.jooq.exception.TooManyRowsException exception) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Authored-world source or version ownership is ambiguous") + .asRuntimeException()); + } catch (DataAccessException | org.jooq.exception.DataAccessException exception) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Game Design owner storage is temporarily unavailable") + .asRuntimeException()); + } catch (TransactionException exception) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Game Design owner snapshot is temporarily unavailable") + .asRuntimeException()); + } catch (IllegalStateException exception) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Authored-world source or version state is invalid") + .asRuntimeException()); + } catch (RuntimeException exception) { + responseObserver.onError( + Status.INTERNAL + .withDescription("Game Design could not read authored-world version state") + .asRuntimeException()); + } + } + + private boolean isWorldManagementPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + return peer != null + && GrpcPeerIdentity.isValidNamespace(workloadNamespace) + && peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateService.java new file mode 100644 index 0000000000..55843de3eb --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateService.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository.AuthoredWorldVersionStateSnapshot; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** Reads current version state only through the exact persisted authored-world source owner. */ +@Service +public final class AuthoredWorldVersionStateService { + private final GameAuthoredWorldSourceRepository sourceRepository; + private final TransactionTemplate ownerSnapshot; + + public AuthoredWorldVersionStateService( + PlatformTransactionManager transactionManager, + GameAuthoredWorldSourceRepository sourceRepository) { + this.sourceRepository = Objects.requireNonNull(sourceRepository, "sourceRepository"); + this.ownerSnapshot = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + this.ownerSnapshot.setName("authored-world-version-state-read"); + this.ownerSnapshot.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerSnapshot.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + this.ownerSnapshot.setReadOnly(true); + this.ownerSnapshot.setTimeout(5); + } + + /** Reads source provenance, selector binding, and exact version state from one fresh snapshot. */ + public AuthoredWorldVersionStateEvidence read(AuthoredWorldVersionStateEvidence.Request request) { + Objects.requireNonNull(request, "request"); + Optional snapshot = + ownerSnapshot.execute( + status -> + sourceRepository.readVersionStateSnapshot( + request.targetNamespace(), + request.readRequestId(), + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.expectedSourceEvidenceDigest(), + request.versionId())); + if (snapshot == null || snapshot.isEmpty()) { + throw new NotFoundException( + "No authored-world source or version exists for the exact requested owner tuple"); + } + AuthoredWorldVersionStateSnapshot result = snapshot.orElseThrow(); + return AuthoredWorldVersionStateEvidence.create( + request, + result.sourceEvidence(), + toProtoState(result.versionState()), + result.versionStateEpoch()); + } + + private static VersionLifecycleState toProtoState( + net.firedevops.firemud.gamedesign.model.VersionLifecycleState state) { + Objects.requireNonNull(state, "state"); + try { + return VersionLifecycleState.valueOf("VERSION_LIFECYCLE_STATE_" + state.name()); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("Persisted version state has no closed wire enum", exception); + } + } + + public static final class NotFoundException extends RuntimeException { + public NotFoundException(String message) { + super(message); + } + } +} 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 38563cb069..389978b2e5 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 @@ -715,9 +715,10 @@ public void getPublishedReleaseBundle( PublishedReleaseBundleDto bundle = versionService.getPublishedReleaseBundle(request.getTenantId(), request.getVersionId()); PublishedReleaseBundleContract.requireSupportedSchemaForRead(bundle); + requireCanonicalReleaseIdentityPair(bundle); TemporalVersionPublishWorkflowMetadataResolver.WorkflowMetadata workflowMetadata = publishWorkflowMetadataResolver.resolve(bundle.publishWorkflowId()); - builder.setBundle( + var bundleBuilder = net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle.newBuilder() .setId(bundle.id()) .setVersionId(bundle.versionId()) @@ -753,8 +754,13 @@ public void getPublishedReleaseBundle( .setIsScriptOnly(bundle.scriptOnly()) .setScriptPatchVersion( bundle.scriptPatchVersion() == null ? "" : bundle.scriptPatchVersion()) - .setPublishedAt(bundle.publishedAt().toString()) - .build()); + .setPublishedAt(bundle.publishedAt().toString()); + if (bundle.canonicalTenantId() != null) { + bundleBuilder + .setCanonicalTenantId(bundle.canonicalTenantId().toString()) + .setCanonicalVersionId(bundle.canonicalVersionId().toString()); + } + builder.setBundle(bundleBuilder.build()); } catch (AdminAuthorizationException ex) { builder.setError( GrpcAppErrors.error( @@ -793,6 +799,21 @@ public void getPublishedReleaseBundle( responseObserver.onCompleted(); } + private void requireCanonicalReleaseIdentityPair(PublishedReleaseBundleDto bundle) { + UUID canonicalTenantId = bundle.canonicalTenantId(); + UUID canonicalVersionId = bundle.canonicalVersionId(); + if (canonicalTenantId == null && canonicalVersionId == null) { + return; + } + UUID nilUuid = new UUID(0L, 0L); + if (canonicalTenantId == null + || canonicalVersionId == null + || canonicalTenantId.equals(nilUuid) + || canonicalVersionId.equals(nilUuid)) { + throw new IllegalArgumentException("published release canonical identity pair is invalid"); + } + } + @Override @Timed(value = "gamedesignGrpc.getVersionState") public void getVersionState( 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 61800e105d..e290d3e592 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 @@ -9,12 +9,14 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.UUID; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; 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.PublishedReleaseBundleService; import org.springframework.stereotype.Service; @@ -29,15 +31,19 @@ public class PublishedReleaseBundleServiceImpl implements PublishedReleaseBundle private final PublishedReleaseBundleRepository repository; private final RevisionRepository revisionRepository; + private final VersionRepository versionRepository; private final ObjectMapper objectMapper; public PublishedReleaseBundleServiceImpl( PublishedReleaseBundleRepository repository, RevisionRepository revisionRepository, + VersionRepository versionRepository, ObjectMapper objectMapper) { this.repository = Objects.requireNonNull(repository, "repository must not be null"); this.revisionRepository = Objects.requireNonNull(revisionRepository, "revisionRepository must not be null"); + this.versionRepository = + Objects.requireNonNull(versionRepository, "versionRepository must not be null"); this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper must not be null"); } @@ -58,9 +64,26 @@ public PublishedReleaseBundleDto createFullVersionBundle( ignored -> { throw new IllegalStateException("published release bundle already exists"); }); + var identitySource = + versionRepository + .findByTenantIdAndId(version.tenantId(), version.id()) + .orElseThrow( + () -> + new IllegalStateException( + "published release canonical identity source missing")); + UUID canonicalTenantId = identitySource.getCanonicalTenantId(); + UUID canonicalVersionId = identitySource.getCanonicalVersionId(); + if (!version.id().equals(identitySource.getId()) + || !version.tenantId().equals(identitySource.getTenantId()) + || !isCanonicalNonNilUuid(canonicalTenantId) + || !isCanonicalNonNilUuid(canonicalVersionId)) { + throw new IllegalStateException("published release canonical identity source is invalid"); + } PublishedReleaseBundle entity = new PublishedReleaseBundle(); entity.setTenantId(version.tenantId()); entity.setVersionId(version.id()); + entity.setCanonicalTenantId(canonicalTenantId); + entity.setCanonicalVersionId(canonicalVersionId); entity.setVersionNumber(version.versionNumber()); entity.setAttestationSchemaVersion( PublishedReleaseBundleContract.SUPPORTED_ATTESTATION_SCHEMA_VERSION); @@ -113,7 +136,13 @@ private PublishedReleaseBundleDto toDto(PublishedReleaseBundle entity) { entity.getGenerationConfigRevision(), entity.isScriptOnly(), entity.getScriptPatchVersion(), - entity.getPublishedAt()); + entity.getPublishedAt(), + entity.getCanonicalTenantId(), + entity.getCanonicalVersionId()); + } + + private boolean isCanonicalNonNilUuid(UUID value) { + return value != null && !value.equals(new UUID(0L, 0L)); } private String serializeKeys(List keys) { diff --git a/services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql b/services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql new file mode 100644 index 0000000000..aa0eba3879 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql @@ -0,0 +1,116 @@ +ALTER TABLE version + ADD COLUMN canonical_version_id UUID, + ADD COLUMN canonical_tenant_id UUID, + ADD COLUMN identity_source_game_row_id BIGINT, + ADD COLUMN identity_source_game_tenant_key VARCHAR(36), + ADD COLUMN identity_source_provenance_kind VARCHAR(32); + +ALTER TABLE version + ADD CONSTRAINT uq_version_canonical_version_id UNIQUE (canonical_version_id), + ADD CONSTRAINT fk_version_identity_source_game + FOREIGN KEY (identity_source_game_row_id) REFERENCES game(id), + ADD CONSTRAINT chk_version_canonical_identity_shape CHECK ( + (canonical_version_id IS NULL + AND canonical_tenant_id IS NULL + AND identity_source_game_row_id IS NULL + AND identity_source_game_tenant_key IS NULL + AND identity_source_provenance_kind IS NULL) + OR + (canonical_version_id IS NOT NULL + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id IS NOT NULL + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND identity_source_game_row_id IS NOT NULL + AND identity_source_game_row_id > 0 + AND identity_source_game_tenant_key IS NOT NULL + AND char_length(identity_source_game_tenant_key) BETWEEN 1 AND 36 + AND identity_source_game_tenant_key !~ '^[[:space:]]*$' + AND identity_source_provenance_kind IS NOT NULL + AND identity_source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V30')) + ); + +-- [jooq ignore start] +CREATE FUNCTION enforce_version_canonical_identity() RETURNS trigger AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.canonical_version_id IS NOT NULL THEN + RAISE EXCEPTION 'canonical Version identity is immutable' + USING ERRCODE = 'check_violation'; + END IF; + RETURN OLD; + END IF; + + IF TG_OP = 'INSERT' THEN + IF NEW.canonical_version_id IS NULL + OR NEW.canonical_tenant_id IS NULL + OR NEW.identity_source_game_row_id IS NULL + OR NEW.identity_source_game_tenant_key IS NULL + OR NEW.identity_source_provenance_kind IS NULL THEN + RAISE EXCEPTION 'new Version rows require an owner-issued canonical identity' + USING ERRCODE = 'check_violation'; + END IF; + + IF NOT EXISTS ( + SELECT 1 + FROM game g + WHERE g.id = NEW.identity_source_game_row_id + AND g.tenant_id = NEW.identity_source_game_tenant_key + AND NEW.tenant_id = g.tenant_id + AND g.canonical_tenant_id = NEW.canonical_tenant_id + AND g.tenant_identity_provenance_kind = NEW.identity_source_provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + ) THEN + RAISE EXCEPTION 'canonical Version identity source does not match its exact game row' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF OLD.canonical_version_id IS NULL THEN + IF NEW.canonical_version_id IS NOT NULL + OR NEW.canonical_tenant_id IS NOT NULL + OR NEW.identity_source_game_row_id IS NOT NULL + OR NEW.identity_source_game_tenant_key IS NOT NULL + OR NEW.identity_source_provenance_kind IS NOT NULL THEN + RAISE EXCEPTION 'retained Version rows cannot be assigned a canonical identity' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.id IS DISTINCT FROM OLD.id + OR NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.canonical_version_id IS DISTINCT FROM OLD.canonical_version_id + OR NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.identity_source_game_row_id IS DISTINCT FROM OLD.identity_source_game_row_id + OR NEW.identity_source_game_tenant_key IS DISTINCT FROM OLD.identity_source_game_tenant_key + OR NEW.identity_source_provenance_kind IS DISTINCT FROM OLD.identity_source_provenance_kind THEN + RAISE EXCEPTION 'canonical Version identity and its tenant source are immutable' + USING ERRCODE = 'check_violation'; + END IF; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_version_canonical_identity_immutable + BEFORE INSERT OR UPDATE OR DELETE ON version + FOR EACH ROW + EXECUTE FUNCTION enforce_version_canonical_identity(); + +CREATE FUNCTION reject_version_canonical_identity_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM version WHERE canonical_version_id IS NOT NULL) THEN + RAISE EXCEPTION 'canonical Version identities cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_version_canonical_identity_no_truncate + BEFORE TRUNCATE ON version + FOR EACH STATEMENT + EXECUTE FUNCTION reject_version_canonical_identity_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql b/services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql new file mode 100644 index 0000000000..e8721ce2e4 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql @@ -0,0 +1,86 @@ +ALTER TABLE version + ADD CONSTRAINT uq_version_release_canonical_identity + UNIQUE (id, canonical_tenant_id, canonical_version_id); + +ALTER TABLE published_release_bundle + ADD COLUMN canonical_tenant_id UUID, + ADD COLUMN canonical_version_id UUID, + ADD CONSTRAINT chk_published_release_bundle_canonical_identity CHECK ( + (canonical_tenant_id IS NULL AND canonical_version_id IS NULL) + OR + (canonical_tenant_id IS NOT NULL + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id IS NOT NULL + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID) + ), + ADD CONSTRAINT fk_published_release_bundle_canonical_version + FOREIGN KEY (version_id, canonical_tenant_id, canonical_version_id) + REFERENCES version (id, canonical_tenant_id, canonical_version_id); + +-- [jooq ignore start] +CREATE FUNCTION enforce_published_release_bundle_immutability() RETURNS trigger AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'published release bundle metadata is retained' + USING ERRCODE = 'check_violation'; + END IF; + + IF TG_OP = 'INSERT' THEN + IF NEW.canonical_tenant_id IS NULL + OR NEW.canonical_version_id IS NULL + OR NEW.canonical_tenant_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.canonical_version_id = '00000000-0000-0000-0000-000000000000'::UUID THEN + RAISE EXCEPTION 'new published release bundles require a non-nil canonical identity' + USING ERRCODE = 'check_violation'; + END IF; + + IF NOT EXISTS ( + SELECT 1 + 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 + WHERE v.id = NEW.version_id + AND v.tenant_id = NEW.tenant_id + AND v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id + AND v.identity_source_game_row_id > 0 + AND v.identity_source_game_tenant_key = v.tenant_id + AND v.identity_source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V30') + 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 + ) THEN + RAISE EXCEPTION 'published release bundle identity does not match its exact Version and Game source' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + RAISE EXCEPTION 'published release bundle attestation is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_published_release_bundle_immutable + BEFORE INSERT OR UPDATE OR DELETE ON published_release_bundle + FOR EACH ROW + EXECUTE FUNCTION enforce_published_release_bundle_immutability(); + +CREATE FUNCTION reject_published_release_bundle_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM published_release_bundle) THEN + RAISE EXCEPTION 'published release bundle metadata cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_published_release_bundle_no_truncate + BEFORE TRUNCATE ON published_release_bundle + FOR EACH STATEMENT + EXECUTE FUNCTION reject_published_release_bundle_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java index cb5ac03aa7..fdf423051d 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java @@ -100,21 +100,23 @@ void versionLockRepositoryUsesConfiguredIsolatedOwnerSchema() throws Exception { try (Connection connection = dataSource.getConnection()) { DSLContext dsl = DSL.using(connection, SQLDialect.POSTGRES); - Table versions = DSL.table(DSL.name(schema, "version")); - var idField = DSL.field(DSL.name("id"), Long.class); - Long versionId = - dsl.insertInto(versions) - .set(DSL.field(DSL.name("tenant_id"), String.class), "configured-schema-tenant") - .set(DSL.field(DSL.name("version_number"), Integer.class), 7) - .set(DSL.field(DSL.name("version_state"), String.class), "PUBLISHED") - .set(DSL.field(DSL.name("version_state_epoch"), Long.class), 9L) - .set(DSL.field(DSL.name("is_script_only"), Boolean.class), false) - .set(DSL.field(DSL.name("notes"), String.class), "configured owner schema lock proof") - .returning(idField) - .fetchOne(idField); - assertThat(versionId).isNotNull(); - VersionRepository repository = new VersionRepository(dsl, postgresProperties); + GameRepository gameRepository = new GameRepository(dsl); + Game game = new Game(); + game.setTenantId("configured-schema-tenant"); + game.setName("Configured owner schema lock proof"); + game.setDescription("Version source for configured owner schema lock proof"); + Game savedGame = gameRepository.save(game); + + Version version = new Version(); + version.setTenantId(savedGame.getTenantId()); + version.setVersionNumber(7); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(9L); + version.setNotes("configured owner schema lock proof"); + Version savedVersion = repository.save(version); + Long versionId = savedVersion.getId(); + assertThat(versionId).isNotNull(); Version locked = repository 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 new file mode 100644 index 0000000000..85fa1d8ad8 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java @@ -0,0 +1,613 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.config.PostgresProperties; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.SQLDialect; +import org.jooq.Table; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.jooq.impl.DataSourceConnectionProvider; +import org.jooq.impl.DefaultConfiguration; +import org.junit.jupiter.api.Test; +import org.springframework.boot.jooq.autoconfigure.SpringTransactionProvider; +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 PublishedReleaseCanonicalIdentityIntegrationTest { + 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 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); + private static final Field TENANT_ID = DSL.field(DSL.name("tenant_id"), String.class); + private static final Field VERSION_ID = DSL.field(DSL.name("version_id"), Long.class); + private static final Field CANONICAL_TENANT_ID = + 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 UUID NIL_UUID = new UUID(0L, 0L); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void migrationLeavesRetainedReleaseTupleAndXminUnchangedAndUnmapped() { + Fixture fixture = fixture(V35); + Game game = saveGame(fixture, "retained-release-tenant"); + Long retainedVersionId = insertRetainedVersion(fixture.dsl(), game.getTenantId()); + Long retainedBundleId = + insertRetainedBundle(fixture.dsl(), game.getTenantId(), retainedVersionId); + Map retainedTupleBefore = retainedTuple(fixture.dsl(), retainedBundleId); + String retainedXminBefore = bundleXmin(fixture.dsl(), retainedBundleId); + + migrate(fixture.dataSource(), fixture.schema(), V35_1); + migrate(fixture.dataSource(), fixture.schema(), V35_2); + + 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(); + }); + assertThatThrownBy( + () -> + fixture + .releaseBundleRepository() + .save(bundle(game.getTenantId(), retainedVersionId))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No exact canonical Game Design source association"); + assertThat(bundleCount(fixture.dsl())).isEqualTo(1); + } + + @Test + void normalSavePersistsExactVersionAndVerifiedGameIdentityAndReadsBackWithinTransaction() { + Fixture fixture = fixture(V35_2); + Game owner = saveGame(fixture, "fresh-release-source"); + Game other = saveGame(fixture, "other-release-source"); + Version version = saveVersion(fixture, owner); + + PublishedReleaseBundle saved = + fixture.releaseBundleRepository().save(bundle(owner.getTenantId(), version.getId())); + assertThat(saved.getCanonicalTenantId()).isEqualTo(owner.getCanonicalTenantId()); + assertThat(saved.getCanonicalVersionId()).isEqualTo(version.getCanonicalVersionId()); + assertThat( + fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(owner.getTenantId(), version.getId()) + .orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(saved); + + Map bundleTupleBeforeSourceMutation = + releaseBundleTuple(fixture.dsl(), saved.getId()); + String bundleXminBeforeSourceMutation = bundleXmin(fixture.dsl(), saved.getId()); + String versionXminBefore = versionXmin(fixture.dsl(), version.getId()); + String gameXminBefore = gameXmin(fixture.dsl(), owner.getId()); + String otherGameXminBefore = gameXmin(fixture.dsl(), other.getId()); + assertThatThrownBy( + () -> + fixture + .dsl() + .update(VERSION) + .set(CANONICAL_TENANT_ID, other.getCanonicalTenantId()) + .where(ID.eq(version.getId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("canonical Version identity and its tenant source are immutable"); + + assertThat(releaseBundleTuple(fixture.dsl(), saved.getId())) + .isEqualTo(bundleTupleBeforeSourceMutation); + assertThat(bundleXmin(fixture.dsl(), saved.getId())).isEqualTo(bundleXminBeforeSourceMutation); + assertThat(bundleCount(fixture.dsl())).isEqualTo(1); + assertThat(versionXmin(fixture.dsl(), version.getId())).isEqualTo(versionXminBefore); + assertThat(gameXmin(fixture.dsl(), owner.getId())).isEqualTo(gameXminBefore); + assertThat(gameXmin(fixture.dsl(), other.getId())).isEqualTo(otherGameXminBefore); + assertThat( + fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(owner.getTenantId(), version.getId()) + .orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(saved); + } + + @Test + void repositoryNestedTransactionRollsBackWithOuterSpringPublisherTransaction() { + Fixture fixture = fixture(V35_2); + Game owner = saveGame(fixture, "outer-release-rollback-owner"); + Version version = saveVersion(fixture, owner); + String versionXminBefore = versionXmin(fixture.dsl(), version.getId()); + String gameXminBefore = gameXmin(fixture.dsl(), owner.getId()); + + assertThatThrownBy( + () -> + fixture + .transactionTemplate() + .execute( + status -> { + PublishedReleaseBundle saved = + fixture + .releaseBundleRepository() + .save(bundle(owner.getTenantId(), version.getId())); + assertThat(saved.getCanonicalTenantId()) + .isEqualTo(owner.getCanonicalTenantId()); + assertThat(saved.getCanonicalVersionId()) + .isEqualTo(version.getCanonicalVersionId()); + Version publishingVersion = + fixture + .versionRepository() + .findByTenantIdAndId(owner.getTenantId(), version.getId()) + .orElseThrow(); + publishingVersion.setVersionState(VersionLifecycleState.PUBLISHED); + publishingVersion.setVersionStateEpoch( + publishingVersion.getVersionStateEpoch() + 1L); + fixture.versionRepository().save(publishingVersion); + assertThat(bundleCount(fixture.dsl())).isEqualTo(1); + assertThat( + fixture + .versionRepository() + .findByTenantIdAndId(owner.getTenantId(), version.getId()) + .orElseThrow() + .getVersionState()) + .isEqualTo(VersionLifecycleState.PUBLISHED); + throw new IllegalStateException("simulate failed outer publication"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("simulate failed outer publication"); + + assertThat(bundleCount(fixture.dsl())).isZero(); + assertThat( + fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(owner.getTenantId(), version.getId())) + .isEmpty(); + assertThat(versionXmin(fixture.dsl(), version.getId())).isEqualTo(versionXminBefore); + assertThat(gameXmin(fixture.dsl(), owner.getId())).isEqualTo(gameXminBefore); + Version exactVersionAfterRollback = + fixture + .versionRepository() + .findByTenantIdAndId(owner.getTenantId(), version.getId()) + .orElseThrow(); + assertThat(exactVersionAfterRollback.getCanonicalTenantId()) + .isEqualTo(owner.getCanonicalTenantId()); + assertThat(exactVersionAfterRollback.getCanonicalVersionId()) + .isEqualTo(version.getCanonicalVersionId()); + assertThat(exactVersionAfterRollback.getVersionState()).isEqualTo(VersionLifecycleState.DRAFT); + assertThat(exactVersionAfterRollback.getVersionStateEpoch()) + .isEqualTo(version.getVersionStateEpoch()); + assertThat(exactVersionAfterRollback.getIdentitySourceGameRowId()).isEqualTo(owner.getId()); + assertThat(exactVersionAfterRollback.getIdentitySourceGameTenantKey()) + .isEqualTo(owner.getTenantId()); + } + + @Test + void deniesWrongTenantNilAndSubstitutedCallerOrDatabaseIdentityWithoutGrowingBundles() { + Fixture fixture = fixture(V35_2); + Game owner = saveGame(fixture, "denied-release-owner"); + Game other = saveGame(fixture, "denied-release-other"); + Version version = saveVersion(fixture, owner); + + assertThatThrownBy( + () -> + fixture + .releaseBundleRepository() + .save(bundle(other.getTenantId(), version.getId()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No exact canonical Game Design source association"); + + PublishedReleaseBundle substitutedTenant = bundle(owner.getTenantId(), version.getId()); + substitutedTenant.setCanonicalTenantId(other.getCanonicalTenantId()); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(substitutedTenant)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Caller-supplied canonical release identity"); + + PublishedReleaseBundle substitutedVersion = bundle(owner.getTenantId(), version.getId()); + substitutedVersion.setCanonicalVersionId(UUID.randomUUID()); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(substitutedVersion)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Caller-supplied canonical release identity"); + + assertThatThrownBy( + () -> + insertRawBundle( + fixture.dsl(), + owner.getTenantId(), + version.getId(), + NIL_UUID, + version.getCanonicalVersionId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("non-nil canonical identity"); + assertThatThrownBy( + () -> + insertRawBundle( + fixture.dsl(), + owner.getTenantId(), + version.getId(), + other.getCanonicalTenantId(), + version.getCanonicalVersionId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("does not match its exact Version and Game source"); + assertThatThrownBy( + () -> + insertRawBundle( + fixture.dsl(), + other.getTenantId(), + version.getId(), + owner.getCanonicalTenantId(), + version.getCanonicalVersionId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("does not match its exact Version and Game source"); + assertThat(bundleCount(fixture.dsl())).isZero(); + } + + @Test + void bundleIdentityIsImmutableRetainedNullCannotBeBackfilledAndMetadataCannotBeDeleted() { + Fixture fixture = fixture(V35); + Game game = saveGame(fixture, "release-retention-owner"); + Long retainedVersionId = insertRetainedVersion(fixture.dsl(), game.getTenantId()); + Long retainedBundleId = + insertRetainedBundle(fixture.dsl(), game.getTenantId(), retainedVersionId); + migrate(fixture.dataSource(), fixture.schema(), V35_1); + migrate(fixture.dataSource(), fixture.schema(), V35_2); + + Version mappedVersion = saveVersion(fixture, game); + PublishedReleaseBundle mapped = + fixture.releaseBundleRepository().save(bundle(game.getTenantId(), mappedVersion.getId())); + Map mappedTupleBefore = releaseBundleTuple(fixture.dsl(), mapped.getId()); + String mappedXminBefore = bundleXmin(fixture.dsl(), mapped.getId()); + Map retainedTupleBefore = releaseBundleTuple(fixture.dsl(), retainedBundleId); + String retainedXminBefore = bundleXmin(fixture.dsl(), retainedBundleId); + + PublishedReleaseBundle exactReadback = + fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(game.getTenantId(), mappedVersion.getId()) + .orElseThrow(); + assertThat(exactReadback).usingRecursiveComparison().isEqualTo(mapped); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(exactReadback)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + exactReadback.setManifestHash("sha256:attempted-release-metadata-mutation"); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(exactReadback)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + + assertThatThrownBy( + () -> + fixture + .dsl() + .update(RELEASE_BUNDLE) + .set(DSL.field(DSL.name("manifest_hash"), String.class), "sha256:forged") + .where(ID.eq(mapped.getId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("published release bundle attestation is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE published_release_bundle SET manifest_hash = manifest_hash " + + "WHERE id = ?", + mapped.getId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("published release bundle attestation is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .update(RELEASE_BUNDLE) + .set(CANONICAL_TENANT_ID, UUID.randomUUID()) + .where(ID.eq(mapped.getId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("published release bundle attestation is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .update(RELEASE_BUNDLE) + .set(CANONICAL_VERSION_ID, UUID.randomUUID()) + .where(ID.eq(mapped.getId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("published release bundle attestation is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .update(RELEASE_BUNDLE) + .set(DSL.field(DSL.name("manifest_hash"), String.class), "sha256:forged") + .where(ID.eq(retainedBundleId)) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("published release bundle attestation is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .update(RELEASE_BUNDLE) + .set(CANONICAL_TENANT_ID, game.getCanonicalTenantId()) + .set(CANONICAL_VERSION_ID, mappedVersion.getCanonicalVersionId()) + .where(ID.eq(retainedBundleId)) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("published release bundle attestation is immutable"); + + PublishedReleaseBundle retained = + fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(game.getTenantId(), retainedVersionId) + .orElseThrow(); + assertThat(retained.getCanonicalTenantId()).isNull(); + assertThat(retained.getCanonicalVersionId()).isNull(); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(retained)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + retained.setCanonicalTenantId(game.getCanonicalTenantId()); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(retained)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + + assertThat(releaseBundleTuple(fixture.dsl(), mapped.getId())).isEqualTo(mappedTupleBefore); + assertThat(bundleXmin(fixture.dsl(), mapped.getId())).isEqualTo(mappedXminBefore); + assertThat(releaseBundleTuple(fixture.dsl(), retainedBundleId)).isEqualTo(retainedTupleBefore); + assertThat(bundleXmin(fixture.dsl(), retainedBundleId)).isEqualTo(retainedXminBefore); + assertThat( + fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(game.getTenantId(), mappedVersion.getId()) + .orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(mapped); + PublishedReleaseBundle retainedAfterAttempts = + fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(game.getTenantId(), retainedVersionId) + .orElseThrow(); + assertThat(retainedAfterAttempts.getCanonicalTenantId()).isNull(); + assertThat(retainedAfterAttempts.getCanonicalVersionId()).isNull(); + assertThat(retainedAfterAttempts.getManifestHash()).isEqualTo("sha256:retained"); + + assertThatThrownBy( + () -> fixture.dsl().deleteFrom(RELEASE_BUNDLE).where(ID.eq(mapped.getId())).execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("published release bundle metadata is retained"); + assertThatThrownBy( + () -> fixture.dsl().execute("TRUNCATE TABLE published_release_bundle CASCADE")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("metadata cannot be truncated"); + assertThat(bundleCount(fixture.dsl())).isEqualTo(2); + } + + private Fixture fixture(MigrationVersion target) { + String schema = "game_design_release_identity_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, target); + return fixtureFromMigratedSchema(schema, dataSource); + } + + private Fixture fixtureFromMigratedSchema(String schema, DriverManagerDataSource dataSource) { + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + DefaultConfiguration jooqConfiguration = new DefaultConfiguration(); + jooqConfiguration.set(SQLDialect.POSTGRES); + jooqConfiguration.set( + new DataSourceConnectionProvider(new TransactionAwareDataSourceProxy(dataSource))); + jooqConfiguration.set(new SpringTransactionProvider(transactionManager)); + DSLContext dsl = DSL.using(jooqConfiguration); + GameRepository gameRepository = new GameRepository(dsl); + PostgresProperties postgresProperties = new PostgresProperties(); + postgresProperties.setSchema(schema); + VersionRepository versionRepository = new VersionRepository(dsl, postgresProperties); + PublishedReleaseBundleRepository releaseBundleRepository = + new PublishedReleaseBundleRepository(dsl); + return new Fixture( + schema, + dataSource, + dsl, + transactionTemplate, + gameRepository, + versionRepository, + releaseBundleRepository); + } + + 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 tenantKey) { + Game game = new Game(); + game.setTenantId(tenantKey); + game.setName("Published Release Identity Owner"); + game.setDescription("Exact immutable Game source association"); + return fixture.transactionTemplate().execute(status -> fixture.gameRepository().save(game)); + } + + private Version saveVersion(Fixture fixture, Game game) { + Version version = new Version(); + version.setTenantId(game.getTenantId()); + version.setVersionNumber(1); + version.setNotes("fresh release source"); + return fixture + .transactionTemplate() + .execute(status -> fixture.versionRepository().save(version)); + } + + private Long insertRetainedVersion(DSLContext dsl, String tenantId) { + return dsl.resultQuery( + "INSERT INTO version (tenant_id, version_number, version_state, version_state_epoch, " + + "script_patch_version, base_version_id, is_script_only, notes) " + + "VALUES (?, 4, 'FAILED', 3, NULL, NULL, FALSE, 'retained release source') " + + "RETURNING id", + tenantId) + .fetchOne(0, Long.class); + } + + private Long insertRetainedBundle(DSLContext dsl, String tenantId, Long versionId) { + return dsl.resultQuery( + "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, " + + "script_patch_version) VALUES (?, ?, 4, 'v1', 'retained-workflow', " + + "'sha256:retained', 'retained-config', '[\"asset-a\"]', '[]', '[]', FALSE, NULL) " + + "RETURNING id", + tenantId, + versionId) + .fetchOne(0, Long.class); + } + + private PublishedReleaseBundle bundle(String tenantId, Long versionId) { + PublishedReleaseBundle bundle = new PublishedReleaseBundle(); + bundle.setTenantId(tenantId); + bundle.setVersionId(versionId); + bundle.setVersionNumber(1); + bundle.setAttestationSchemaVersion("v1"); + bundle.setPublishWorkflowId("workflow-" + versionId); + bundle.setManifestHash("sha256:manifest"); + bundle.setGenerationConfigRevision("generation-1"); + bundle.setRequiredManifestAssetKeysJson("[]"); + bundle.setParticipantDigestsJson("[]"); + bundle.setCommandDefinitionsJson("[]"); + return bundle; + } + + private void insertRawBundle( + DSLContext dsl, + String tenantId, + Long versionId, + UUID canonicalTenantId, + UUID canonicalVersionId) { + dsl.execute( + "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, " + + "canonical_tenant_id, canonical_version_id) " + + "VALUES (?, ?, 1, 'v1', 'direct-write-test', 'sha256:raw', 'generation-1', " + + "'[]', '[]', '[]', FALSE, ?, ?)", + tenantId, + versionId, + canonicalTenantId, + canonicalVersionId); + } + + private long bundleCount(DSLContext dsl) { + return dsl.fetchCount(RELEASE_BUNDLE); + } + + private Map retainedTuple(DSLContext dsl, Long bundleId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT id, tenant_id, version_id, version_number, attestation_schema_version, " + + "publish_workflow_id, manifest_hash, required_manifest_asset_keys_json, " + + "script_only, script_patch_version, published_at, " + + "generation_config_revision, participant_digests_json, " + + "command_definitions_json FROM published_release_bundle WHERE id = ?", + bundleId), + "Retained release bundle query returned no row") + .intoMap(); + } + + private Map releaseBundleTuple(DSLContext dsl, Long bundleId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT id, tenant_id, version_id, canonical_tenant_id, canonical_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, script_patch_version, published_at " + + "FROM published_release_bundle WHERE id = ?", + bundleId), + "Published release bundle tuple query returned no row") + .intoMap(); + } + + private String bundleXmin(DSLContext dsl, Long bundleId) { + var row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT xmin::text AS xmin FROM published_release_bundle WHERE id = ?", bundleId), + "Published release bundle xmin query returned no row"); + return Objects.requireNonNull( + row.get("xmin", String.class), "Published release bundle xmin readback returned null"); + } + + private String versionXmin(DSLContext dsl, Long versionId) { + var row = + Objects.requireNonNull( + dsl.fetchOne("SELECT xmin::text AS xmin FROM version WHERE id = ?", versionId), + "Version xmin query returned no row"); + return Objects.requireNonNull(row.get("xmin", String.class)); + } + + private String gameXmin(DSLContext dsl, Long gameId) { + var row = + Objects.requireNonNull( + dsl.fetchOne("SELECT xmin::text AS xmin FROM game WHERE id = ?", gameId), + "Game xmin query returned no row"); + return Objects.requireNonNull(row.get("xmin", String.class)); + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + TransactionTemplate transactionTemplate, + GameRepository gameRepository, + VersionRepository versionRepository, + PublishedReleaseBundleRepository releaseBundleRepository) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionCanonicalIdentityIntegrationTest.java new file mode 100644 index 0000000000..5773fd4f11 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionCanonicalIdentityIntegrationTest.java @@ -0,0 +1,509 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.config.PostgresProperties; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.SQLDialect; +import org.jooq.Table; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class VersionCanonicalIdentityIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final MigrationVersion V35 = MigrationVersion.fromVersion("35"); + private static final Table VERSION = DSL.table(DSL.name("version")); + private static final Field ID = DSL.field(DSL.name("id"), Long.class); + private static final Field TENANT_ID = DSL.field(DSL.name("tenant_id"), String.class); + private static final Field VERSION_NUMBER = + DSL.field(DSL.name("version_number"), Integer.class); + private static final Field VERSION_STATE = + DSL.field(DSL.name("version_state"), String.class); + private static final Field VERSION_STATE_EPOCH = + DSL.field(DSL.name("version_state_epoch"), Long.class); + private static final Field SCRIPT_PATCH_VERSION = + DSL.field(DSL.name("script_patch_version"), String.class); + private static final Field BASE_VERSION_ID = + DSL.field(DSL.name("base_version_id"), Long.class); + private static final Field IS_SCRIPT_ONLY = + DSL.field(DSL.name("is_script_only"), Boolean.class); + private static final Field NOTES = DSL.field(DSL.name("notes"), String.class); + private static final Field CREATED_AT = + DSL.field(DSL.name("created_at"), java.sql.Timestamp.class); + private static final Field UPDATED_AT = + DSL.field(DSL.name("updated_at"), java.sql.Timestamp.class); + private static final Field CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field IDENTITY_SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("identity_source_game_row_id"), Long.class); + private static final Field IDENTITY_SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("identity_source_game_tenant_key"), String.class); + private static final Field IDENTITY_SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("identity_source_provenance_kind"), String.class); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void v35_1PreservesRetainedVersionHistoryAndLeavesIdentityUnmapped() { + Fixture fixture = fixture(V35); + Game game = saveGame(fixture, "retained-version-source"); + Long retainedVersionId = insertRetainedVersion(fixture.dsl(), game.getTenantId()); + Map retainedFieldsBefore = retainedFields(fixture.dsl(), retainedVersionId); + String retainedXminBefore = versionXmin(fixture.dsl(), retainedVersionId); + + migrate(fixture.dataSource(), fixture.schema(), null); + + assertThat(retainedFields(fixture.dsl(), retainedVersionId)).isEqualTo(retainedFieldsBefore); + assertThat(versionXmin(fixture.dsl(), retainedVersionId)).isEqualTo(retainedXminBefore); + assertThat( + fixture + .dsl() + .select(CANONICAL_VERSION_ID) + .from(VERSION) + .where(ID.eq(retainedVersionId)) + .fetchOne(CANONICAL_VERSION_ID)) + .isNull(); + assertThat( + fixture + .dsl() + .select(CANONICAL_TENANT_ID) + .from(VERSION) + .where(ID.eq(retainedVersionId)) + .fetchOne(CANONICAL_TENANT_ID)) + .isNull(); + assertThat( + fixture + .dsl() + .select(IDENTITY_SOURCE_GAME_ROW_ID) + .from(VERSION) + .where(ID.eq(retainedVersionId)) + .fetchOne(IDENTITY_SOURCE_GAME_ROW_ID)) + .isNull(); + assertThat( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + game.getCanonicalTenantId(), UUID.randomUUID())) + .isEmpty(); + + assertThatThrownBy( + () -> + fixture + .dsl() + .update(VERSION) + .set(CANONICAL_VERSION_ID, UUID.randomUUID()) + .set(CANONICAL_TENANT_ID, game.getCanonicalTenantId()) + .set(IDENTITY_SOURCE_GAME_ROW_ID, game.getId()) + .set(IDENTITY_SOURCE_GAME_TENANT_KEY, game.getTenantId()) + .set(IDENTITY_SOURCE_PROVENANCE_KIND, "NEW_GAME_ROW") + .where(ID.eq(retainedVersionId)) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("retained Version rows cannot be assigned a canonical identity"); + } + + @Test + void savePersistsAndReadsBackFreshCanonicalIdentityAcrossUpdate() { + Fixture fixture = fixture(null); + Game game = saveGame(fixture, "fresh-version-source"); + + Version inserted = + fixture + .transactionTemplate() + .execute(status -> fixture.versionRepository().save(version(game))); + assertThat(inserted).isNotNull(); + assertThat(inserted.getCanonicalVersionId()).isNotNull().isNotEqualTo(NIL_UUID); + assertThat(inserted.getCanonicalTenantId()).isEqualTo(game.getCanonicalTenantId()); + assertThat(inserted.getIdentitySourceGameRowId()).isEqualTo(game.getId()); + assertThat(inserted.getIdentitySourceGameTenantKey()).isEqualTo(game.getTenantId()); + assertThat(inserted.getIdentitySourceProvenanceKind()).isEqualTo("NEW_GAME_ROW"); + + Version exactRead = + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + game.getCanonicalTenantId(), inserted.getCanonicalVersionId()) + .orElseThrow(); + assertIdentityMatches(exactRead, game, inserted.getCanonicalVersionId()); + assertIdentityMatches( + fixture.versionRepository().findById(inserted.getId()).orElseThrow(), + game, + inserted.getCanonicalVersionId()); + + inserted.setNotes("updated without replacing owner identity"); + Version updated = + fixture.transactionTemplate().execute(status -> fixture.versionRepository().save(inserted)); + assertThat(updated).isNotNull(); + assertThat(updated.getNotes()).isEqualTo("updated without replacing owner identity"); + assertIdentityMatches(updated, game, inserted.getCanonicalVersionId()); + assertIdentityMatches( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + game.getCanonicalTenantId(), inserted.getCanonicalVersionId()) + .orElseThrow(), + game, + inserted.getCanonicalVersionId()); + } + + @Test + void newVersionIdentityUsesExactRetainedGameSourceProvenance() { + Fixture fixture = fixtureWithRetainedGame(); + Game retainedGame = fixture.gameRepository().findByTenantId("retained-version-game-source"); + assertThat(retainedGame).isNotNull(); + + Version saved = + fixture + .transactionTemplate() + .execute(status -> fixture.versionRepository().save(version(retainedGame))); + + assertThat(saved).isNotNull(); + assertThat(saved.getCanonicalVersionId()).isNotNull().isNotEqualTo(NIL_UUID); + assertThat(saved.getIdentitySourceProvenanceKind()).isEqualTo("RETAINED_GAME_V30"); + assertIdentityMatches( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + retainedGame.getCanonicalTenantId(), saved.getCanonicalVersionId()) + .orElseThrow(), + retainedGame, + saved.getCanonicalVersionId(), + "RETAINED_GAME_V30"); + } + + @Test + void canonicalLookupRejectsWrongTenantMissingAndNilIdsWithoutMutation() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "lookup-version-owner"); + Game other = saveGame(fixture, "lookup-version-other"); + Version saved = + fixture + .transactionTemplate() + .execute(status -> fixture.versionRepository().save(version(owner))); + assertThat(saved).isNotNull(); + String versionXminBefore = versionXmin(fixture.dsl(), saved.getId()); + String ownerXminBefore = gameXmin(fixture.dsl(), owner.getId()); + String otherXminBefore = gameXmin(fixture.dsl(), other.getId()); + + assertThat( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + other.getCanonicalTenantId(), saved.getCanonicalVersionId())) + .isEmpty(); + assertThat( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + owner.getCanonicalTenantId(), UUID.randomUUID())) + .isEmpty(); + assertThat( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId(owner.getCanonicalTenantId(), null)) + .isEmpty(); + assertThat( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId(null, saved.getCanonicalVersionId())) + .isEmpty(); + assertThat( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + NIL_UUID, saved.getCanonicalVersionId())) + .isEmpty(); + assertThat( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + owner.getCanonicalTenantId(), NIL_UUID)) + .isEmpty(); + assertIdentityMatches( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + owner.getCanonicalTenantId(), saved.getCanonicalVersionId()) + .orElseThrow(), + owner, + saved.getCanonicalVersionId()); + + assertThat(versionXmin(fixture.dsl(), saved.getId())).isEqualTo(versionXminBefore); + assertThat(gameXmin(fixture.dsl(), owner.getId())).isEqualTo(ownerXminBefore); + assertThat(gameXmin(fixture.dsl(), other.getId())).isEqualTo(otherXminBefore); + } + + @Test + void databaseRejectsIdentityMutationNilIdentityAndMismatchedSource() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "mutation-version-owner"); + Game other = saveGame(fixture, "mutation-version-other"); + Version saved = + fixture + .transactionTemplate() + .execute(status -> fixture.versionRepository().save(version(owner))); + assertThat(saved).isNotNull(); + + assertThatThrownBy( + () -> + fixture + .dsl() + .update(VERSION) + .set(CANONICAL_VERSION_ID, UUID.randomUUID()) + .where(ID.eq(saved.getId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("canonical Version identity and its tenant source are immutable"); + assertThatThrownBy( + () -> fixture.dsl().deleteFrom(VERSION).where(ID.eq(saved.getId())).execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("canonical Version identity is immutable"); + + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "INSERT INTO version (tenant_id, version_number, version_state, " + + "version_state_epoch, canonical_version_id, canonical_tenant_id, " + + "identity_source_game_row_id, identity_source_game_tenant_key, " + + "identity_source_provenance_kind) " + + "VALUES (?, 2, 'DRAFT', 1, ?, ?, ?, ?, ?)", + owner.getTenantId(), + NIL_UUID, + owner.getCanonicalTenantId(), + owner.getId(), + owner.getTenantId(), + "NEW_GAME_ROW")) + .isInstanceOf(DataAccessException.class); + + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "INSERT INTO version (tenant_id, version_number, version_state, " + + "version_state_epoch, canonical_version_id, canonical_tenant_id, " + + "identity_source_game_row_id, identity_source_game_tenant_key, " + + "identity_source_provenance_kind) " + + "VALUES (?, 3, 'DRAFT', 1, ?, ?, ?, ?, ?)", + owner.getTenantId(), + UUID.randomUUID(), + owner.getCanonicalTenantId(), + other.getId(), + other.getTenantId(), + "NEW_GAME_ROW")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining( + "canonical Version identity source does not match its exact game row"); + + Version wrongTenantAlias = version(owner); + wrongTenantAlias.setTenantId(owner.getCanonicalTenantId().toString()); + assertThatThrownBy( + () -> + fixture + .transactionTemplate() + .execute(status -> fixture.versionRepository().save(wrongTenantAlias))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no exact Game Design source row"); + } + + @Test + void canonicalIdentityRejectsTruncateWhileUnmappedRetainedVersionRemainsDeletable() { + Fixture mappedFixture = fixture(null); + Game mappedGame = saveGame(mappedFixture, "truncate-version-owner"); + Version mapped = + mappedFixture + .transactionTemplate() + .execute(status -> mappedFixture.versionRepository().save(version(mappedGame))); + assertThat(mapped).isNotNull(); + + assertThatThrownBy(() -> mappedFixture.dsl().execute("TRUNCATE TABLE version CASCADE")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("canonical Version identities cannot be truncated"); + + Fixture retainedFixture = fixture(V35); + Game retainedGame = saveGame(retainedFixture, "delete-retained-version-owner"); + Long retainedVersionId = + insertRetainedVersion(retainedFixture.dsl(), retainedGame.getTenantId()); + migrate(retainedFixture.dataSource(), retainedFixture.schema(), null); + assertThat(retainedFixture.dsl().deleteFrom(VERSION).where(ID.eq(retainedVersionId)).execute()) + .isEqualTo(1); + } + + private Fixture fixture(MigrationVersion target) { + String schema = "game_design_version_identity_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, target); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + GameRepository gameRepository = new GameRepository(dsl); + PostgresProperties postgresProperties = new PostgresProperties(); + postgresProperties.setSchema(schema); + VersionRepository versionRepository = new VersionRepository(dsl, postgresProperties); + return new Fixture( + schema, dataSource, dsl, gameRepository, versionRepository, transactionTemplate); + } + + private Fixture fixtureWithRetainedGame() { + String schema = "gd_retained_version_identity_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("29")); + DSLContext legacyDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + legacyDsl.execute( + "INSERT INTO game (tenant_id, name, description) VALUES (?, ?, ?)", + "retained-version-game-source", + "Retained Version Source", + "Source row predating canonical tenant identity"); + migrate(dataSource, schema, null); + return fixtureFromMigratedSchema(schema, dataSource); + } + + private Fixture fixtureFromMigratedSchema(String schema, DriverManagerDataSource dataSource) { + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + GameRepository gameRepository = new GameRepository(dsl); + PostgresProperties postgresProperties = new PostgresProperties(); + postgresProperties.setSchema(schema); + VersionRepository versionRepository = new VersionRepository(dsl, postgresProperties); + return new Fixture( + schema, dataSource, dsl, gameRepository, versionRepository, transactionTemplate); + } + + private DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + return dataSource; + } + + private void migrate(DriverManagerDataSource dataSource, String schema, MigrationVersion target) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private Game saveGame(Fixture fixture, String tenantKey) { + Game game = new Game(); + game.setTenantId(tenantKey); + game.setName("Version Identity Owner"); + game.setDescription("Source row for canonical Version identity"); + return fixture.transactionTemplate().execute(status -> fixture.gameRepository().save(game)); + } + + private Long insertRetainedVersion(DSLContext dsl, String tenantId) { + return dsl.resultQuery( + "INSERT INTO version (tenant_id, version_number, version_state, version_state_epoch, " + + "script_patch_version, base_version_id, is_script_only, notes) " + + "VALUES (?, 4, 'FAILED', 3, NULL, NULL, FALSE, 'retained history') RETURNING id", + tenantId) + .fetchOne(0, Long.class); + } + + private Map retainedFields(DSLContext dsl, Long versionId) { + return dsl.select( + ID, + TENANT_ID, + VERSION_NUMBER, + VERSION_STATE, + VERSION_STATE_EPOCH, + SCRIPT_PATCH_VERSION, + BASE_VERSION_ID, + IS_SCRIPT_ONLY, + NOTES, + CREATED_AT, + UPDATED_AT) + .from(VERSION) + .where(ID.eq(versionId)) + .fetchSingle() + .intoMap(); + } + + private String versionXmin(DSLContext dsl, Long versionId) { + var row = + Objects.requireNonNull( + dsl.fetchOne("SELECT xmin::text AS xmin FROM version WHERE id = ?", versionId), + "Version xmin query returned no row"); + return Objects.requireNonNull( + row.get("xmin", String.class), "Version xmin readback returned null"); + } + + private String gameXmin(DSLContext dsl, Long gameId) { + var row = + Objects.requireNonNull( + dsl.fetchOne("SELECT xmin::text AS xmin FROM game WHERE id = ?", gameId), + "Game xmin query returned no row"); + return Objects.requireNonNull( + row.get("xmin", String.class), "Game xmin readback returned null"); + } + + private Version version(Game game) { + Version version = new Version(); + version.setTenantId(game.getTenantId()); + version.setVersionNumber(1); + version.setNotes("fresh version"); + return version; + } + + private void assertIdentityMatches(Version version, Game game, UUID canonicalVersionId) { + assertIdentityMatches(version, game, canonicalVersionId, "NEW_GAME_ROW"); + } + + private void assertIdentityMatches( + Version version, Game game, UUID canonicalVersionId, String provenanceKind) { + assertThat(version.getTenantId()).isEqualTo(game.getTenantId()); + assertThat(version.getCanonicalVersionId()).isEqualTo(canonicalVersionId); + assertThat(version.getCanonicalTenantId()).isEqualTo(game.getCanonicalTenantId()); + assertThat(version.getIdentitySourceGameRowId()).isEqualTo(game.getId()); + assertThat(version.getIdentitySourceGameTenantKey()).isEqualTo(game.getTenantId()); + assertThat(version.getIdentitySourceProvenanceKind()).isEqualTo(provenanceKind); + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + GameRepository gameRepository, + VersionRepository versionRepository, + TransactionTemplate transactionTemplate) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/AuthoredWorldVersionStateIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/AuthoredWorldVersionStateIntegrationTest.java new file mode 100644 index 0000000000..12e6feee34 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/AuthoredWorldVersionStateIntegrationTest.java @@ -0,0 +1,388 @@ +package integration.net.firedevops.firemud.gamedesign.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Locale; +import java.util.Map; +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.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +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.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldVersionStateService; +import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +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; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL owner proof for source-qualified, current Game Design version-state reads. */ +@Testcontainers(disabledWithoutDocker = true) +@SpringBootTest( + classes = GameDesignServiceApplication.class, + properties = { + "spring.profiles.active=test", + "firemud.auth.jwt-secret=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "firemud.grpc.plaintext=true", + "firemud.grpc.workload-namespace=authored-version-state-test", + "spring.grpc.server.port=0", + "asset.store.endpoint=http://localhost:9000", + "asset.store.bucket=test-bucket", + "asset.store.region=us-east-1", + "asset.store.access-key=test-access-key", + "asset.store.secret-key=test-secret-key" + }) +@Import(NoGrpcServerTestConfiguration.class) +class AuthoredWorldVersionStateIntegrationTest { + private static final String NAMESPACE = "authored-version-state-test"; + private static final org.jooq.Table VERSION = DSL.table(DSL.name("version")); + private static final org.jooq.Field VERSION_ID = DSL.field(DSL.name("id"), Long.class); + private static final org.jooq.Field VERSION_STATE = + DSL.field(DSL.name("version_state"), String.class); + private static final org.jooq.Field VERSION_STATE_EPOCH = + DSL.field(DSL.name("version_state_epoch"), Long.class); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "game_design_service"); + } + + @Autowired private AuthoredWorldVersionStateService service; + @Autowired private GameRepository gameRepository; + @Autowired private GameAuthoredWorldSourceRepository sourceRepository; + @Autowired private VersionRepository versionRepository; + @Autowired private PlatformTransactionManager transactionManager; + @Autowired private DSLContext dsl; + @Autowired private javax.sql.DataSource dataSource; + + @Test + void readsCompletePersistedSourceAndCurrentVersionWithoutMutatingOwnerRows() { + Fixture fixture = fixture("positive"); + Map before = rowVersions(fixture); + + AuthoredWorldVersionStateEvidence first = service.read(request(fixture, UUID.randomUUID())); + + assertThat(first.request().canonicalTenantId()).isEqualTo(fixture.canonicalTenantId()); + assertThat(first.request().canonicalTenantId().toString()) + .isNotEqualTo(fixture.privateTenantKey()); + assertThat(first.sourceEvidence()).isEqualTo(fixture.source()); + assertThat(first.versionState()) + .isEqualTo( + net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_DRAFT); + assertThat(first.versionStateEpoch()).isEqualTo(1L); + assertThat(rowVersions(fixture)).isEqualTo(before); + + Version changed = fixture.version(); + changed.setVersionState(VersionLifecycleState.RETIRED); + changed.setVersionStateEpoch(2L); + new TransactionTemplate(transactionManager).execute(status -> versionRepository.save(changed)); + + AuthoredWorldVersionStateEvidence current = service.read(request(fixture, UUID.randomUUID())); + assertThat(current.sourceEvidence()).isEqualTo(first.sourceEvidence()); + assertThat(current.versionState()) + .isEqualTo( + net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_RETIRED); + assertThat(current.versionStateEpoch()).isEqualTo(2L); + Map afterStateChange = rowVersions(fixture); + assertThat(afterStateChange).containsEntry("game", before.get("game")); + assertThat(afterStateChange).containsEntry("binding", before.get("binding")); + assertThat(afterStateChange).containsEntry("source", before.get("source")); + assertThat(afterStateChange.get("version")).isNotEqualTo(before.get("version")); + assertThat(rowVersions(fixture)).isEqualTo(afterStateChange); + } + + @Test + void rejectsStaleSourceDigestAndARealVersionOwnedByAnotherGame() { + Fixture sourceFixture = fixture("ownership-source"); + Fixture otherFixture = fixture("ownership-other"); + String staleDigest = "sha256:" + "f".repeat(64); + Map sourceBefore = rowVersions(sourceFixture); + Map otherBefore = rowVersions(otherFixture); + + assertThatThrownBy(() -> service.read(request(sourceFixture, UUID.randomUUID(), staleDigest))) + .isInstanceOf(GameAuthoredWorldSourceRepository.InvalidSourceEvidenceException.class) + .hasMessageContaining("digest"); + assertThatThrownBy( + () -> + service.read( + request( + UUID.randomUUID(), + otherFixture.canonicalTenantId(), + otherFixture.source().worldSlug(), + sourceFixture.source().operationId(), + sourceFixture.source().evidenceDigest(), + sourceFixture.version().getId()))) + .isInstanceOf(GameAuthoredWorldSourceRepository.InvalidSourceEvidenceException.class) + .hasMessageContaining("exact requested scope"); + assertThatThrownBy( + () -> + service.read( + request( + sourceFixture, + UUID.randomUUID(), + sourceFixture.source().evidenceDigest(), + otherFixture.version().getId()))) + .isInstanceOf(GameAuthoredWorldSourceRepository.InvalidSourceEvidenceException.class) + .hasMessageContaining("not owned by the exact Game Design source game"); + assertThat(rowVersions(sourceFixture)).isEqualTo(sourceBefore); + assertThat(rowVersions(otherFixture)).isEqualTo(otherBefore); + } + + @Test + void freshOwnerSnapshotDoesNotJoinAnAmbientRepeatableReadSnapshot() { + Fixture fixture = fixture("ambient-snapshot"); + TransactionTemplate outer = new TransactionTemplate(transactionManager); + outer.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + AuthoredWorldVersionStateEvidence result = + outer.execute( + status -> { + assertThat( + dsl.select(VERSION_STATE) + .from(VERSION) + .where(VERSION_ID.eq(fixture.version().getId())) + .fetchOne(VERSION_STATE)) + .isEqualTo("DRAFT"); + updateVersionInRequiresNew(fixture, "PUBLISHED", 2L); + AuthoredWorldVersionStateEvidence fresh = + service.read(request(fixture, UUID.randomUUID())); + assertThat( + dsl.select(VERSION_STATE) + .from(VERSION) + .where(VERSION_ID.eq(fixture.version().getId())) + .fetchOne(VERSION_STATE)) + .isEqualTo("DRAFT"); + return fresh; + }); + + assertThat(result).isNotNull(); + assertThat(result.versionState()) + .isEqualTo( + net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_PUBLISHED); + assertThat(result.versionStateEpoch()).isEqualTo(2L); + } + + @Test + void versionChangeDuringOwnerReadRemainsOneRepeatableReadSnapshot() throws Exception { + Fixture fixture = fixture("concurrent-snapshot"); + CountDownLatch versionQueryReached = new CountDownLatch(1); + CountDownLatch versionQueryReleased = new CountDownLatch(1); + AtomicBoolean interlockEnabled = new AtomicBoolean(true); + DefaultExecuteListener interlock = + new DefaultExecuteListener() { + @Override + public void executeStart(ExecuteContext context) { + String sql = context.sql(); + if (interlockEnabled.get() + && sql != null + && sql.toLowerCase(Locale.ROOT).contains("from \"version\"")) { + versionQueryReached.countDown(); + await(versionQueryReleased); + } + } + }; + DefaultConfiguration configuration = new DefaultConfiguration(); + configuration.set(new TransactionAwareDataSourceProxy(dataSource)); + configuration.set(SQLDialect.POSTGRES); + configuration.set(new DefaultExecuteListenerProvider(interlock)); + GameAuthoredWorldSourceRepository interlockedRepository = + new GameAuthoredWorldSourceRepository(DSL.using(configuration)); + AuthoredWorldVersionStateService interlockedService = + new AuthoredWorldVersionStateService(transactionManager, interlockedRepository); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + Future read = + executor.submit(() -> interlockedService.read(request(fixture, UUID.randomUUID()))); + assertThat(versionQueryReached.await(10, TimeUnit.SECONDS)).isTrue(); + updateVersionInRequiresNew(fixture, "PUBLISHED", 2L); + interlockEnabled.set(false); + versionQueryReleased.countDown(); + + AuthoredWorldVersionStateEvidence snapshot = read.get(15, TimeUnit.SECONDS); + assertThat(snapshot.versionState()) + .isEqualTo( + net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_DRAFT); + assertThat(snapshot.versionStateEpoch()).isEqualTo(1L); + AuthoredWorldVersionStateEvidence nextRead = + service.read(request(fixture, UUID.randomUUID())); + assertThat(nextRead.versionState()) + .isEqualTo( + net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_PUBLISHED); + assertThat(nextRead.versionStateEpoch()).isEqualTo(2L); + } finally { + interlockEnabled.set(false); + versionQueryReleased.countDown(); + executor.shutdownNow(); + } + } + + private Fixture fixture(String label) { + String privateTenantKey = "version-state-" + UUID.randomUUID().toString().substring(0, 8); + Game game = new Game(); + game.setTenantId(privateTenantKey); + game.setName("Synthetic " + label); + game.setDescription("Synthetic source/version owner proof fixture"); + Game persistedGame = + new TransactionTemplate(transactionManager).execute(status -> gameRepository.save(game)); + assertThat(persistedGame).isNotNull(); + + String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + AuthoredWorldSourceEvidence source = + new TransactionTemplate(transactionManager) + .execute( + status -> + sourceRepository.register( + NAMESPACE, + UUID.randomUUID(), + persistedGame.getCanonicalTenantId(), + "tenant-" + suffix, + "world-" + suffix, + "Synthetic World 🐉")); + assertThat(source).isNotNull(); + + Version version = new Version(); + version.setTenantId(privateTenantKey); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + version.setNotes("synthetic source-qualified version-state proof fixture"); + Version persistedVersion = + new TransactionTemplate(transactionManager) + .execute(status -> versionRepository.save(version)); + assertThat(persistedVersion).isNotNull(); + return new Fixture( + persistedGame.getCanonicalTenantId(), privateTenantKey, source, persistedVersion); + } + + private AuthoredWorldVersionStateEvidence.Request request(Fixture fixture, UUID readRequestId) { + return request( + fixture, readRequestId, fixture.source().evidenceDigest(), fixture.version().getId()); + } + + private AuthoredWorldVersionStateEvidence.Request request( + Fixture fixture, UUID readRequestId, String sourceDigest) { + return request(fixture, readRequestId, sourceDigest, fixture.version().getId()); + } + + private AuthoredWorldVersionStateEvidence.Request request( + Fixture fixture, UUID readRequestId, String sourceDigest, long versionId) { + return request( + readRequestId, + fixture.canonicalTenantId(), + fixture.source().worldSlug(), + fixture.source().operationId(), + sourceDigest, + versionId); + } + + private AuthoredWorldVersionStateEvidence.Request request( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceDigest, + long versionId) { + return new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + readRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceDigest, + versionId); + } + + private Map rowVersions(Fixture fixture) { + return Map.of( + "game", + xmin( + "SELECT xmin::text AS xmin FROM game WHERE canonical_tenant_id = ?", + fixture.canonicalTenantId()), + "binding", + xmin( + "SELECT xmin::text AS xmin FROM game_design_tenant_slug_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + fixture.canonicalTenantId()), + "source", + xmin( + "SELECT xmin::text AS xmin FROM game_design_authored_world_source_operations " + + "WHERE operation_id = ?", + fixture.source().operationId()), + "version", + xmin("SELECT xmin::text AS xmin FROM version WHERE id = ?", fixture.version().getId())); + } + + private String xmin(String sql, Object... arguments) { + var rows = dsl.fetch(sql, arguments); + assertThat(rows).hasSize(1); + return rows.getFirst().get("xmin", String.class); + } + + private void updateVersionInRequiresNew(Fixture fixture, String state, long epoch) { + TransactionTemplate update = new TransactionTemplate(transactionManager); + update.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + update.execute( + status -> + dsl.update(VERSION) + .set(VERSION_STATE, state) + .set(VERSION_STATE_EPOCH, epoch) + .where(VERSION_ID.eq(fixture.version().getId())) + .execute()); + } + + private void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out at version-state snapshot interlock"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted at version-state snapshot interlock", exception); + } + } + + private record Fixture( + UUID canonicalTenantId, + String privateTenantKey, + AuthoredWorldSourceEvidence source, + Version version) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/AuthoredWorldVersionStateMtlsIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/AuthoredWorldVersionStateMtlsIntegrationTest.java new file mode 100644 index 0000000000..39c66b9539 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/AuthoredWorldVersionStateMtlsIntegrationTest.java @@ -0,0 +1,502 @@ +package integration.net.firedevops.firemud.gamedesign.service; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import java.io.IOException; +import java.math.BigInteger; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.Base64; +import java.util.Date; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +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.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldVersionStateGrpcService; +import net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldVersionStateService; +import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.assertj.core.api.Assertions; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +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; + +/** + * PostgreSQL-to-physical-mTLS-socket proof for the unregistered current version-state read. + * + *

Fixtures are synthetic persisted Game Design source/version rows. The producer, repositories, + * transaction manager, standalone production handler, peer interceptor, and World client are real. + * This proves neither automatic delivery nor World mutation/publication behavior. Ephemeral + * test-only certificates cover the one authorized World client and Game Design server needed here; + * the socket-only {@code AuthoredWorldVersionStateMtlsTest} retains wrong-peer and + * malformed-evidence coverage. + */ +@Testcontainers(disabledWithoutDocker = true) +@SpringBootTest( + classes = GameDesignServiceApplication.class, + properties = { + "spring.profiles.active=test", + "firemud.auth.jwt-secret=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "firemud.grpc.plaintext=true", + "firemud.grpc.workload-namespace=authored-version-state-mtls-test", + "spring.grpc.server.port=0", + "asset.store.endpoint=http://localhost:9000", + "asset.store.bucket=test-bucket", + "asset.store.region=us-east-1", + "asset.store.access-key=test-access-key", + "asset.store.secret-key=test-secret-key" + }) +@Import(NoGrpcServerTestConfiguration.class) +class AuthoredWorldVersionStateMtlsIntegrationTest { + private static final String NAMESPACE = "authored-version-state-mtls-test"; + private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1L); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + private static TestPki pki; + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "game_design_service"); + } + + @Autowired private AuthoredWorldVersionStateService versionStateService; + @Autowired private GameRepository gameRepository; + @Autowired private GameAuthoredWorldSourceRepository sourceRepository; + @Autowired private VersionRepository versionRepository; + @Autowired private PlatformTransactionManager transactionManager; + @Autowired private org.jooq.DSLContext dsl; + + private Server server; + + @BeforeAll + static void createEphemeralTestCertificates() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + KeyPair caKeyPair = newRsaKeyPair(); + X500Name caName = new X500Name("CN=Authored Version State Integration Test CA, O=FireMUD Test"); + X509Certificate caCertificate = + issueCertificate( + caName, caKeyPair.getPublic(), caName, caKeyPair.getPrivate(), true, null, false); + pki = + new TestPki( + caCertificate, + issueLeaf( + caName, + caKeyPair.getPrivate(), + "game-design-service", + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-design-service", + true), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "world-management-service", + "spiffe://firemud/ns/" + NAMESPACE + "/sa/world-management-service", + false)); + } + + @BeforeEach + void startProductionHandlerOnPhysicalMutualTlsSocket() throws Exception { + AuthoredWorldVersionStateGrpcService handler = + new AuthoredWorldVersionStateGrpcService(versionStateService, NAMESPACE); + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.gameDesignServerCertificate().privateKey(), + pki.gameDesignServerCertificate().certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(handler, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + @AfterEach + void stopPhysicalSocket() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void returnsCompletePersistedSourceAndVersionStateOverSocketWithoutMutation( + @TempDir Path directory) throws Exception { + Fixture fixture = fixture("complete-socket-read"); + Map before = rowVersions(fixture); + AuthoredWorldVersionStateEvidence.Request request = request(fixture, UUID.randomUUID()); + + AuthoredWorldVersionStateEvidence actual; + try (AuthoredWorldVersionStateClient client = newClient(directory)) { + client.init(); + actual = client.read(request); + } + + AuthoredWorldVersionStateEvidence expected = + AuthoredWorldVersionStateEvidence.create( + request, + fixture.source(), + net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_DRAFT, + 1L); + assertThat(actual).isEqualTo(expected); + assertThat(actual.request()).isEqualTo(request); + assertThat(actual.sourceEvidence()).isEqualTo(fixture.source()); + assertThat(actual.request().canonicalTenantId().toString()) + .isNotEqualTo(fixture.privateTenantKey()); + assertThat(rowVersions(fixture)).isEqualTo(before); + } + + @Test + void changedSourceDigestAndForeignPersistedVersionFailClosedWithoutMutation( + @TempDir Path directory) throws Exception { + Fixture fixture = fixture("closed-source"); + Fixture otherGame = fixture("closed-foreign-version"); + Map before = rowVersions(fixture); + Map otherBefore = rowVersions(otherGame); + AuthoredWorldVersionStateEvidence.Request validRequest = request(fixture, UUID.randomUUID()); + AuthoredWorldVersionStateEvidence.Request changedDigestRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + validRequest.readRequestId(), + validRequest.canonicalTenantId(), + validRequest.worldSlug(), + validRequest.sourceOperationId(), + "sha256:" + "f".repeat(64), + validRequest.versionId()); + AuthoredWorldVersionStateEvidence.Request foreignVersionRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + validRequest.canonicalTenantId(), + validRequest.worldSlug(), + validRequest.sourceOperationId(), + validRequest.expectedSourceEvidenceDigest(), + otherGame.version().getId()); + + try (AuthoredWorldVersionStateClient client = newClient(directory)) { + client.init(); + assertStatus(() -> client.read(changedDigestRequest), Status.Code.FAILED_PRECONDITION); + assertThat(rowVersions(fixture)).isEqualTo(before); + + assertStatus(() -> client.read(foreignVersionRequest), Status.Code.FAILED_PRECONDITION); + } + + assertThat(rowVersions(fixture)).isEqualTo(before); + assertThat(rowVersions(otherGame)).isEqualTo(otherBefore); + } + + @Test + void sameReadIdentityObservesFreshCommittedLifecycleAndEpochSnapshot(@TempDir Path directory) + throws Exception { + Fixture fixture = fixture("fresh-current-snapshot"); + Map before = rowVersions(fixture); + AuthoredWorldVersionStateEvidence.Request sameRequest = request(fixture, UUID.randomUUID()); + + AuthoredWorldVersionStateEvidence first; + AuthoredWorldVersionStateEvidence current; + try (AuthoredWorldVersionStateClient client = newClient(directory)) { + client.init(); + first = client.read(sameRequest); + assertThat(rowVersions(fixture)).isEqualTo(before); + + Version changed = fixture.version(); + changed.setVersionState(VersionLifecycleState.RETIRED); + changed.setVersionStateEpoch(2L); + new TransactionTemplate(transactionManager) + .execute(status -> versionRepository.save(changed)); + Map afterCommittedChange = rowVersions(fixture); + assertThat(afterCommittedChange).containsEntry("game", before.get("game")); + assertThat(afterCommittedChange).containsEntry("binding", before.get("binding")); + assertThat(afterCommittedChange).containsEntry("source", before.get("source")); + assertThat(afterCommittedChange.get("version")).isNotEqualTo(before.get("version")); + + current = client.read(sameRequest); + assertThat(rowVersions(fixture)).isEqualTo(afterCommittedChange); + } + + assertThat(first.request()).isEqualTo(sameRequest); + assertThat(first.sourceEvidence()).isEqualTo(fixture.source()); + assertThat(first.versionState()) + .isEqualTo( + net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_DRAFT); + assertThat(first.versionStateEpoch()).isEqualTo(1L); + assertThat(current.request()).isEqualTo(sameRequest); + assertThat(current.sourceEvidence()).isEqualTo(first.sourceEvidence()); + assertThat(current.versionState()) + .isEqualTo( + net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_RETIRED); + assertThat(current.versionStateEpoch()).isEqualTo(2L); + assertThat(current.evidenceDigest()).isNotEqualTo(first.evidenceDigest()); + } + + private AuthoredWorldVersionStateClient newClient(Path directory) throws Exception { + Files.createDirectories(directory); + Path caCertificate = + writePem(directory.resolve("test-ca.crt"), "CERTIFICATE", pki.caCertificate().getEncoded()); + Path clientCertificate = + writePem( + directory.resolve("world-client.crt"), + "CERTIFICATE", + pki.worldManagementCertificate().certificate().getEncoded()); + Path clientPrivateKey = + writePem( + directory.resolve("world-client.key"), + "PRIVATE KEY", + pki.worldManagementCertificate().privateKey().getEncoded()); + + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(clientCertificate.toString()); + tls.setPrivateKey(clientPrivateKey.toString()); + tls.setCaCert(caCertificate.toString()); + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + server.getPort()); + return new AuthoredWorldVersionStateClient(endpoints, tls, new GrpcChannelFactory(), NAMESPACE); + } + + private Fixture fixture(String label) { + String privateTenantKey = "version-state-" + UUID.randomUUID().toString().substring(0, 8); + Game game = new Game(); + game.setTenantId(privateTenantKey); + game.setName("Synthetic " + label); + game.setDescription("Synthetic persisted source/version socket proof fixture"); + Game persistedGame = + new TransactionTemplate(transactionManager).execute(status -> gameRepository.save(game)); + assertThat(persistedGame).isNotNull(); + + String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + AuthoredWorldSourceEvidence source = + new TransactionTemplate(transactionManager) + .execute( + status -> + sourceRepository.register( + NAMESPACE, + UUID.randomUUID(), + persistedGame.getCanonicalTenantId(), + "tenant-" + suffix, + "world-" + suffix, + "Synthetic World 🐉")); + assertThat(source).isNotNull(); + + Version version = new Version(); + version.setTenantId(privateTenantKey); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + version.setNotes("synthetic source-qualified version-state socket proof fixture"); + Version persistedVersion = + new TransactionTemplate(transactionManager) + .execute(status -> versionRepository.save(version)); + assertThat(persistedVersion).isNotNull(); + return new Fixture( + persistedGame.getCanonicalTenantId(), privateTenantKey, source, persistedVersion); + } + + private AuthoredWorldVersionStateEvidence.Request request(Fixture fixture, UUID readRequestId) { + return new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + readRequestId, + fixture.canonicalTenantId(), + fixture.source().worldSlug(), + fixture.source().operationId(), + fixture.source().evidenceDigest(), + fixture.version().getId()); + } + + private Map rowVersions(Fixture fixture) { + return Map.of( + "game", + xmin( + "SELECT xmin::text AS xmin FROM game WHERE canonical_tenant_id = ?", + fixture.canonicalTenantId()), + "binding", + xmin( + "SELECT xmin::text AS xmin FROM game_design_tenant_slug_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + fixture.canonicalTenantId()), + "source", + xmin( + "SELECT xmin::text AS xmin FROM game_design_authored_world_source_operations " + + "WHERE operation_id = ?", + fixture.source().operationId()), + "version", + xmin("SELECT xmin::text AS xmin FROM version WHERE id = ?", fixture.version().getId())); + } + + private String xmin(String sql, Object... arguments) { + var rows = dsl.fetch(sql, arguments); + assertThat(rows).hasSize(1); + return rows.getFirst().get("xmin", String.class); + } + + private static void assertStatus(Runnable call, Status.Code expectedCode) { + Throwable failure = Assertions.catchThrowable(call::run); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expectedCode); + } + + private static Path writePem(Path path, String label, byte[] encoded) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(encoded); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + + private static TestCertificate issueLeaf( + X500Name caName, + PrivateKey caPrivateKey, + String commonName, + String workloadUri, + boolean serverCertificate) + throws Exception { + KeyPair keyPair = newRsaKeyPair(); + X500Name subject = new X500Name("CN=" + commonName + ", O=FireMUD Test"); + GeneralNames subjectAltNames = + new GeneralNames( + new GeneralName[] { + new GeneralName(GeneralName.uniformResourceIdentifier, workloadUri), + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + }); + X509Certificate certificate = + issueCertificate( + subject, + keyPair.getPublic(), + caName, + caPrivateKey, + false, + subjectAltNames, + serverCertificate); + return new TestCertificate(keyPair.getPrivate(), certificate); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerPrivateKey, + boolean ca, + GeneralNames subjectAltNames, + boolean serverCertificate) + throws Exception { + Instant now = Instant.now().minusSeconds(60L); + JcaX509v3CertificateBuilder builder = + new JcaX509v3CertificateBuilder( + issuer, + BigInteger.valueOf(CERTIFICATE_SERIAL.getAndIncrement()), + Date.from(now), + Date.from(now.plusSeconds(60L * 60L * 24L * 14L)), + subject, + publicKey); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca)); + if (ca) { + builder.addExtension( + Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); + } else { + builder.addExtension( + Extension.keyUsage, + true, + new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + serverCertificate ? KeyPurposeId.id_kp_serverAuth : KeyPurposeId.id_kp_clientAuth)); + builder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); + } + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuerPrivateKey))); + } + + private static KeyPair newRsaKeyPair() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private record Fixture( + UUID canonicalTenantId, + String privateTenantKey, + AuthoredWorldSourceEvidence source, + Version version) {} + + private record TestCertificate(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestCertificate gameDesignServerCertificate, + TestCertificate worldManagementCertificate) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java index 72c252962e..5559859a9a 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java @@ -268,6 +268,7 @@ void draftV1ScopeIsReportedBlockedAndMigrationDoesNotReadEntityDigest() { @Test void competingSameEpochCasTransitionsAllowOnlyOneWriter() throws Exception { + createGame("cas-tenant"); Version version = createVersion("cas-tenant", 1, VersionLifecycleState.PUBLISHED); CountDownLatch start = new CountDownLatch(1); try (ExecutorService executor = Executors.newFixedThreadPool(2)) { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java index a9b5f0a254..1f55ac1c60 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java @@ -2,9 +2,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.time.LocalDateTime; +import java.util.UUID; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.GameTemplate; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; @@ -102,4 +105,71 @@ void runSeedsAndReassertsCanonicalPublishedRuntimeData() throws Exception { assertThat(artifactCaptor.getValue().getLastWorkflowId()).isEqualTo("demo-seed-publish"); assertThat(artifactCaptor.getValue().getManifestHash()).isEqualTo("demo-manifest-hash"); } + + @Test + void runReusesExistingPublishedReleaseBundleWithoutSavingOrChangingItsMetadata() { + when(gameRepository.findByTenantId("1")).thenReturn(null); + when(versionRepository.findByTenantIdAndVersionNumber("1", 1)) + .thenReturn(java.util.Optional.empty()); + Version version = new Version(); + version.setId(7L); + version.setTenantId("1"); + version.setVersionNumber(1); + when(versionRepository.save(any(Version.class))).thenReturn(version); + when(templateRepository.findByTenantIdAndName("1", "Default Template")) + .thenReturn(java.util.Optional.empty()); + when(revisionRepository.findByTenantIdAndVersionIdAndRevisionKind("1", 7L, "GENERIC")) + .thenReturn(java.util.Optional.empty()); + + LocalDateTime publishedAt = LocalDateTime.of(2025, 3, 4, 5, 6, 7); + PublishedReleaseBundle existingBundle = new PublishedReleaseBundle(); + existingBundle.setId(19L); + existingBundle.setTenantId("1"); + existingBundle.setVersionId(7L); + existingBundle.setCanonicalTenantId(UUID.fromString("11111111-1111-4111-8111-111111111111")); + existingBundle.setCanonicalVersionId(UUID.fromString("22222222-2222-4222-8222-222222222222")); + existingBundle.setVersionNumber(42); + existingBundle.setAttestationSchemaVersion("stored-schema"); + existingBundle.setPublishWorkflowId("stored-workflow"); + existingBundle.setManifestHash("stored-manifest"); + existingBundle.setGenerationConfigRevision("stored-generation-revision"); + existingBundle.setRequiredManifestAssetKeysJson("[\"stored-asset\"]"); + existingBundle.setParticipantDigestsJson("[\"stored-participant\"]"); + existingBundle.setCommandDefinitionsJson("[\"stored-command\"]"); + existingBundle.setScriptOnly(true); + existingBundle.setScriptPatchVersion("stored-patch"); + existingBundle.setPublishedAt(publishedAt); + when(publishedReleaseBundleRepository.findByTenantIdAndVersionId("1", 7L)) + .thenReturn(java.util.Optional.of(existingBundle)); + when(versionAssetArtifactRepository.findByTenantIdAndVersionId("1", 7L)) + .thenReturn(java.util.Optional.empty()); + when(versionAssetArtifactRepository.save(any(VersionAssetArtifact.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + + seeder.run(new DefaultApplicationArguments(new String[] {})); + + verify(publishedReleaseBundleRepository, never()).save(any(PublishedReleaseBundle.class)); + assertThat(existingBundle.getId()).isEqualTo(19L); + assertThat(existingBundle.getCanonicalTenantId()) + .isEqualTo(UUID.fromString("11111111-1111-4111-8111-111111111111")); + assertThat(existingBundle.getCanonicalVersionId()) + .isEqualTo(UUID.fromString("22222222-2222-4222-8222-222222222222")); + assertThat(existingBundle.getVersionNumber()).isEqualTo(42); + assertThat(existingBundle.getAttestationSchemaVersion()).isEqualTo("stored-schema"); + assertThat(existingBundle.getPublishWorkflowId()).isEqualTo("stored-workflow"); + assertThat(existingBundle.getManifestHash()).isEqualTo("stored-manifest"); + assertThat(existingBundle.getGenerationConfigRevision()) + .isEqualTo("stored-generation-revision"); + assertThat(existingBundle.getRequiredManifestAssetKeysJson()).isEqualTo("[\"stored-asset\"]"); + assertThat(existingBundle.getParticipantDigestsJson()).isEqualTo("[\"stored-participant\"]"); + assertThat(existingBundle.getCommandDefinitionsJson()).isEqualTo("[\"stored-command\"]"); + assertThat(existingBundle.isScriptOnly()).isTrue(); + assertThat(existingBundle.getScriptPatchVersion()).isEqualTo("stored-patch"); + assertThat(existingBundle.getPublishedAt()).isEqualTo(publishedAt); + + ArgumentCaptor artifactCaptor = + ArgumentCaptor.forClass(VersionAssetArtifact.class); + verify(versionAssetArtifactRepository).save(artifactCaptor.capture()); + assertThat(artifactCaptor.getValue().getManifestHash()).isEqualTo("stored-manifest"); + } } 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 new file mode 100644 index 0000000000..11620c5387 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java @@ -0,0 +1,215 @@ +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.Connection; +import java.sql.DriverManager; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; + +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"); + + @Test + void newBundleUsesExactPersistedVersionAndGameIdentityAndReadsItBack() throws Exception { + try (Fixture fixture = fixture()) { + insertGame(fixture.dsl(), 7L, "tenant-key", TENANT_UUID, 7L, "tenant-key", "NEW_GAME_ROW"); + insertVersion( + fixture.dsl(), + 17L, + "tenant-key", + TENANT_UUID, + VERSION_UUID, + 7L, + "tenant-key", + "NEW_GAME_ROW"); + + PublishedReleaseBundle saved = fixture.repository().save(bundle("tenant-key", 17L)); + assertThat(saved.getId()).isNotNull(); + assertThat(saved.getCanonicalTenantId()).isEqualTo(TENANT_UUID); + assertThat(saved.getCanonicalVersionId()).isEqualTo(VERSION_UUID); + assertThat(fixture.repository().findByTenantIdAndVersionId("tenant-key", 17L).orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(saved); + + PublishedReleaseBundle stored = + fixture.repository().findByTenantIdAndVersionId("tenant-key", 17L).orElseThrow(); + assertThatThrownBy(() -> fixture.repository().save(stored)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + assertThat(fixture.repository().findByTenantIdAndVersionId("tenant-key", 17L).orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(stored); + + stored.setManifestHash("sha256:updated-test-value"); + assertThatThrownBy(() -> fixture.repository().save(stored)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + stored.setCanonicalVersionId(OTHER_UUID); + assertThatThrownBy(() -> fixture.repository().save(stored)) + .isInstanceOf(IllegalStateException.class) + .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.getCanonicalTenantId()).isEqualTo(TENANT_UUID); + assertThat(persistedAfterAttempts.getCanonicalVersionId()).isEqualTo(VERSION_UUID); + assertThat(fixture.bundleCount()).isEqualTo(1); + } + } + + @Test + void rejectsCallerSubstitutionWrongTenantUnmappedVersionAndContradictoryGameSource() + throws Exception { + try (Fixture fixture = fixture()) { + insertGame(fixture.dsl(), 7L, "tenant-key", TENANT_UUID, 7L, "tenant-key", "NEW_GAME_ROW"); + insertVersion( + fixture.dsl(), + 17L, + "tenant-key", + TENANT_UUID, + VERSION_UUID, + 7L, + "tenant-key", + "NEW_GAME_ROW"); + insertVersion(fixture.dsl(), 18L, "tenant-key", null, null, null, null, null); + insertVersion( + fixture.dsl(), + 19L, + "tenant-key", + OTHER_UUID, + UUID.randomUUID(), + 8L, + "other-key", + "NEW_GAME_ROW"); + + PublishedReleaseBundle substituted = bundle("tenant-key", 17L); + substituted.setCanonicalTenantId(OTHER_UUID); + assertThatThrownBy(() -> fixture.repository().save(substituted)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Caller-supplied canonical release identity"); + + assertThatThrownBy(() -> fixture.repository().save(bundle("other-tenant-key", 17L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No exact canonical Game Design source association"); + assertThatThrownBy(() -> fixture.repository().save(bundle("tenant-key", 18L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No exact canonical Game Design source association"); + assertThatThrownBy(() -> fixture.repository().save(bundle("tenant-key", 19L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No exact canonical Game Design source association"); + assertThat(fixture.bundleCount()).isZero(); + } + } + + private static Fixture fixture() throws Exception { + Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:published-release-bundle-" + + UUID.randomUUID() + + ";DATABASE_TO_LOWER=TRUE"); + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + dsl.execute( + "CREATE TABLE game (" + + "id BIGINT PRIMARY KEY, tenant_id VARCHAR(36) NOT NULL, " + + "canonical_tenant_id UUID NOT NULL, tenant_identity_provenance_kind VARCHAR(32), " + + "tenant_identity_source_game_id BIGINT, " + + "tenant_identity_source_legacy_tenant_id VARCHAR(36))"); + dsl.execute( + "CREATE TABLE version (" + + "id BIGINT PRIMARY KEY, tenant_id VARCHAR(36) NOT NULL, " + + "canonical_tenant_id UUID, canonical_version_id UUID, " + + "identity_source_game_row_id BIGINT, identity_source_game_tenant_key VARCHAR(36), " + + "identity_source_provenance_kind VARCHAR(32))"); + dsl.execute( + "CREATE TABLE published_release_bundle (" + + "id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, " + + "tenant_id VARCHAR(36) NOT NULL, version_id BIGINT NOT NULL, " + + "canonical_tenant_id UUID, canonical_version_id UUID, version_number INT NOT NULL, " + + "attestation_schema_version VARCHAR(16) NOT NULL, " + + "publish_workflow_id VARCHAR(64) NOT NULL, manifest_hash VARCHAR(128) NOT NULL, " + + "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, " + + "script_only BOOLEAN NOT NULL, script_patch_version VARCHAR(100), " + + "published_at TIMESTAMP NOT NULL)"); + return new Fixture(connection, dsl, new PublishedReleaseBundleRepository(dsl)); + } + + private static void insertGame( + DSLContext dsl, + long id, + String tenantId, + UUID canonicalTenantId, + long sourceGameId, + String sourceTenantKey, + String provenanceKind) { + dsl.execute( + "INSERT INTO game (id, tenant_id, canonical_tenant_id, " + + "tenant_identity_provenance_kind, tenant_identity_source_game_id, " + + "tenant_identity_source_legacy_tenant_id) VALUES (?, ?, ?, ?, ?, ?)", + id, + tenantId, + canonicalTenantId, + provenanceKind, + sourceGameId, + sourceTenantKey); + } + + private static void insertVersion( + DSLContext dsl, + long id, + String tenantId, + UUID canonicalTenantId, + UUID canonicalVersionId, + Long sourceGameId, + String sourceTenantKey, + String provenanceKind) { + dsl.execute( + "INSERT INTO version (id, tenant_id, canonical_tenant_id, canonical_version_id, " + + "identity_source_game_row_id, identity_source_game_tenant_key, " + + "identity_source_provenance_kind) VALUES (?, ?, ?, ?, ?, ?, ?)", + id, + tenantId, + canonicalTenantId, + canonicalVersionId, + sourceGameId, + sourceTenantKey, + provenanceKind); + } + + private static PublishedReleaseBundle bundle(String tenantId, long versionId) { + PublishedReleaseBundle bundle = new PublishedReleaseBundle(); + bundle.setTenantId(tenantId); + bundle.setVersionId(versionId); + bundle.setVersionNumber(1); + bundle.setAttestationSchemaVersion("1"); + bundle.setPublishWorkflowId("workflow-" + versionId); + bundle.setManifestHash("sha256:initial-test-value"); + bundle.setGenerationConfigRevision("generation-1"); + bundle.setRequiredManifestAssetKeysJson("[]"); + bundle.setParticipantDigestsJson("[]"); + bundle.setCommandDefinitionsJson("[]"); + return bundle; + } + + private record Fixture( + Connection connection, DSLContext dsl, PublishedReleaseBundleRepository repository) + implements AutoCloseable { + long bundleCount() { + return dsl.fetchCount(DSL.table(DSL.name("published_release_bundle"))); + } + + @Override + public void close() throws Exception { + connection.close(); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionRepositoryTest.java index d4ea5b74de..6dc881b34a 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionRepositoryTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.sql.DriverManager; +import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.List; import java.util.Locale; @@ -13,6 +14,9 @@ import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Result; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.jooq.tools.jdbc.MockConnection; @@ -43,6 +47,64 @@ void entityDigestBaselineVersionLockUsesConfiguredOwnerSchema() { "\"isolated_game_design_owner\".\"lock_version_for_entity_digest_baseline_migration\""); } + @Test + void entityDigestBaselineProjectionDoesNotFabricateCanonicalVersionIdentity() { + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + Field id = DSL.field(DSL.name("id"), Long.class); + Field tenantId = DSL.field(DSL.name("tenant_id"), String.class); + Field versionNumber = DSL.field(DSL.name("version_number"), Integer.class); + Field versionState = DSL.field(DSL.name("version_state"), String.class); + Field versionStateEpoch = DSL.field(DSL.name("version_state_epoch"), Long.class); + Field scriptPatchVersion = DSL.field(DSL.name("script_patch_version"), String.class); + Field baseVersionId = DSL.field(DSL.name("base_version_id"), Long.class); + Field scriptOnly = DSL.field(DSL.name("is_script_only"), Boolean.class); + Field notes = DSL.field(DSL.name("notes"), String.class); + Field createdAt = DSL.field(DSL.name("created_at"), Timestamp.class); + Field updatedAt = DSL.field(DSL.name("updated_at"), Timestamp.class); + Field[] fields = { + id, + tenantId, + versionNumber, + versionState, + versionStateEpoch, + scriptPatchVersion, + baseVersionId, + scriptOnly, + notes, + createdAt, + updatedAt + }; + Result result = resultDsl.newResult(fields); + Record row = resultDsl.newRecord(fields); + row.set(id, 17L); + row.set(tenantId, "tenant"); + row.set(versionNumber, 6); + row.set(versionState, VersionLifecycleState.DRAFT.name()); + row.set(versionStateEpoch, 2L); + row.set(scriptOnly, false); + row.set(notes, "baseline read"); + row.set(createdAt, Timestamp.valueOf(LocalDateTime.of(2026, 10, 1, 12, 0))); + row.set(updatedAt, Timestamp.valueOf(LocalDateTime.of(2026, 10, 1, 12, 1))); + result.add(row); + + MockDataProvider provider = context -> new MockResult[] {new MockResult(1, result)}; + DSLContext dsl = DSL.using(new MockConnection(provider), SQLDialect.POSTGRES); + PostgresProperties postgres = new PostgresProperties(); + postgres.setSchema("isolated_game_design_owner"); + + Version version = + new VersionRepository(dsl, postgres) + .findByTenantIdAndIdForEntityDigestBaselineMigration("tenant", 17L) + .orElseThrow(); + + assertThat(version.getId()).isEqualTo(17L); + assertThat(version.getCanonicalVersionId()).isNull(); + assertThat(version.getCanonicalTenantId()).isNull(); + assertThat(version.getIdentitySourceGameRowId()).isNull(); + assertThat(version.getIdentitySourceGameTenantKey()).isNull(); + assertThat(version.getIdentitySourceProvenanceKind()).isNull(); + } + @Test void entityDigestBaselineVersionLockRejectsMissingOrBlankOwnerSchemaWithoutQuery() { AtomicInteger queryCount = new AtomicInteger(); @@ -79,6 +141,11 @@ void scriptPatchPublicationLookupUsesExactRetainedScopeAndLeavesAmbiguityVisible "CREATE TABLE \"version\" (" + "\"id\" BIGINT PRIMARY KEY, " + "\"tenant_id\" VARCHAR(36) NOT NULL, " + + "\"canonical_version_id\" UUID, " + + "\"canonical_tenant_id\" UUID, " + + "\"identity_source_game_row_id\" BIGINT, " + + "\"identity_source_game_tenant_key\" VARCHAR(36), " + + "\"identity_source_provenance_kind\" VARCHAR(32), " + "\"version_number\" INT NOT NULL, " + "\"version_state\" VARCHAR(32) NOT NULL, " + "\"version_state_epoch\" BIGINT NOT NULL, " diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java new file mode 100644 index 0000000000..63a95db34f --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java @@ -0,0 +1,196 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateResponse; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import org.junit.jupiter.api.Test; + +class AuthoredWorldVersionStateGrpcServiceTest { + private static final String NAMESPACE = "test"; + private static final UUID READ_REQUEST_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID REGISTRATION_REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + + @Test + void exactWorldPeerMayReadAndReceivesClosedEvidence() { + AuthoredWorldVersionStateService service = mock(AuthoredWorldVersionStateService.class); + var request = request(); + var evidence = + AuthoredWorldVersionStateEvidence.create( + request, sourceEvidence(), VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, 7L); + when(service.read(request)).thenReturn(evidence); + var handler = new AuthoredWorldVersionStateGrpcService(service, NAMESPACE); + TestObserver observer = new TestObserver<>(); + + withPeer( + peer(NAMESPACE, "world-management-service"), + () -> + handler.getAuthoredWorldVersionState( + AuthoredWorldVersionStateGrpcCodec.toRequest(request), observer)); + + assertThat(observer.error).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(AuthoredWorldVersionStateGrpcCodec.fromResponse(request, observer.value)) + .isEqualTo(evidence); + verify(service).read(request); + } + + @Test + void exactPeerGuardRunsBeforeMalformedRequestDecodeOrOwnerAccess() { + AuthoredWorldVersionStateService service = mock(AuthoredWorldVersionStateService.class); + var handler = new AuthoredWorldVersionStateGrpcService(service, NAMESPACE); + GetAuthoredWorldVersionStateRequest malformed = + GetAuthoredWorldVersionStateRequest.newBuilder() + .setSchemaVersion(99) + .setReadRequestId("not-a-uuid") + .build(); + + TestObserver absent = new TestObserver<>(); + handler.getAuthoredWorldVersionState(malformed, absent); + assertStatus(absent, Status.Code.PERMISSION_DENIED); + + TestObserver wrongService = new TestObserver<>(); + withPeer( + peer(NAMESPACE, "game-session-service"), + () -> handler.getAuthoredWorldVersionState(malformed, wrongService)); + assertStatus(wrongService, Status.Code.PERMISSION_DENIED); + + TestObserver wrongNamespace = new TestObserver<>(); + withPeer( + peer("other", "world-management-service"), + () -> handler.getAuthoredWorldVersionState(malformed, wrongNamespace)); + assertStatus(wrongNamespace, Status.Code.PERMISSION_DENIED); + + verifyNoInteractions(service); + } + + @Test + void exactPeerGetsInvalidArgumentBeforeAnyOwnerReadForMalformedClosedRequest() { + AuthoredWorldVersionStateService service = mock(AuthoredWorldVersionStateService.class); + var handler = new AuthoredWorldVersionStateGrpcService(service, NAMESPACE); + GetAuthoredWorldVersionStateRequest malformed = + GetAuthoredWorldVersionStateRequest.newBuilder() + .setSchemaVersion(2) + .setTargetNamespace(NAMESPACE) + .setReadRequestId(READ_REQUEST_ID.toString()) + .build(); + TestObserver observer = new TestObserver<>(); + + withPeer( + peer(NAMESPACE, "world-management-service"), + () -> handler.getAuthoredWorldVersionState(malformed, observer)); + + assertStatus(observer, Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(service); + } + + private static void assertStatus(TestObserver observer, Status.Code expectedCode) { + assertThat(observer.error).isNotNull(); + assertThat(observer.error.type()).isEqualTo(StatusRuntimeException.class); + assertThat(observer.error.code()).isEqualTo(expectedCode); + } + + private static void withPeer(GrpcPeerIdentity peer, Runnable action) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + action.run(); + } finally { + context.detach(previous); + } + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static AuthoredWorldVersionStateEvidence.Request request() { + AuthoredWorldSourceEvidence source = sourceEvidence(); + return new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + READ_REQUEST_ID, + TENANT_ID, + "cafe-coast", + SOURCE_OPERATION_ID, + source.evidenceDigest(), + 19L); + } + + private static AuthoredWorldSourceEvidence sourceEvidence() { + String displayName = "Café 🐉"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION_REQUEST_ID, TENANT_ID, "tenant-one", "cafe-coast", displayName); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + "tenant-one", + "cafe-coast", + displayName, + 42L, + "game-owner-tenant", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + "tenant-one", + "cafe-coast", + displayName, + 42L, + "game-owner-tenant", + "NEW_GAME_ROW")); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class TestObserver implements StreamObserver { + private T value; + private ErrorEvidence error; + private boolean completed; + + @Override + public void onNext(T next) { + value = next; + } + + @Override + public void onError(Throwable failure) { + error = new ErrorEvidence(failure.getClass(), Status.fromThrowable(failure).getCode()); + } + + @Override + public void onCompleted() { + completed = true; + } + + private record ErrorEvidence(Class type, Status.Code code) {} + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateMtlsTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateMtlsTest.java new file mode 100644 index 0000000000..8669fc5448 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateMtlsTest.java @@ -0,0 +1,752 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.ForwardingServerCall.SimpleForwardingServerCall; +import io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import java.io.IOException; +import java.math.BigInteger; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.Base64; +import java.util.Date; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.AuthoredWorldSourceReceipt; +import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateResponse; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.test.TlsTestSupport; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * Physical socket proof for the source-qualified current version-state read boundary. + * + *

The production peer extractor, standalone gRPC handler, and shared client run over ephemeral + * mTLS sockets. The version-state producer is mocked and returns a complete digest-valid receipt; + * this suite does not prove the producer's owner snapshot, database state, World mutation, or + * publication fence. + */ +class AuthoredWorldVersionStateMtlsTest { + private static final String NAMESPACE = "test"; + private static final String METHOD = + "gamedesign.v1.GameDesignService/GetAuthoredWorldVersionState"; + private static final UUID REGISTRATION_REQUEST_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID TENANT_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID READ_REQUEST_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1L); + private static final AuthoredWorldSourceEvidence SOURCE_EVIDENCE = sourceEvidence(); + private static final AuthoredWorldVersionStateEvidence.Request READ_REQUEST = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + READ_REQUEST_ID, + TENANT_ID, + "harbor-world", + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE.evidenceDigest(), + 17L); + private static final AuthoredWorldVersionStateEvidence VERSION_STATE_EVIDENCE = + AuthoredWorldVersionStateEvidence.create( + READ_REQUEST, SOURCE_EVIDENCE, VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, 9L); + private static TestPki pki; + + private AuthoredWorldVersionStateService versionStateService; + private Server server; + private AtomicReference responseMutation; + + @BeforeAll + static void generateEphemeralPki() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + KeyPair caKeyPair = newRsaKeyPair(); + X500Name caName = new X500Name("CN=Authored Version State Test CA, O=FireMUD Test"); + X509Certificate caCertificate = + issueCertificate( + caName, caKeyPair.getPublic(), caName, caKeyPair.getPrivate(), true, null, false); + pki = + new TestPki( + caCertificate, + issueLeaf( + caName, + caKeyPair.getPrivate(), + "game-design-service", + "spiffe://firemud/ns/test/sa/game-design-service", + true), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "wrong-game-design-server-workload", + "spiffe://firemud/ns/test/sa/world-management-service", + true), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "wrong-game-design-server-namespace", + "spiffe://firemud/ns/other-test/sa/game-design-service", + true), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "world-management-service", + "spiffe://firemud/ns/test/sa/world-management-service", + false), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "game-session-service", + "spiffe://firemud/ns/test/sa/game-session-service", + false), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "wrong-namespace-world-management-service", + "spiffe://firemud/ns/other-test/sa/world-management-service", + false), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "trusted-certificate-without-workload-uri", + null, + false)); + } + + @BeforeEach + void startPhysicalReceiver() throws Exception { + versionStateService = mock(AuthoredWorldVersionStateService.class); + when(versionStateService.read(READ_REQUEST)).thenReturn(VERSION_STATE_EVIDENCE); + responseMutation = new AtomicReference<>(ResponseMutation.NONE); + server = startReceiver(pki.gameDesignServerCertificate()); + } + + @AfterEach + void stopPhysicalReceiver() throws Exception { + if (server != null) { + stopServer(server); + server = null; + } + } + + @Test + void exactSameNamespaceWorldWorkloadReceivesCompleteVersionStateEvidenceOverSocket( + @TempDir Path directory) throws Exception { + AuthoredWorldVersionStateClient client = + newSharedClient(directory, server, pki.worldManagementCertificate()); + try { + client.init(); + + assertThat(client.read(READ_REQUEST)).isEqualTo(VERSION_STATE_EVIDENCE); + } finally { + client.close(); + } + + verify(versionStateService).read(READ_REQUEST); + } + + @Test + void wrongServiceNamespaceAndSharedCertificatesAreRejectedBeforeProducerRead() throws Exception { + for (TestCertificate clientCertificate : + List.of( + pki.gameSessionCertificate(), + pki.wrongNamespaceWorldManagementCertificate(), + pki.noWorkloadUriCertificate())) { + ManagedChannel channel = channel(server, clientCertificate); + try { + assertStatus( + () -> versionStateStub(channel).getAuthoredWorldVersionState(wireReadRequest()), + Status.Code.PERMISSION_DENIED); + } finally { + stopChannel(channel); + } + } + + verifyNoInteractions(versionStateService); + } + + @Test + void missingClientCertificateCannotSupplyAnAuthenticatedPeerToProducer() throws Exception { + ManagedChannel channel = channel(server, null); + try { + assertTlsDenied( + () -> versionStateStub(channel).getAuthoredWorldVersionState(wireReadRequest()), METHOD); + } finally { + stopChannel(channel); + } + + verifyNoInteractions(versionStateService); + } + + @Test + void unknownClosedRequestFieldsAreRejectedBeforeProducerRead() throws Exception { + ManagedChannel channel = channel(server, pki.worldManagementCertificate()); + GetAuthoredWorldVersionStateRequest unknownFieldRequest = + wireReadRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + try { + assertStatus( + () -> versionStateStub(channel).getAuthoredWorldVersionState(unknownFieldRequest), + Status.Code.INVALID_ARGUMENT); + } finally { + stopChannel(channel); + } + + verifyNoInteractions(versionStateService); + } + + @Test + void worldClientRejectsWrongSameCaServerIdentityBeforeSendingAnyRpc(@TempDir Path directory) + throws Exception { + for (TestCertificate serverCertificate : + List.of(pki.wrongServerWorkloadCertificate(), pki.wrongServerNamespaceCertificate())) { + InboundRpcCapture inboundRpcCapture = new InboundRpcCapture(); + Server wrongIdentityServer = startReceiver(serverCertificate, inboundRpcCapture); + AuthoredWorldVersionStateClient client = + newSharedClient( + directory.resolve(UUID.randomUUID().toString()), + wrongIdentityServer, + pki.worldManagementCertificate()); + try { + client.init(); + assertServerPeerRefused(() -> client.read(READ_REQUEST)); + inboundRpcCapture.assertNoInboundRequests(); + } finally { + client.close(); + stopServer(wrongIdentityServer); + } + } + + verifyNoInteractions(versionStateService); + } + + @Test + void worldClientRejectsMismatchedCompleteEvidenceOverPhysicalSocket(@TempDir Path directory) + throws Exception { + AuthoredWorldVersionStateClient client = + newSharedClient(directory, server, pki.worldManagementCertificate()); + try { + client.init(); + + responseMutation.set(ResponseMutation.CHANGE_READ_REQUEST_ID); + assertClientCodecRejected( + () -> client.read(READ_REQUEST), "does not echo the exact read request"); + + responseMutation.set(ResponseMutation.CHANGE_SOURCE_DISPLAY_NAME); + assertClientCodecRejected( + () -> client.read(READ_REQUEST), "Request digest does not match the registration tuple"); + + responseMutation.set(ResponseMutation.CHANGE_SOURCE_OPERATION_ID_WITH_VALID_DIGEST); + assertClientCodecRejected( + () -> client.read(READ_REQUEST), "does not match the exact version-state request"); + + responseMutation.set(ResponseMutation.CHANGE_VERSION_STATE_EPOCH); + assertClientCodecRejected( + () -> client.read(READ_REQUEST), + "evidence digest does not match the exact current-state tuple"); + + responseMutation.set(ResponseMutation.ADD_UNKNOWN_SOURCE_FIELD); + assertClientCodecRejected( + () -> client.read(READ_REQUEST), + "AuthoredWorldSourceReceipt contains unsupported fields"); + } finally { + client.close(); + } + + verify(versionStateService, times(5)).read(READ_REQUEST); + } + + private Server startReceiver(TestCertificate serverCertificate) throws Exception { + return startReceiver(serverCertificate, null); + } + + private Server startReceiver( + TestCertificate serverCertificate, InboundRpcCapture inboundRpcCapture) throws Exception { + AuthoredWorldVersionStateGrpcService service = + new AuthoredWorldVersionStateGrpcService(versionStateService, NAMESPACE); + ServerInterceptor[] interceptors = + inboundRpcCapture == null + ? new ServerInterceptor[] { + responseMutationInterceptor(responseMutation), new GrpcPeerIdentityInterceptor() + } + : new ServerInterceptor[] { + inboundRpcCapture, + responseMutationInterceptor(responseMutation), + new GrpcPeerIdentityInterceptor() + }; + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverCertificate.privateKey(), serverCertificate.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, interceptors)) + .build() + .start(); + } + + private AuthoredWorldVersionStateClient newSharedClient( + Path directory, Server receiver, TestCertificate clientCertificate) throws Exception { + Files.createDirectories(directory); + Path caCertificate = + writePem(directory.resolve("test-ca.crt"), "CERTIFICATE", pki.caCertificate().getEncoded()); + Path certificate = + writePem( + directory.resolve("client.crt"), + "CERTIFICATE", + clientCertificate.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve("client.key"), + "PRIVATE KEY", + clientCertificate.privateKey().getEncoded()); + + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(certificate.toString()); + tls.setPrivateKey(privateKey.toString()); + tls.setCaCert(caCertificate.toString()); + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + receiver.getPort()); + return new AuthoredWorldVersionStateClient(endpoints, tls, new GrpcChannelFactory(), NAMESPACE); + } + + private ManagedChannel channel(Server receiver, TestCertificate clientCertificate) + throws Exception { + var sslContextBuilder = GrpcSslContexts.forClient().trustManager(pki.caCertificate()); + if (clientCertificate != null) { + sslContextBuilder.keyManager(clientCertificate.privateKey(), clientCertificate.certificate()); + } + return NettyChannelBuilder.forAddress(new InetSocketAddress("127.0.0.1", receiver.getPort())) + .sslContext(sslContextBuilder.build()) + .build(); + } + + private static GameDesignServiceGrpc.GameDesignServiceBlockingStub versionStateStub( + ManagedChannel channel) { + return GameDesignServiceGrpc.newBlockingStub(channel).withDeadlineAfter(3, TimeUnit.SECONDS); + } + + private static GetAuthoredWorldVersionStateRequest wireReadRequest() { + return AuthoredWorldVersionStateGrpcCodec.toRequest(READ_REQUEST); + } + + private static ServerInterceptor responseMutationInterceptor( + AtomicReference pendingMutation) { + return new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + ServerCall forwardingCall = + new SimpleForwardingServerCall<>(call) { + @Override + public void sendMessage(RespT message) { + super.sendMessage( + mutateResponse(message, pendingMutation.getAndSet(ResponseMutation.NONE))); + } + }; + return next.startCall(forwardingCall, headers); + } + }; + } + + @SuppressWarnings("unchecked") + private static Response mutateResponse(Response response, ResponseMutation mutation) { + if (mutation == ResponseMutation.NONE) { + return response; + } + if (!(response instanceof GetAuthoredWorldVersionStateResponse versionStateResponse)) { + throw new IllegalStateException( + "Response mutation does not match the version-state read RPC"); + } + var evidence = versionStateResponse.getEvidence(); + return (Response) + switch (mutation) { + case CHANGE_READ_REQUEST_ID -> + versionStateResponse.toBuilder() + .setEvidence( + evidence.toBuilder().setReadRequestId("55555555-5555-4555-8555-555555555555")) + .build(); + case CHANGE_SOURCE_DISPLAY_NAME -> + versionStateResponse.toBuilder() + .setEvidence( + evidence.toBuilder() + .setSourceEvidence( + evidence.getSourceEvidence().toBuilder() + .setWorldDisplayName("Changed display name"))) + .build(); + case CHANGE_SOURCE_OPERATION_ID_WITH_VALID_DIGEST -> + versionStateResponse.toBuilder() + .setEvidence( + evidence.toBuilder() + .setSourceEvidence( + sourceReceiptWithChangedOperationId(evidence.getSourceEvidence()))) + .build(); + case CHANGE_VERSION_STATE_EPOCH -> + versionStateResponse.toBuilder() + .setEvidence(evidence.toBuilder().setVersionStateEpoch(10L)) + .build(); + case ADD_UNKNOWN_SOURCE_FIELD -> + versionStateResponse.toBuilder() + .setEvidence( + evidence.toBuilder() + .setSourceEvidence( + evidence.getSourceEvidence().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, + UnknownFieldSet.Field.newBuilder() + .addVarint(1) + .build()) + .build()))) + .build(); + case NONE -> versionStateResponse; + }; + } + + private static void assertStatus(Runnable call, Status.Code expectedCode) { + Throwable failure = catchFailure(call); + assertThat(failure) + .as("RPC should fail with %s: %s", expectedCode, diagnostics(failure)) + .isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()) + .as("RPC denial evidence: %s", diagnostics(failure)) + .isEqualTo(expectedCode); + } + + private static AuthoredWorldSourceReceipt sourceReceiptWithChangedOperationId( + AuthoredWorldSourceReceipt sourceReceipt) { + UUID changedOperationId = UUID.fromString("55555555-5555-4555-8555-555555555555"); + String changedEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + sourceReceipt.getTargetNamespace(), + UUID.fromString(sourceReceipt.getRegistrationRequestId()), + changedOperationId, + sourceReceipt.getRequestDigest(), + UUID.fromString(sourceReceipt.getCanonicalTenantId()), + sourceReceipt.getTenantSlug(), + sourceReceipt.getWorldSlug(), + sourceReceipt.getWorldDisplayName(), + sourceReceipt.getSourceGameRowId(), + sourceReceipt.getSourceGameTenantKey(), + sourceReceipt.getProvenanceKind()); + return sourceReceipt.toBuilder() + .setOperationId(changedOperationId.toString()) + .setEvidenceDigest(changedEvidenceDigest) + .build(); + } + + private static void assertServerPeerRefused(Runnable call) { + Throwable failure = catchFailure(call); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(Status.fromThrowable(failure).getDescription()) + .contains("exact authenticated server workload identity"); + } + + private static void assertClientCodecRejected(Runnable call, String expectedEvidence) { + Throwable failure = catchFailure(call); + assertThat(failure).isInstanceOf(IllegalStateException.class); + assertThat(diagnostics(failure)).contains(expectedEvidence); + } + + private static void assertTlsDenied(Runnable call, String method) { + Throwable failure = catchFailure(call); + assertThat(failure) + .as( + "%s must fail with client-certificate handshake evidence: %s", + method, diagnostics(failure)) + .isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()) + .as( + "%s must fail at TLS rather than by application timeout: %s", + method, diagnostics(failure)) + .isEqualTo(Status.Code.UNAVAILABLE); + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as( + "%s cause chain must identify client-certificate rejection: %s", + method, diagnostics(failure)) + .isTrue(); + } + + private static AuthoredWorldSourceEvidence sourceEvidence() { + String tenantSlug = "firemud"; + String worldSlug = "harbor-world"; + String worldDisplayName = "Harbor World"; + String sourceGameTenantKey = "legacy-game-17"; + String provenanceKind = "NEW_GAME_ROW"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION_REQUEST_ID, TENANT_ID, tenantSlug, worldSlug, worldDisplayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + tenantSlug, + worldSlug, + worldDisplayName, + 17L, + sourceGameTenantKey, + provenanceKind); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + tenantSlug, + worldSlug, + worldDisplayName, + 17L, + sourceGameTenantKey, + provenanceKind, + evidenceDigest); + } + + private static Path writePem(Path path, String label, byte[] encoded) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(encoded); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + + private static void stopServer(Server server) throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + private static void stopChannel(ManagedChannel channel) throws InterruptedException { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + private static Throwable catchFailure(Runnable action) { + try { + action.run(); + return null; + } catch (Throwable throwable) { + return throwable; + } + } + + private static String diagnostics(Throwable throwable) { + if (throwable == null) { + return "RPC unexpectedly completed"; + } + StringBuilder result = new StringBuilder(); + for (Throwable current = throwable; current != null; current = current.getCause()) { + if (!result.isEmpty()) { + result.append(" <- "); + } + result.append(current.getClass().getName()).append(": ").append(current.getMessage()); + } + return result.toString(); + } + + private static TestCertificate issueLeaf( + X500Name caName, + PrivateKey caPrivateKey, + String commonName, + String workloadUri, + boolean serverCertificate) + throws Exception { + KeyPair keyPair = newRsaKeyPair(); + X500Name subject = new X500Name("CN=" + commonName + ", O=FireMUD Test"); + GeneralName[] subjectAltNames = + workloadUri == null + ? new GeneralName[] { + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + } + : new GeneralName[] { + new GeneralName(GeneralName.uniformResourceIdentifier, workloadUri), + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + }; + X509Certificate certificate = + issueCertificate( + subject, + keyPair.getPublic(), + caName, + caPrivateKey, + false, + new GeneralNames(subjectAltNames), + serverCertificate); + return new TestCertificate(keyPair.getPrivate(), certificate); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerPrivateKey, + boolean ca, + GeneralNames subjectAltNames, + boolean serverCertificate) + throws Exception { + Instant now = Instant.now().minusSeconds(60L); + JcaX509v3CertificateBuilder builder = + new JcaX509v3CertificateBuilder( + issuer, + BigInteger.valueOf(CERTIFICATE_SERIAL.getAndIncrement()), + Date.from(now), + Date.from(now.plusSeconds(60L * 60L * 24L * 14L)), + subject, + publicKey); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca)); + if (ca) { + builder.addExtension( + Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); + } else { + builder.addExtension( + Extension.keyUsage, + true, + new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + serverCertificate ? KeyPurposeId.id_kp_serverAuth : KeyPurposeId.id_kp_clientAuth)); + builder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); + } + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuerPrivateKey))); + } + + private static KeyPair newRsaKeyPair() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private static final class InboundRpcCapture implements ServerInterceptor { + private final AtomicInteger rpcCount = new AtomicInteger(); + private final AtomicInteger metadataCount = new AtomicInteger(); + private final AtomicInteger requestMessageCount = new AtomicInteger(); + private final AtomicReference methodName = new AtomicReference<>(); + private final AtomicReference requestMetadata = new AtomicReference<>(); + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + rpcCount.incrementAndGet(); + metadataCount.incrementAndGet(); + methodName.set(call.getMethodDescriptor().getFullMethodName()); + requestMetadata.set(headers); + ServerCall.Listener listener = next.startCall(call, headers); + return new SimpleForwardingServerCallListener<>(listener) { + @Override + public void onMessage(ReqT message) { + requestMessageCount.incrementAndGet(); + super.onMessage(message); + } + }; + } + + private void assertNoInboundRequests() { + assertThat(rpcCount.get()).isZero(); + assertThat(metadataCount.get()).isZero(); + assertThat(requestMessageCount.get()).isZero(); + assertThat(methodName.get()).isNull(); + assertThat(requestMetadata.get()).isNull(); + } + } + + private record TestCertificate(PrivateKey privateKey, X509Certificate certificate) {} + + private enum ResponseMutation { + NONE, + CHANGE_READ_REQUEST_ID, + CHANGE_SOURCE_DISPLAY_NAME, + CHANGE_SOURCE_OPERATION_ID_WITH_VALID_DIGEST, + CHANGE_VERSION_STATE_EPOCH, + ADD_UNKNOWN_SOURCE_FIELD + } + + private record TestPki( + X509Certificate caCertificate, + TestCertificate gameDesignServerCertificate, + TestCertificate wrongServerWorkloadCertificate, + TestCertificate wrongServerNamespaceCertificate, + TestCertificate worldManagementCertificate, + TestCertificate gameSessionCertificate, + TestCertificate wrongNamespaceWorldManagementCertificate, + TestCertificate noWorkloadUriCertificate) {} +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateServiceTest.java new file mode 100644 index 0000000000..5ec7448976 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateServiceTest.java @@ -0,0 +1,188 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository.AuthoredWorldVersionStateSnapshot; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; + +class AuthoredWorldVersionStateServiceTest { + private static final String NAMESPACE = "test"; + private static final UUID READ_REQUEST_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID REGISTRATION_REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + + @Test + void readsCompleteSourceAndVersionInsideFreshReadOnlyRepeatableReadTransaction() { + RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + GameAuthoredWorldSourceRepository repository = mock(GameAuthoredWorldSourceRepository.class); + AuthoredWorldSourceEvidence source = sourceEvidence(); + when(repository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + TENANT_ID, + "cafe-coast", + SOURCE_OPERATION_ID, + source.evidenceDigest(), + 19L)) + .thenReturn( + Optional.of( + new AuthoredWorldVersionStateSnapshot( + source, + net.firedevops.firemud.gamedesign.model.VersionLifecycleState.PUBLISHED, + 7L))); + AuthoredWorldVersionStateService service = + new AuthoredWorldVersionStateService(transactionManager, repository); + + AuthoredWorldVersionStateEvidence evidence = service.read(request(source.evidenceDigest())); + + assertThat(evidence.sourceEvidence()).isEqualTo(source); + assertThat(evidence.versionState()) + .isEqualTo(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED); + assertThat(evidence.versionStateEpoch()).isEqualTo(7L); + assertThat(transactionManager.definition).isNotNull(); + assertThat(transactionManager.definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(transactionManager.definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThat(transactionManager.definition.isReadOnly()).isTrue(); + verify(repository) + .readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + TENANT_ID, + "cafe-coast", + SOURCE_OPERATION_ID, + source.evidenceDigest(), + 19L); + } + + @Test + void missingExactSourceOrVersionFailsClosed() { + RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + GameAuthoredWorldSourceRepository repository = mock(GameAuthoredWorldSourceRepository.class); + when(repository.readVersionStateSnapshot( + eq(NAMESPACE), + eq(READ_REQUEST_ID), + eq(TENANT_ID), + eq("cafe-coast"), + eq(SOURCE_OPERATION_ID), + any(String.class), + eq(19L))) + .thenReturn(Optional.empty()); + AuthoredWorldVersionStateService service = + new AuthoredWorldVersionStateService(transactionManager, repository); + + assertThatThrownBy(() -> service.read(request("sha256:" + "a".repeat(64)))) + .isInstanceOf(AuthoredWorldVersionStateService.NotFoundException.class) + .hasMessageContaining("exact requested owner tuple"); + } + + @Test + void repositoryOwnerConsistencyFailuresDoNotBecomeEvidence() { + RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + GameAuthoredWorldSourceRepository repository = mock(GameAuthoredWorldSourceRepository.class); + when(repository.readVersionStateSnapshot( + eq(NAMESPACE), + eq(READ_REQUEST_ID), + eq(TENANT_ID), + eq("cafe-coast"), + eq(SOURCE_OPERATION_ID), + any(String.class), + eq(19L))) + .thenThrow( + new GameAuthoredWorldSourceRepository.InvalidSourceEvidenceException( + "source binding changed")); + AuthoredWorldVersionStateService service = + new AuthoredWorldVersionStateService(transactionManager, repository); + + assertThatThrownBy(() -> service.read(request("sha256:" + "a".repeat(64)))) + .isInstanceOf(GameAuthoredWorldSourceRepository.InvalidSourceEvidenceException.class) + .hasMessageContaining("source binding changed"); + } + + private static AuthoredWorldVersionStateEvidence.Request request(String sourceDigest) { + return new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + READ_REQUEST_ID, + TENANT_ID, + "cafe-coast", + SOURCE_OPERATION_ID, + sourceDigest, + 19L); + } + + private static AuthoredWorldSourceEvidence sourceEvidence() { + String displayName = "Café 🐉"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION_REQUEST_ID, TENANT_ID, "tenant-one", "cafe-coast", displayName); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + "tenant-one", + "cafe-coast", + displayName, + 42L, + "game-owner-tenant", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + "tenant-one", + "cafe-coast", + displayName, + 42L, + "game-owner-tenant", + "NEW_GAME_ROW")); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class RecordingTransactionManager + extends AbstractPlatformTransactionManager { + private TransactionDefinition definition; + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition transactionDefinition) { + definition = transactionDefinition; + } + + @Override + protected void doCommit(DefaultTransactionStatus status) {} + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java index 3319159b0e..ac9275bd14 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 @@ -96,7 +96,9 @@ void launchDescriptorRejectsJwtOnlyInternalServiceIdentity() { "genrev-1", false, null, - java.time.LocalDateTime.parse("2026-04-14T12:00:00"))); + java.time.LocalDateTime.parse("2026-04-14T12:00:00"), + null, + null)); 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 ad63e257bf..c0553dea2b 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 @@ -191,7 +191,9 @@ void getPublishedReleaseBundleReturnsCanonicalAttestation() { "genrev-1", false, null, - LocalDateTime.parse("2026-04-14T12:00:00"))); + LocalDateTime.parse("2026-04-14T12:00:00"), + UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"))); AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { @@ -212,10 +214,84 @@ void getPublishedReleaseBundleReturnsCanonicalAttestation() { List.of("{\"commandId\":\"block\",\"schemaVersion\":1}"), ref.get().getBundle().getCommandDefinitionsList()); assertEquals(1, ref.get().getBundle().getParticipantDigestsCount()); + assertEquals( + "67d7b75b-42d1-4ac6-9572-684c5e633cda", ref.get().getBundle().getCanonicalTenantId()); + assertEquals( + "c472ebd1-56d8-49df-b8fa-85963dd940f8", ref.get().getBundle().getCanonicalVersionId()); assertEquals("publish", ref.get().getBundle().getWorkflowFamily()); assertEquals("TEMPORAL_DISABLED", ref.get().getBundle().getWorkflowStatus()); } + @Test + void getPublishedReleaseBundleRejectsPartialCanonicalIdentity() { + Mockito.when(versionService.getPublishedReleaseBundle("tenant-1", 7L)) + .thenReturn( + new PublishedReleaseBundleDto( + 11L, + "tenant-1", + 7L, + 8, + "v1", + "workflow-1", + "abc123", + List.of("manifest.json"), + List.of(), + "genrev-1", + false, + null, + LocalDateTime.parse("2026-04-14T12:00:00"), + UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), + null)); + AtomicReference ref = new AtomicReference<>(); + + try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { + service.getPublishedReleaseBundle( + GetPublishedReleaseBundleRequest.newBuilder() + .setTenantId("tenant-1") + .setVersionId(7L) + .build(), + observerFor(ref)); + } + + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + assertEquals(false, ref.get().hasBundle()); + } + + @Test + void getPublishedReleaseBundleRejectsNilCanonicalIdentity() { + Mockito.when(versionService.getPublishedReleaseBundle("tenant-1", 7L)) + .thenReturn( + new PublishedReleaseBundleDto( + 11L, + "tenant-1", + 7L, + 8, + "v1", + "workflow-1", + "abc123", + List.of("manifest.json"), + List.of(), + "genrev-1", + false, + null, + LocalDateTime.parse("2026-04-14T12:00:00"), + UUID.fromString("00000000-0000-0000-0000-000000000000"), + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"))); + AtomicReference ref = new AtomicReference<>(); + + try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { + service.getPublishedReleaseBundle( + GetPublishedReleaseBundleRequest.newBuilder() + .setTenantId("tenant-1") + .setVersionId(7L) + .build(), + observerFor(ref)); + } + + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + assertEquals(false, ref.get().hasBundle()); + } + @Test void getPublishedScriptPatchVersionReturnsPublicationReadModel() { Mockito.when(versionService.getPublishedScriptPatchVersion("tenant-1", 7L, "patch-1")) @@ -1065,7 +1141,9 @@ void getPublishedReleaseBundleRejectsUnsupportedSchema() { "genrev-1", false, null, - LocalDateTime.parse("2026-04-14T12:00:00"))); + LocalDateTime.parse("2026-04-14T12:00:00"), + null, + null)); AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { 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 fe1abaf97c..64a014f89a 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 @@ -657,7 +657,9 @@ private PublishedReleaseBundleDto releaseBundle( "genrev-1", false, null, - LocalDateTime.now()); + LocalDateTime.now(), + null, + null); } @SuppressWarnings("removal") 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 22cfa90253..7339e9fd47 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 @@ -3,6 +3,7 @@ import static net.firedevops.firemud.gamedesign.service.impl.CommandDefinitionFixtures.commandDefinition; import static net.firedevops.firemud.gamedesign.service.impl.CommandDefinitionFixtures.validCommandDefinition; 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.when; @@ -10,13 +11,16 @@ import java.time.LocalDateTime; import java.util.List; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.entity.Revision; +import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.RevisionRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -27,6 +31,7 @@ class PublishedReleaseBundleServiceImplTest { @Mock private PublishedReleaseBundleRepository repository; @Mock private RevisionRepository revisionRepository; + @Mock private VersionRepository versionRepository; private PublishedReleaseBundleServiceImpl service; @@ -34,7 +39,14 @@ class PublishedReleaseBundleServiceImplTest { void setUp() { MockitoAnnotations.openMocks(this); service = - new PublishedReleaseBundleServiceImpl(repository, revisionRepository, new ObjectMapper()); + new PublishedReleaseBundleServiceImpl( + repository, revisionRepository, versionRepository, new ObjectMapper()); + Version source = new Version(); + source.setId(7L); + source.setTenantId("tenant-1"); + source.setCanonicalTenantId(UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda")); + source.setCanonicalVersionId(UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8")); + when(versionRepository.findByTenantIdAndId("tenant-1", 7L)).thenReturn(Optional.of(source)); } @Test @@ -85,6 +97,37 @@ void createFullVersionBundlePersistsImmutableAttestation() { assertEquals(1, dto.participantDigests().size()); assertEquals(List.of(validCommandDefinition()), dto.commandDefinitions()); assertEquals("v1", dto.attestationSchemaVersion()); + assertEquals(sourceIdentity().getCanonicalTenantId(), dto.canonicalTenantId()); + assertEquals(sourceIdentity().getCanonicalVersionId(), dto.canonicalVersionId()); + org.mockito.Mockito.verify(repository) + .save( + org.mockito.ArgumentMatchers.argThat( + saved -> + sourceIdentity().getCanonicalTenantId().equals(saved.getCanonicalTenantId()) + && sourceIdentity() + .getCanonicalVersionId() + .equals(saved.getCanonicalVersionId()))); + } + + @Test + void retainedBundleWithoutCanonicalIdentityStaysAbsent() { + PublishedReleaseBundle retained = new PublishedReleaseBundle(); + retained.setId(11L); + retained.setTenantId("tenant-1"); + retained.setVersionId(7L); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(retained)); + + var dto = service.findPublishedReleaseBundle("tenant-1", 7L).orElseThrow(); + + assertNull(dto.canonicalTenantId()); + assertNull(dto.canonicalVersionId()); + } + + private Version sourceIdentity() { + Version version = new Version(); + version.setCanonicalTenantId(UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda")); + version.setCanonicalVersionId(UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8")); + return version; } @Test 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 ef89325c46..c08cd8be10 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 @@ -127,7 +127,9 @@ void repairFailsClosedWhenManifestHashDrifts() { "genrev-1", false, null, - LocalDateTime.now())); + LocalDateTime.now(), + null, + null)); when(assetExportService.exportAssets("tenant-1", 8)) .thenReturn(new ExportedAssetManifest("different", List.of("manifest.json"))); @@ -169,7 +171,9 @@ void repairFailsClosedWhenAttestedAssetKeysDrift() { "genrev-1", false, null, - LocalDateTime.now())); + LocalDateTime.now(), + null, + null)); when(assetExportService.exportAssets("tenant-1", 8)) .thenReturn(new ExportedAssetManifest("attested", List.of("manifest.json"))); 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 ccb05c4d59..8788633606 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 @@ -204,7 +204,9 @@ void publishFullVersionUsesTenantScopedVersionSequence() { "genrev-tenant-1-10", false, null, - LocalDateTime.now())); + LocalDateTime.now(), + null, + null)); when(versionAssetArtifactService.markPublished( any(String.class), any(Long.class), @@ -481,7 +483,9 @@ void succeededReplayUsesStoredBundleAfterLifecycleDriftWithoutWritesOrGates() { "generation-revision", false, null, - LocalDateTime.now()); + LocalDateTime.now(), + null, + null); VersionAssetArtifactStateDto driftedArtifact = new VersionAssetArtifactStateDto( "tenant-1", @@ -554,7 +558,9 @@ void succeededReplayRejectsMismatchedCommittedBundleIdentity() { "generation-revision", false, null, - LocalDateTime.now()); + LocalDateTime.now(), + null, + null); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) @@ -644,7 +650,9 @@ void legacySucceededAttemptReplaysWithoutBackfillOrMutableReads() { "generation-revision", false, null, - LocalDateTime.now()); + LocalDateTime.now(), + null, + null); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.of(bundle)); @@ -764,7 +772,9 @@ void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { "generation-revision", false, null, - LocalDateTime.now()); + LocalDateTime.now(), + null, + null); VersionAssetArtifactStateDto artifact = new VersionAssetArtifactStateDto( "tenant-1", @@ -988,7 +998,9 @@ void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { "generation-revision", false, null, - LocalDateTime.now()); + LocalDateTime.now(), + null, + null); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); 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 883fca9a26..fff00f4b4a 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 @@ -1803,7 +1803,9 @@ private PublishedReleaseBundleDto publishedReleaseBundle( "genrev-1", false, null, - LocalDateTime.parse("2026-04-26T10:00:00")); + LocalDateTime.parse("2026-04-26T10:00:00"), + null, + null); } private PublishedPluginVersion uploadedPluginVersion( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeRepository.java index 38100db605..a2a0ccff36 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeRepository.java @@ -6,7 +6,9 @@ import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.jooq.DSLContext; import org.jooq.Field; import org.jooq.Record; @@ -201,6 +203,38 @@ public Optional read(String namespace, UUID in return Optional.of(receipt); } + /** Reads a committed World intake by its exact canonical source-owned binding. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readBySource( + String namespace, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World authored-source intake read requires a committed-outcome owner read"); + } + validateSourceReadKey( + namespace, canonicalTenantId, worldSlug, sourceOperationId, sourceEvidenceDigest); + Record record = + dsl.selectFrom(INTAKE) + .where( + TARGET_NAMESPACE + .eq(namespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(WORLD_SLUG.eq(worldSlug)) + .and(SOURCE_OPERATION_ID.eq(sourceOperationId)) + .and(SOURCE_EVIDENCE_DIGEST.eq(sourceEvidenceDigest))) + .fetchOne(); + if (record == null) { + return Optional.empty(); + } + WorldAuthoredSourceIntakeReceipt receipt = toReceipt(record); + requireTenantAssociation(receipt); + return Optional.of(receipt); + } + private void lockFreshIntakeAndExistingTenantRows() { // Serialize allocator owners, then keep every current tenant-bearing table stable while the // candidate is checked. Legacy writers do not take this association lock; their database @@ -430,6 +464,20 @@ private void validateReadKey(String namespace, UUID intakeRequestId) { requireNonNil(intakeRequestId, "intakeRequestId"); } + private void validateSourceReadKey( + String namespace, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest) { + AuthoredWorldSourceDigest.validateReadSelector(namespace, canonicalTenantId, worldSlug); + requireNonNil(sourceOperationId, "sourceOperationId"); + if (!GameTenantCreationDigest.isDigest(sourceEvidenceDigest)) { + throw new IllegalArgumentException( + "sourceEvidenceDigest must be a canonical lowercase SHA-256 digest"); + } + } + private void requireActiveOwnerTransaction() { if (!TransactionSynchronizationManager.isActualTransactionActive()) { throw new IllegalStateException( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidence.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidence.java new file mode 100644 index 0000000000..24b0f3ba96 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidence.java @@ -0,0 +1,160 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; + +/** Exact caller binding and owner-produced checkpoint for one World publication-freeze attempt. */ +public record WorldDesignPublicationFenceEvidence( + String targetNamespace, + UUID canonicalTenantId, + long versionId, + UUID intakeRequestId, + UUID intakeOperationId, + UUID sourceOperationId, + String sourceEvidenceDigest, + String publicationRequestId, + String requestDigest, + long versionStateEpoch, + String publishWorkflowId) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SOURCE_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern REQUEST_DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern CONTENT_DIGEST = Pattern.compile("[0-9a-f]{64}"); + + // requestDigest is retained as the supplied full publication-request digest. The existing + // PublicationDigestRequestBinding is used only for workflow identity derivation here; its + // publicationDigestRequest/v1 read-binding digest is not the full freeze-request digest. + + public WorldDesignPublicationFenceEvidence { + new OwnerBinding( + targetNamespace, + canonicalTenantId, + versionId, + intakeRequestId, + intakeOperationId, + sourceOperationId, + sourceEvidenceDigest); + requirePositive(versionStateEpoch, "versionStateEpoch"); + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.full( + canonicalTenantId.toString(), Long.toString(versionId), publicationRequestId); + if (requestDigest == null || !REQUEST_DIGEST.matcher(requestDigest).matches()) { + throw new IllegalArgumentException("requestDigest must be 64 lowercase hexadecimal digits"); + } + if (!binding.derivedWorkflowIdentity().equals(publishWorkflowId)) { + throw new IllegalArgumentException( + "publishWorkflowId does not match the canonical full-version workflow identity"); + } + } + + /** The common owner scope and complete source binding used by ordinary writers and freezes. */ + public OwnerBinding ownerBinding() { + return new OwnerBinding( + targetNamespace, + canonicalTenantId, + versionId, + intakeRequestId, + intakeOperationId, + sourceOperationId, + sourceEvidenceDigest); + } + + /** + * Scope/source identity needed to serialize an ordinary OPEN writer. It carries no publication + * request, digest, epoch, workflow, fence, or checkpoint. + */ + public record OwnerBinding( + String targetNamespace, + UUID canonicalTenantId, + long versionId, + UUID intakeRequestId, + UUID intakeOperationId, + UUID sourceOperationId, + String sourceEvidenceDigest) { + public OwnerBinding { + if (targetNamespace == null || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requirePositive(versionId, "versionId"); + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(intakeOperationId, "intakeOperationId"); + requireNonNil(sourceOperationId, "sourceOperationId"); + if (sourceEvidenceDigest == null || !SOURCE_DIGEST.matcher(sourceEvidenceDigest).matches()) { + throw new IllegalArgumentException( + "sourceEvidenceDigest must be a canonical prefixed SHA-256 digest"); + } + } + } + + /** + * Returns the full-version request identity binding used to derive the canonical workflow ID. Its + * separate publicationDigestRequest/v1 digest is not this record's supplied requestDigest. + */ + public PublicationDigestRequestBinding publicationBinding() { + return PublicationDigestRequestBinding.full( + canonicalTenantId.toString(), Long.toString(versionId), publicationRequestId); + } + + /** Owner-local complete digest checkpoint captured only after the shared version lock is held. */ + public record Checkpoint(String appliedCommitId, String contentDigest, int digestSchemaVersion) { + public Checkpoint { + requireText(appliedCommitId, "appliedCommitId"); + if (appliedCommitId.isBlank()) { + throw new IllegalArgumentException("appliedCommitId must not be blank"); + } + if (!CONTENT_DIGEST + .matcher(Objects.requireNonNull(contentDigest, "contentDigest")) + .matches()) { + throw new IllegalArgumentException("contentDigest must be 64 lowercase hexadecimal digits"); + } + if (digestSchemaVersion <= 0) { + throw new IllegalArgumentException("digestSchemaVersion must be positive"); + } + } + + private static void requireText(String value, String label) { + if (value == null || value.isEmpty() || value.getBytes(StandardCharsets.UTF_8).length > 256) { + throw new IllegalArgumentException( + label + " must be non-empty and at most 256 UTF-8 bytes"); + } + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + throw new IllegalArgumentException(label + " contains malformed Unicode"); + } + index++; + } else if (Character.isLowSurrogate(current)) { + throw new IllegalArgumentException(label + " contains malformed Unicode"); + } + } + } + } + + /** Stored freeze result. The UUID is opaque and may only be compared for equality. */ + public record FrozenAttempt( + WorldDesignPublicationFenceEvidence request, UUID publicationFence, Checkpoint checkpoint) { + public FrozenAttempt { + Objects.requireNonNull(request, "request"); + requireNonNil(publicationFence, "publicationFence"); + Objects.requireNonNull(checkpoint, "checkpoint"); + } + } + + private static void requirePositive(long value, String label) { + if (value <= 0L) { + throw new IllegalArgumentException(label + " must be positive"); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java new file mode 100644 index 0000000000..9bc4746db0 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java @@ -0,0 +1,376 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.Checkpoint; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.FrozenAttempt; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Internal owner-local persistence for the World publication fence prerequisite. + * + *

This repository is not wired to an RPC or authoring route. A supplied checkpoint is retained + * as owner evidence only; it is not an authenticated Game Design freeze acknowledgement. + */ +@Repository +public class WorldDesignPublicationFenceRepository { + private static final String OPEN = "OPEN"; + private static final String FROZEN = "FROZEN"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private static final Table OWNER = DSL.table(DSL.name("world_design_publication_fence_owner")); + private static final Table ATTEMPT = + DSL.table(DSL.name("world_design_publication_fence_attempt")); + private static final Field TARGET_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field LOCAL_TENANT_KEY = + DSL.field(DSL.name("local_tenant_key"), Long.class); + private static final Field VERSION_ID = DSL.field(DSL.name("version_id"), Long.class); + private static final Field INTAKE_OPERATION_ID = + DSL.field(DSL.name("intake_operation_id"), UUID.class); + private static final Field INTAKE_REQUEST_ID = + DSL.field(DSL.name("intake_request_id"), UUID.class); + private static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("source_operation_id"), UUID.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_digest"), String.class); + private static final Field INTAKE_RECEIPT_DIGEST = + DSL.field(DSL.name("intake_receipt_digest"), String.class); + private static final Field OWNER_FREEZE_PHASE = + DSL.field(DSL.name("owner_freeze_phase"), String.class); + private static final Field CURRENT_PUBLICATION_FENCE = + DSL.field(DSL.name("current_publication_fence"), UUID.class); + + private static final Field PUBLICATION_FENCE = + DSL.field(DSL.name("publication_fence"), UUID.class); + private static final Field PUBLICATION_REQUEST_ID = + DSL.field(DSL.name("publication_request_id"), String.class); + private static final Field REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field VERSION_STATE_EPOCH = + DSL.field(DSL.name("version_state_epoch"), Long.class); + private static final Field PUBLISH_WORKFLOW_ID = + DSL.field(DSL.name("publish_workflow_id"), String.class); + private static final Field APPLIED_COMMIT_ID = + 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 DIGEST_SCHEMA_VERSION = + DSL.field(DSL.name("digest_schema_version"), Integer.class); + + private final DSLContext dsl; + private final WorldAuthoredSourceIntakeRepository intakeRepository; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Injected repositories are internal Spring collaborators; construction acquires no resources and this repository has no finalizer.") + public WorldDesignPublicationFenceRepository( + DSLContext dsl, WorldAuthoredSourceIntakeRepository intakeRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + this.intakeRepository = Objects.requireNonNull(intakeRepository, "intakeRepository"); + } + + /** + * Acquires the shared writable version row for an ordinary mutation and holds its row lock until + * the caller's owner transaction ends. The exact committed intake is resolved before row create + * or lock; the private local tenant key is always derived from that immutable intake. + */ + @Transactional(propagation = Propagation.MANDATORY) + public void lockOpen(OwnerBinding binding) { + requireWritableReadCommittedOwnerTransaction(); + ResolvedIntake intake = resolveCommittedIntake(binding); + Record owner = createAndLockOwner(binding, intake); + requireMatchingOwnerBinding(owner, binding, intake); + if (!OPEN.equals(owner.get(OWNER_FREEZE_PHASE, String.class))) { + throw new ConflictException("World version is not open for an ordinary Draft mutation"); + } + if (owner.get(CURRENT_PUBLICATION_FENCE, UUID.class) != null) { + throw new ConflictException("Open World version unexpectedly retains a publication fence"); + } + } + + /** + * Claims the owner-local freeze after taking the same version row lock as ordinary writers. + * + *

The checkpoint supplier runs only for the first OPEN-to-FROZEN transition, after this + * transaction holds the row lock. An exact retry returns the stored fence and checkpoint without + * recapturing server-derived output. No producer, caller authentication, or public freeze route + * is established by this internal persistence method. + */ + @Transactional(propagation = Propagation.MANDATORY) + public FrozenAttempt claimFreeze( + WorldDesignPublicationFenceEvidence evidence, Supplier checkpointSupplier) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(checkpointSupplier, "checkpointSupplier"); + OwnerBinding binding = evidence.ownerBinding(); + ResolvedIntake intake = resolveCommittedIntake(binding); + Record owner = createAndLockOwner(binding, intake); + requireMatchingOwnerBinding(owner, binding, intake); + + String phase = owner.get(OWNER_FREEZE_PHASE, String.class); + UUID currentFence = owner.get(CURRENT_PUBLICATION_FENCE, UUID.class); + if (FROZEN.equals(phase)) { + if (currentFence == null) { + throw new ConflictException("Frozen World owner row has no publication fence"); + } + FrozenAttempt stored = findAttemptByFence(currentFence); + if (stored == null) { + throw new ConflictException("Frozen World owner row has no immutable attempt record"); + } + requireExactRequest(stored, evidence); + return stored; + } + if (!OPEN.equals(phase) || currentFence != null) { + throw new ConflictException( + "World version cannot start a publication freeze in its current phase"); + } + if (findAttemptByRequest(evidence) != null) { + throw new ConflictException("World publication request already has an immutable attempt"); + } + + Checkpoint checkpoint = + Objects.requireNonNull( + checkpointSupplier.get(), "checkpointSupplier returned no complete World checkpoint"); + UUID publicationFence = newNonNilUuid(); + int inserted = insertAttempt(evidence, intake, publicationFence, checkpoint); + if (inserted != 1) { + throw new ConflictException("World publication attempt was not inserted"); + } + + int updated = + dsl.update(OWNER) + .set(OWNER_FREEZE_PHASE, FROZEN) + .set(CURRENT_PUBLICATION_FENCE, publicationFence) + .where( + TARGET_NAMESPACE + .eq(evidence.targetNamespace()) + .and(CANONICAL_TENANT_ID.eq(evidence.canonicalTenantId())) + .and(VERSION_ID.eq(evidence.versionId())) + .and(OWNER_FREEZE_PHASE.eq(OPEN)) + .and(CURRENT_PUBLICATION_FENCE.isNull())) + .execute(); + if (updated != 1) { + throw new ConflictException("World publication freeze lost its locked OPEN owner row"); + } + return new FrozenAttempt(evidence, publicationFence, checkpoint); + } + + /** + * Reads one exact immutable attempt by its full request binding without creating or changing + * rows. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readAttempt(WorldDesignPublicationFenceEvidence evidence) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("World publication attempt read requires a committed read"); + } + resolveCommittedIntake(evidence.ownerBinding()); + FrozenAttempt stored = findAttemptByRequest(evidence); + if (stored == null) { + return Optional.empty(); + } + requireExactRequest(stored, evidence); + return Optional.of(stored); + } + + private ResolvedIntake resolveCommittedIntake(OwnerBinding binding) { + Objects.requireNonNull(binding, "binding"); + WorldAuthoredSourceIntakeReceipt receipt = + intakeRepository + .read(binding.targetNamespace(), binding.intakeRequestId()) + .orElseThrow( + () -> + new MissingIntakeException( + "World publication fence requires an already committed authored-source intake")); + if (!binding.targetNamespace().equals(receipt.targetNamespace()) + || !binding.canonicalTenantId().equals(receipt.canonicalTenantId()) + || !binding.intakeRequestId().equals(receipt.intakeRequestId()) + || !binding.intakeOperationId().equals(receipt.operationId()) + || !binding.sourceOperationId().equals(receipt.sourceOperationId()) + || !binding.sourceEvidenceDigest().equals(receipt.sourceEvidenceDigest())) { + throw new ConflictException( + "World publication request differs from the complete committed authored-source intake"); + } + return new ResolvedIntake(receipt); + } + + private Record createAndLockOwner(OwnerBinding binding, ResolvedIntake intake) { + WorldAuthoredSourceIntakeReceipt receipt = intake.receipt(); + dsl.insertInto(OWNER) + .set(TARGET_NAMESPACE, binding.targetNamespace()) + .set(CANONICAL_TENANT_ID, binding.canonicalTenantId()) + .set(LOCAL_TENANT_KEY, receipt.localTenantKey()) + .set(VERSION_ID, binding.versionId()) + .set(OWNER_FREEZE_PHASE, OPEN) + .onConflictDoNothing() + .execute(); + + Record owner = + dsl.selectFrom(OWNER) + .where( + TARGET_NAMESPACE + .eq(binding.targetNamespace()) + .and(CANONICAL_TENANT_ID.eq(binding.canonicalTenantId())) + .and(VERSION_ID.eq(binding.versionId()))) + .forUpdate() + .fetchOne(); + if (owner == null) { + throw new ConflictException("World version owner row could not be created or locked"); + } + return owner; + } + + private void requireMatchingOwnerBinding( + Record owner, OwnerBinding binding, ResolvedIntake intake) { + WorldAuthoredSourceIntakeReceipt receipt = intake.receipt(); + if (!Objects.equals(owner.get(TARGET_NAMESPACE, String.class), binding.targetNamespace()) + || !Objects.equals(owner.get(CANONICAL_TENANT_ID, UUID.class), binding.canonicalTenantId()) + || !Objects.equals(owner.get(LOCAL_TENANT_KEY, Long.class), receipt.localTenantKey()) + || !Objects.equals(owner.get(VERSION_ID, Long.class), binding.versionId())) { + throw new ConflictException( + "World version owner row is bound to a different canonical tenant association"); + } + } + + private int insertAttempt( + WorldDesignPublicationFenceEvidence evidence, + ResolvedIntake intake, + UUID publicationFence, + Checkpoint checkpoint) { + WorldAuthoredSourceIntakeReceipt receipt = intake.receipt(); + return dsl.insertInto(ATTEMPT) + .set(PUBLICATION_FENCE, publicationFence) + .set(TARGET_NAMESPACE, evidence.targetNamespace()) + .set(CANONICAL_TENANT_ID, evidence.canonicalTenantId()) + .set(LOCAL_TENANT_KEY, receipt.localTenantKey()) + .set(VERSION_ID, evidence.versionId()) + .set(INTAKE_OPERATION_ID, receipt.operationId()) + .set(INTAKE_REQUEST_ID, receipt.intakeRequestId()) + .set(SOURCE_OPERATION_ID, receipt.sourceOperationId()) + .set(SOURCE_EVIDENCE_DIGEST, receipt.sourceEvidenceDigest()) + .set(INTAKE_RECEIPT_DIGEST, receipt.receiptDigest()) + .set(PUBLICATION_REQUEST_ID, evidence.publicationRequestId()) + .set(REQUEST_DIGEST, evidence.requestDigest()) + .set(VERSION_STATE_EPOCH, evidence.versionStateEpoch()) + .set(PUBLISH_WORKFLOW_ID, evidence.publishWorkflowId()) + .set(APPLIED_COMMIT_ID, checkpoint.appliedCommitId()) + .set(CONTENT_DIGEST, checkpoint.contentDigest()) + .set(DIGEST_SCHEMA_VERSION, checkpoint.digestSchemaVersion()) + .execute(); + } + + private FrozenAttempt findAttemptByFence(UUID publicationFence) { + Record record = + dsl.selectFrom(ATTEMPT).where(PUBLICATION_FENCE.eq(publicationFence)).fetchOne(); + return record == null ? null : toFrozenAttempt(record); + } + + private FrozenAttempt findAttemptByRequest(WorldDesignPublicationFenceEvidence evidence) { + Record record = + dsl.selectFrom(ATTEMPT) + .where( + TARGET_NAMESPACE + .eq(evidence.targetNamespace()) + .and(CANONICAL_TENANT_ID.eq(evidence.canonicalTenantId())) + .and(VERSION_ID.eq(evidence.versionId())) + .and(PUBLICATION_REQUEST_ID.eq(evidence.publicationRequestId()))) + .fetchOne(); + return record == null ? null : toFrozenAttempt(record); + } + + private FrozenAttempt toFrozenAttempt(Record record) { + WorldDesignPublicationFenceEvidence request = + new WorldDesignPublicationFenceEvidence( + record.get(TARGET_NAMESPACE), + record.get(CANONICAL_TENANT_ID), + record.get(VERSION_ID), + record.get(INTAKE_REQUEST_ID), + record.get(INTAKE_OPERATION_ID), + record.get(SOURCE_OPERATION_ID), + record.get(SOURCE_EVIDENCE_DIGEST), + record.get(PUBLICATION_REQUEST_ID), + record.get(REQUEST_DIGEST), + record.get(VERSION_STATE_EPOCH), + record.get(PUBLISH_WORKFLOW_ID)); + Checkpoint checkpoint = + new Checkpoint( + record.get(APPLIED_COMMIT_ID), + record.get(CONTENT_DIGEST), + record.get(DIGEST_SCHEMA_VERSION)); + return new FrozenAttempt(request, record.get(PUBLICATION_FENCE), checkpoint); + } + + private void requireExactRequest( + FrozenAttempt stored, WorldDesignPublicationFenceEvidence supplied) { + if (!stored.request().equals(supplied)) { + throw new ConflictException( + "World publication request identity was reused with changed source or request binding"); + } + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World publication fence requires an active owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "World publication fence requires a writable owner transaction"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation != null && declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("World publication fence requires READ COMMITTED isolation"); + } + Record settings = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS transaction_isolation, " + + "current_setting('transaction_read_only') AS transaction_read_only"); + if (settings == null + || !"read committed".equalsIgnoreCase(settings.get("transaction_isolation", String.class)) + || !"off".equalsIgnoreCase(settings.get("transaction_read_only", String.class))) { + throw new IllegalStateException( + "World publication fence requires a writable READ COMMITTED owner transaction"); + } + } + + private UUID newNonNilUuid() { + UUID value; + do { + value = UUID.randomUUID(); + } while (NIL_UUID.equals(value)); + return value; + } + + private record ResolvedIntake(WorldAuthoredSourceIntakeReceipt receipt) {} + + /** Exact input conflicts fail closed without changing either owner or attempt history. */ + public static final class ConflictException extends IllegalStateException { + public ConflictException(String message) { + super(message); + } + } + + /** No owner state may be created for a missing or not-yet-committed authored-source intake. */ + public static final class MissingIntakeException extends IllegalStateException { + public MissingIntakeException(String message) { + super(message); + } + } +} diff --git a/services/world-management-service/src/main/resources/db/migration/V24__world_canonical_tenant_mutation_guard.sql b/services/world-management-service/src/main/resources/db/migration/V24__world_canonical_tenant_mutation_guard.sql new file mode 100644 index 0000000000..56b19ac59d --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V24__world_canonical_tenant_mutation_guard.sql @@ -0,0 +1,219 @@ +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION world_claim_legacy_numeric_tenant_key() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + claimed_key BIGINT; +BEGIN + IF TG_OP = 'DELETE' THEN + IF EXISTS ( + SELECT 1 + FROM world_authored_source_tenant_key_reservation + WHERE tenant_key = OLD.tenant_id + AND claim_kind = 'CANONICAL_AUTHORED_SOURCE' + ) THEN + RAISE EXCEPTION + 'World tenant key % is reserved for a canonical authored source', OLD.tenant_id + USING ERRCODE = '23514'; + END IF; + RETURN OLD; + END IF; + + IF TG_OP = 'UPDATE' AND EXISTS ( + SELECT 1 + FROM world_authored_source_tenant_key_reservation + WHERE tenant_key = OLD.tenant_id + AND claim_kind = 'CANONICAL_AUTHORED_SOURCE' + ) THEN + RAISE EXCEPTION + 'World tenant key % is reserved for a canonical authored source', OLD.tenant_id + USING ERRCODE = '23514'; + END IF; + + IF EXISTS ( + SELECT 1 + FROM world_authored_source_tenant_key_reservation + WHERE tenant_key = NEW.tenant_id + AND claim_kind = 'CANONICAL_AUTHORED_SOURCE' + ) THEN + RAISE EXCEPTION + 'World tenant key % is reserved for a canonical authored source', NEW.tenant_id + USING ERRCODE = '23514'; + END IF; + + INSERT INTO world_authored_source_tenant_key_reservation AS reservation + (tenant_key, claim_kind) + VALUES (NEW.tenant_id, 'LEGACY_NUMERIC') + ON CONFLICT (tenant_key) DO UPDATE + SET tenant_key = EXCLUDED.tenant_key + WHERE reservation.claim_kind = 'LEGACY_NUMERIC' + RETURNING reservation.tenant_key INTO claimed_key; + + IF claimed_key IS NULL THEN + RAISE EXCEPTION 'World tenant key % is reserved for a canonical authored source', NEW.tenant_id + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION world_reject_tenant_table_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION + 'World tenant-bearing tables require owner-qualified row mutation; TRUNCATE is forbidden' + USING ERRCODE = '23514'; +END; +$$; + +DROP TRIGGER trg_reserve_generation_rule_tenant_key ON generation_rule; +CREATE TRIGGER trg_reserve_generation_rule_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON generation_rule + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_instance_tenant_key ON instance; +CREATE TRIGGER trg_reserve_instance_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_region_tenant_key ON region; +CREATE TRIGGER trg_reserve_region_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON region + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_region_instance_tenant_key ON region_instance; +CREATE TRIGGER trg_reserve_region_instance_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON region_instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_room_tenant_key ON room; +CREATE TRIGGER trg_reserve_room_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON room + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_room_exit_tenant_key ON room_exit; +CREATE TRIGGER trg_reserve_room_exit_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON room_exit + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_room_instance_tenant_key ON room_instance; +CREATE TRIGGER trg_reserve_room_instance_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON room_instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_room_instance_exit_tenant_key ON room_instance_exit; +CREATE TRIGGER trg_reserve_room_instance_exit_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON room_instance_exit + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_world_design_aggregate_epoch_tenant_key + ON world_design_aggregate_epoch; +CREATE TRIGGER trg_reserve_world_design_aggregate_epoch_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON world_design_aggregate_epoch + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_world_design_revision_ledger_tenant_key + ON world_design_revision_ledger; +CREATE TRIGGER trg_reserve_world_design_revision_ledger_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON world_design_revision_ledger + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_world_design_scope_epoch_tenant_key + ON world_design_scope_epoch; +CREATE TRIGGER trg_reserve_world_design_scope_epoch_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON world_design_scope_epoch + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_world_entity_spawn_binding_tenant_key + ON world_entity_spawn_binding; +CREATE TRIGGER trg_reserve_world_entity_spawn_binding_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON world_entity_spawn_binding + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_world_event_tenant_key ON world_event; +CREATE TRIGGER trg_reserve_world_event_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON world_event + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_world_instance_tenant_key ON world_instance; +CREATE TRIGGER trg_reserve_world_instance_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON world_instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_zone_tenant_key ON zone; +CREATE TRIGGER trg_reserve_zone_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON zone + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_zone_instance_tenant_key ON zone_instance; +CREATE TRIGGER trg_reserve_zone_instance_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON zone_instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +CREATE TRIGGER trg_generation_rule_no_truncate + BEFORE TRUNCATE ON generation_rule + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_instance_no_truncate + BEFORE TRUNCATE ON instance + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_region_no_truncate + BEFORE TRUNCATE ON region + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_region_instance_no_truncate + BEFORE TRUNCATE ON region_instance + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_room_no_truncate + BEFORE TRUNCATE ON room + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_room_exit_no_truncate + BEFORE TRUNCATE ON room_exit + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_room_instance_no_truncate + BEFORE TRUNCATE ON room_instance + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_room_instance_exit_no_truncate + BEFORE TRUNCATE ON room_instance_exit + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_world_design_aggregate_epoch_no_truncate + BEFORE TRUNCATE ON world_design_aggregate_epoch + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_world_design_revision_ledger_no_truncate + BEFORE TRUNCATE ON world_design_revision_ledger + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_world_design_scope_epoch_no_truncate + BEFORE TRUNCATE ON world_design_scope_epoch + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_world_entity_spawn_binding_no_truncate + BEFORE TRUNCATE ON world_entity_spawn_binding + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_world_event_no_truncate + BEFORE TRUNCATE ON world_event + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_world_instance_no_truncate + BEFORE TRUNCATE ON world_instance + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_zone_no_truncate + BEFORE TRUNCATE ON zone + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_zone_instance_no_truncate + BEFORE TRUNCATE ON zone_instance + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V25__world_design_publication_fence.sql b/services/world-management-service/src/main/resources/db/migration/V25__world_design_publication_fence.sql new file mode 100644 index 0000000000..1542829b59 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V25__world_design_publication_fence.sql @@ -0,0 +1,220 @@ +ALTER TABLE world_authored_source_intake + ADD CONSTRAINT uq_world_authored_source_intake_publication_binding UNIQUE ( + operation_id, + target_namespace, + canonical_tenant_id, + local_tenant_key, + intake_request_id, + source_operation_id, + source_evidence_digest, + receipt_digest + ); + +CREATE TABLE world_design_publication_fence_attempt ( + publication_fence UUID NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL, + version_id BIGINT NOT NULL, + intake_operation_id UUID NOT NULL, + intake_request_id UUID NOT NULL, + source_operation_id UUID NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL, + intake_receipt_digest VARCHAR(71) NOT NULL, + publication_request_id VARCHAR(256) NOT NULL, + request_digest VARCHAR(64) NOT NULL, + version_state_epoch BIGINT NOT NULL, + publish_workflow_id VARCHAR(537) NOT NULL, + applied_commit_id VARCHAR(256) NOT NULL, + content_digest VARCHAR(64) NOT NULL, + digest_schema_version INTEGER NOT NULL, + CONSTRAINT pk_world_design_publication_fence_attempt + PRIMARY KEY (publication_fence), + CONSTRAINT uq_world_design_publication_attempt_scope_request + UNIQUE (target_namespace, canonical_tenant_id, version_id, publication_request_id), + CONSTRAINT uq_world_design_publication_attempt_owner_fence + UNIQUE ( + publication_fence, + target_namespace, + canonical_tenant_id, + local_tenant_key, + version_id + ), + CONSTRAINT fk_world_design_publication_attempt_tenant_association + FOREIGN KEY (target_namespace, canonical_tenant_id, local_tenant_key) + REFERENCES world_authored_source_tenant_association + (target_namespace, canonical_tenant_id, local_tenant_key), + CONSTRAINT fk_world_design_publication_attempt_intake + FOREIGN KEY ( + intake_operation_id, + target_namespace, + canonical_tenant_id, + local_tenant_key, + intake_request_id, + source_operation_id, + source_evidence_digest, + intake_receipt_digest + ) + REFERENCES world_authored_source_intake ( + operation_id, + target_namespace, + canonical_tenant_id, + local_tenant_key, + intake_request_id, + source_operation_id, + source_evidence_digest, + receipt_digest + ), + CONSTRAINT ck_world_design_publication_attempt_scope + CHECK (version_id > 0 AND version_state_epoch > 0 AND digest_schema_version > 0), + CONSTRAINT ck_world_design_publication_attempt_namespace + CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + ), + CONSTRAINT ck_world_design_publication_attempt_ids + CHECK ( + publication_fence <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND local_tenant_key > 0 + ), + CONSTRAINT ck_world_design_publication_attempt_source_digest + CHECK (source_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT ck_world_design_publication_attempt_receipt_digest + CHECK (intake_receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT ck_world_design_publication_attempt_request + CHECK ( + octet_length(publication_request_id) BETWEEN 1 AND 256 + AND position(':' IN publication_request_id) = 0 + AND octet_length(request_digest) = 64 + AND request_digest ~ '^[0-9a-f]{64}$' + AND publish_workflow_id = + 'publish:' || canonical_tenant_id::TEXT || ':publish-request:' || publication_request_id + AND octet_length(publish_workflow_id) <= 537 + ), + CONSTRAINT ck_world_design_publication_attempt_checkpoint + CHECK ( + octet_length(applied_commit_id) BETWEEN 1 AND 256 + AND content_digest ~ '^[0-9a-f]{64}$' + ) +); + +CREATE TABLE world_design_publication_fence_owner ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL, + version_id BIGINT NOT NULL, + owner_freeze_phase VARCHAR(32) NOT NULL, + current_publication_fence UUID, + CONSTRAINT pk_world_design_publication_fence_owner + PRIMARY KEY (local_tenant_key, version_id), + CONSTRAINT uq_world_design_publication_fence_owner_scope + UNIQUE (target_namespace, canonical_tenant_id, version_id), + CONSTRAINT fk_world_design_publication_owner_tenant_association + FOREIGN KEY (target_namespace, canonical_tenant_id, local_tenant_key) + REFERENCES world_authored_source_tenant_association + (target_namespace, canonical_tenant_id, local_tenant_key), + CONSTRAINT fk_world_design_publication_owner_current_attempt + FOREIGN KEY ( + current_publication_fence, + target_namespace, + canonical_tenant_id, + local_tenant_key, + version_id + ) + REFERENCES world_design_publication_fence_attempt ( + publication_fence, + target_namespace, + canonical_tenant_id, + local_tenant_key, + version_id + ), + CONSTRAINT ck_world_design_publication_fence_owner_scope + CHECK (version_id > 0 AND local_tenant_key > 0), + CONSTRAINT ck_world_design_publication_fence_owner_ids + CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT ck_world_design_publication_fence_owner_namespace + CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + ), + CONSTRAINT ck_world_design_publication_fence_owner_phase + CHECK ( + (owner_freeze_phase = 'OPEN' AND current_publication_fence IS NULL) + OR + (owner_freeze_phase IN ( + 'FROZEN', + 'PUBLISHED', + 'ABORTED', + 'RECONCILIATION_REQUIRED' + ) AND current_publication_fence IS NOT NULL) + ) +); + +-- [jooq ignore start] +CREATE FUNCTION world_reject_publication_attempt_history_mutation() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'World publication-fence attempt history is immutable' + USING ERRCODE = '55000'; +END; +$$; + +CREATE FUNCTION world_protect_publication_fence_owner() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'World publication-fence owner rows cannot be deleted' + USING ERRCODE = '55000'; + END IF; + + IF TG_OP = 'INSERT' THEN + IF NEW.owner_freeze_phase = 'OPEN' AND NEW.current_publication_fence IS NULL THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'World publication-fence owner rows must be created OPEN without a fence' + USING ERRCODE = '55000'; + END IF; + + IF OLD.target_namespace IS NOT DISTINCT FROM NEW.target_namespace + AND OLD.canonical_tenant_id IS NOT DISTINCT FROM NEW.canonical_tenant_id + AND OLD.local_tenant_key IS NOT DISTINCT FROM NEW.local_tenant_key + AND OLD.version_id IS NOT DISTINCT FROM NEW.version_id + AND OLD.owner_freeze_phase = 'OPEN' + AND NEW.owner_freeze_phase = 'FROZEN' + AND OLD.current_publication_fence IS NULL + AND NEW.current_publication_fence IS NOT NULL + THEN + RETURN NEW; + END IF; + + RAISE EXCEPTION 'World publication-fence owner binding or phase transition is immutable' + USING ERRCODE = '55000'; +END; +$$; + +CREATE TRIGGER trg_world_publication_attempt_immutable + BEFORE UPDATE OR DELETE ON world_design_publication_fence_attempt + FOR EACH ROW EXECUTE FUNCTION world_reject_publication_attempt_history_mutation(); + +CREATE TRIGGER trg_world_publication_attempt_no_truncate + BEFORE TRUNCATE ON world_design_publication_fence_attempt + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_publication_attempt_history_mutation(); + +CREATE TRIGGER trg_world_publication_owner_protect + BEFORE INSERT OR UPDATE OR DELETE ON world_design_publication_fence_owner + FOR EACH ROW EXECUTE FUNCTION world_protect_publication_fence_owner(); + +CREATE TRIGGER trg_world_publication_owner_no_truncate + BEFORE TRUNCATE ON world_design_publication_fence_owner + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_publication_attempt_history_mutation(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java index 7b9771c820..d764f18544 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java @@ -3,9 +3,17 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Statement; import java.util.Arrays; +import java.util.HashSet; +import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @@ -20,10 +28,12 @@ import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; import net.firedevops.firemud.worldmanagement.client.GameDesignClient; import net.firedevops.firemud.worldmanagement.client.GameSessionClient; +import net.firedevops.firemud.worldmanagement.client.GrpcGameSessionInitialAdmissionBindProofClient; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationInfo; +import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; import org.jooq.exception.DataAccessException; import org.junit.jupiter.api.Test; @@ -50,6 +60,24 @@ properties = "spring.grpc.server.port=0") class WorldAuthoredSourceIntakeIntegrationTest { private static final String NAMESPACE = "firemud"; + private static final Set PROTECTED_TENANT_TABLES = + Set.of( + "generation_rule", + "instance", + "region", + "region_instance", + "room", + "room_exit", + "room_instance", + "room_instance_exit", + "world_design_aggregate_epoch", + "world_design_revision_ledger", + "world_design_scope_epoch", + "world_entity_spawn_binding", + "world_event", + "world_instance", + "zone", + "zone_instance"); private static final String OCCUPIED_LEGACY_KEYS = "SELECT COUNT(*) FROM (" + "SELECT tenant_id AS occupied_key FROM generation_rule UNION ALL " @@ -111,6 +139,10 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private PlatformTransactionManager transactionManager; @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + @MockitoBean private GameDesignClient gameDesignClient; @MockitoBean private GameSessionClient gameSessionClient; @MockitoBean private EntityManagementClient entityManagementClient; @@ -202,6 +234,184 @@ void persistsCompleteFreshReceiptAndReusesExactTenantAssociationAcrossWorlds() { assertThat(second.source().provenanceKind()).isEqualTo("NEW_GAME_ROW"); } + @Test + void readBySourceReturnsExactCommittedReceiptOnRepeatedCallsWithoutGrowth() { + UUID tenant = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source(tenant, tenantSlug(tenant), "source-read-world", sourceRowId(tenant), "Source Read"); + WorldAuthoredSourceIntakeReceipt receipt = accept(UUID.randomUUID(), source); + long intakeCount = countRows("world_authored_source_intake"); + long associationCount = countRows("world_authored_source_tenant_association"); + long reservationCount = countRows("world_authored_source_tenant_key_reservation"); + + assertThat( + repository.readBySource( + NAMESPACE, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .contains(receipt); + assertThat( + repository.readBySource( + NAMESPACE, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .contains(receipt); + assertThat(countRows("world_authored_source_intake")).isEqualTo(intakeCount); + assertThat(countRows("world_authored_source_tenant_association")).isEqualTo(associationCount); + assertThat(countRows("world_authored_source_tenant_key_reservation")) + .isEqualTo(reservationCount); + } + + @Test + void readBySourceRejectsAnyChangedBindingAndRetainedOrUnmappedEvidence() { + UUID tenant = UUID.randomUUID(); + String tenantSlug = tenantSlug(tenant); + long sourceRowId = sourceRowId(tenant); + AuthoredWorldSourceEvidence source = + source(tenant, tenantSlug, "source-binding-world", sourceRowId, "Source Binding"); + accept(UUID.randomUUID(), source); + + assertThat( + repository.readBySource( + "other-namespace", + tenant, + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .isEmpty(); + assertThat( + repository.readBySource( + NAMESPACE, + UUID.randomUUID(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .isEmpty(); + assertThat( + repository.readBySource( + NAMESPACE, tenant, "another-world", source.operationId(), source.evidenceDigest())) + .isEmpty(); + assertThat( + repository.readBySource( + NAMESPACE, tenant, source.worldSlug(), UUID.randomUUID(), source.evidenceDigest())) + .isEmpty(); + assertThat( + repository.readBySource( + NAMESPACE, + tenant, + source.worldSlug(), + source.operationId(), + "sha256:" + "0".repeat(64))) + .isEmpty(); + + AuthoredWorldSourceEvidence retainedSource = + source(tenant, tenantSlug, "retained-world", sourceRowId, "Retained", "RETAINED_GAME_V30"); + assertThat( + repository.readBySource( + NAMESPACE, + retainedSource.canonicalTenantId(), + retainedSource.worldSlug(), + retainedSource.operationId(), + retainedSource.evidenceDigest())) + .isEmpty(); + assertThat( + repository.readBySource( + NAMESPACE, + UUID.randomUUID(), + "unmapped-world", + UUID.randomUUID(), + source.evidenceDigest())) + .isEmpty(); + } + + @Test + void readBySourceRejectsMalformedBinding() { + UUID tenant = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, tenantSlug(tenant), "malformed-read-world", sourceRowId(tenant), "Malformed"); + UUID nilUuid = new UUID(0L, 0L); + + assertThatThrownBy( + () -> + repository.readBySource( + "FireMud", + tenant, + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + repository.readBySource( + NAMESPACE, + nilUuid, + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + repository.readBySource( + NAMESPACE, + tenant, + "Malformed-World", + source.operationId(), + source.evidenceDigest())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + repository.readBySource( + NAMESPACE, tenant, source.worldSlug(), nilUuid, source.evidenceDigest())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + repository.readBySource( + NAMESPACE, tenant, source.worldSlug(), source.operationId(), "sha256:BAD")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void readBySourceDoesNotExposeUncommittedOwnerEvidence() { + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, + tenantSlug(tenant), + "uncommitted-read-world", + sourceRowId(tenant), + "Uncommitted"); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + + transactionTemplate.execute( + status -> { + repository.acceptFresh(NAMESPACE, requestId, source); + assertThat( + repository.readBySource( + NAMESPACE, + tenant, + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .isEmpty(); + return null; + }); + + assertThat( + repository.readBySource( + NAMESPACE, + tenant, + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .contains(repository.read(NAMESPACE, requestId).orElseThrow()); + } + @Test void deniesRetainedEvidenceAndChangedRequestOrTenantScopeBeforeAddingClaims() { UUID tenant = UUID.randomUUID(); @@ -357,6 +567,80 @@ void rejectsImmutableHistoryMutationAndTruncation() { assertThat(countReservationsForCanonicalTenant(tenant)).isEqualTo(1L); } + @Test + void canonicalReservationsGuardEveryWorldRowMutationTrigger() throws SQLException { + String schema = "world_canonical_guard_" + UUID.randomUUID().toString().replace("-", ""); + UUID canonicalTenantId = UUID.randomUUID(); + long canonicalTenantKey = + 80_000_000_000_000L + ThreadLocalRandom.current().nextLong(1_000_000L); + long legacyTenantKey = canonicalTenantKey + 1L; + + try { + migrateFixture(schema, MigrationVersion.fromVersion("23.1")); + long canonicalRegionId = + seedCanonicalRegionBeforeGuard(schema, canonicalTenantId, canonicalTenantKey); + migrateFixture(schema, MigrationVersion.fromVersion("24")); + + try (Connection connection = fixtureConnection(schema)) { + assertProtectedReservationTriggerCatalog(connection); + assertProtectedTenantTruncateTriggerCatalog(connection); + + for (String table : PROTECTED_TENANT_TABLES) { + assertSqlState("23514", () -> insertTenantKeyRow(connection, table, canonicalTenantKey)); + long expectedRows = table.equals("region") ? 1L : 0L; + assertThat(countRowsForTenant(connection, table, canonicalTenantKey)) + .as("canonical-key insert side effects for %s", table) + .isEqualTo(expectedRows); + } + + long legacyRegionId = insertRegion(connection, legacyTenantKey, "legacy-before-update"); + assertSqlState( + "23514", + () -> + updateRegion( + connection, + canonicalRegionId, + legacyTenantKey, + "attempted move from canonical key")); + assertCanonicalRegion( + connection, canonicalRegionId, canonicalTenantKey, "test-only canonical row"); + assertThat(countRowsForTenant(connection, "region", legacyTenantKey)).isEqualTo(1L); + assertThat(readReservationClaimKind(connection, legacyTenantKey)) + .isEqualTo("LEGACY_NUMERIC"); + + assertSqlState( + "23514", + () -> updateRegionPayload(connection, canonicalRegionId, "attempted payload update")); + assertCanonicalRegion( + connection, canonicalRegionId, canonicalTenantKey, "test-only canonical row"); + + assertSqlState("23514", () -> deleteRegion(connection, canonicalRegionId)); + assertCanonicalRegion( + connection, canonicalRegionId, canonicalTenantKey, "test-only canonical row"); + assertThat(readReservationClaimKind(connection, canonicalTenantKey)) + .isEqualTo("CANONICAL_AUTHORED_SOURCE"); + + updateRegionPayload(connection, legacyRegionId, "legacy payload update remains allowed"); + assertThat(readRegionName(connection, legacyRegionId)) + .isEqualTo("legacy payload update remains allowed"); + deleteRegion(connection, legacyRegionId); + assertThat(countRowsForTenant(connection, "region", legacyTenantKey)).isZero(); + assertThat(readReservationClaimKind(connection, legacyTenantKey)) + .isEqualTo("LEGACY_NUMERIC"); + + assertSqlState("23514", () -> truncateTenantTable(connection, "region")); + assertCanonicalRegion( + connection, canonicalRegionId, canonicalTenantKey, "test-only canonical row"); + assertThat(countRowsForTenant(connection, "region", canonicalTenantKey)).isEqualTo(1L); + assertThat(readReservationClaimKind(connection, canonicalTenantKey)) + .isEqualTo("CANONICAL_AUTHORED_SOURCE"); + assertThat(countCanonicalAssociations(connection, canonicalTenantId)).isEqualTo(1L); + } + } finally { + dropFixtureSchema(schema); + } + } + @Test void rejectsReadOnlyAndNonReadCommittedOwnerTransactionsWithoutClaims() { UUID tenant = UUID.randomUUID(); @@ -569,6 +853,288 @@ void concurrentLegacyClaimAfterAllocationCannotTakeTheReservedSelector() throws } } + private static void migrateFixture(String schema, MigrationVersion target) { + var configuration = + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private static long seedCanonicalRegionBeforeGuard( + String schema, UUID canonicalTenantId, long canonicalTenantKey) throws SQLException { + try (Connection connection = fixtureConnection(schema); + Statement controls = connection.createStatement()) { + // Test-only bypass in this isolated V23.1 schema; restore triggers before applying V24. + controls.execute("SET session_replication_role = replica"); + try { + String tenantSlug = tenantSlug(canonicalTenantId); + String sourceKey = "src-" + canonicalTenantId.toString().replace("-", ""); + try (PreparedStatement association = + connection.prepareStatement( + "INSERT INTO world_authored_source_tenant_association " + + "(target_namespace, canonical_tenant_id, tenant_slug, " + + "source_game_row_id, source_game_tenant_key, " + + "source_provenance_kind, local_tenant_key) " + + "VALUES (?, ?, ?, ?, ?, 'NEW_GAME_ROW', ?)")) { + association.setString(1, NAMESPACE); + association.setObject(2, canonicalTenantId); + association.setString(3, tenantSlug); + association.setLong(4, sourceRowId(canonicalTenantId)); + association.setString(5, sourceKey); + association.setLong(6, canonicalTenantKey); + association.executeUpdate(); + } + try (PreparedStatement reservation = + connection.prepareStatement( + "INSERT INTO world_authored_source_tenant_key_reservation " + + "(tenant_key, claim_kind, target_namespace, canonical_tenant_id) " + + "VALUES (?, 'CANONICAL_AUTHORED_SOURCE', ?, ?)")) { + reservation.setLong(1, canonicalTenantKey); + reservation.setString(2, NAMESPACE); + reservation.setObject(3, canonicalTenantId); + reservation.executeUpdate(); + } + try (PreparedStatement region = + connection.prepareStatement( + "INSERT INTO region (tenant_id, name) VALUES (?, ?) RETURNING id")) { + region.setLong(1, canonicalTenantKey); + region.setString(2, "test-only canonical row"); + try (ResultSet result = region.executeQuery()) { + if (!result.next()) { + throw new SQLException("Test-only canonical region seed returned no row"); + } + return result.getLong(1); + } + } + } finally { + controls.execute("SET session_replication_role = origin"); + } + } + } + + private static Connection fixtureConnection(String schema) throws SQLException { + Connection connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + connection.setSchema(schema); + return connection; + } + + private static void dropFixtureSchema(String schema) throws SQLException { + try (Connection connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + Statement statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } + } + + private static void assertProtectedReservationTriggerCatalog(Connection connection) + throws SQLException { + Set actualTables = new HashSet<>(); + try (Statement statement = connection.createStatement(); + ResultSet result = + statement.executeQuery( + "SELECT table_row.relname, trigger_row.tgname, function_row.proname, " + + "trigger_row.tgtype, trigger_row.tgenabled " + + "FROM pg_trigger AS trigger_row " + + "JOIN pg_class AS table_row ON table_row.oid = trigger_row.tgrelid " + + "JOIN pg_namespace AS namespace_row " + + "ON namespace_row.oid = table_row.relnamespace " + + "JOIN pg_proc AS function_row ON function_row.oid = trigger_row.tgfoid " + + "WHERE namespace_row.nspname = current_schema() " + + "AND trigger_row.tgname LIKE 'trg_reserve_%_tenant_key' " + + "AND NOT trigger_row.tgisinternal")) { + while (result.next()) { + String table = result.getString(1); + actualTables.add(table); + assertThat(result.getString(2)).isEqualTo("trg_reserve_" + table + "_tenant_key"); + assertThat(result.getString(3)).isEqualTo("world_claim_legacy_numeric_tenant_key"); + assertThat(result.getInt(4)).isEqualTo(31); + assertThat(result.getString(5)).isEqualTo("O"); + } + } + assertThat(actualTables).containsExactlyInAnyOrderElementsOf(PROTECTED_TENANT_TABLES); + } + + private static void assertProtectedTenantTruncateTriggerCatalog(Connection connection) + throws SQLException { + Set actualTables = new HashSet<>(); + try (Statement statement = connection.createStatement(); + ResultSet result = + statement.executeQuery( + "SELECT table_row.relname, trigger_row.tgname, trigger_row.tgtype, " + + "trigger_row.tgenabled " + + "FROM pg_trigger AS trigger_row " + + "JOIN pg_class AS table_row ON table_row.oid = trigger_row.tgrelid " + + "JOIN pg_namespace AS namespace_row " + + "ON namespace_row.oid = table_row.relnamespace " + + "JOIN pg_proc AS function_row ON function_row.oid = trigger_row.tgfoid " + + "WHERE namespace_row.nspname = current_schema() " + + "AND function_row.proname = 'world_reject_tenant_table_truncate' " + + "AND NOT trigger_row.tgisinternal")) { + while (result.next()) { + String table = result.getString(1); + actualTables.add(table); + assertThat(result.getString(2)).isEqualTo("trg_" + table + "_no_truncate"); + assertThat(result.getInt(3)).isEqualTo(34); + assertThat(result.getString(4)).isEqualTo("O"); + } + } + assertThat(actualTables).containsExactlyInAnyOrderElementsOf(PROTECTED_TENANT_TABLES); + } + + private static void truncateTenantTable(Connection connection, String table) throws SQLException { + try (Statement statement = connection.createStatement()) { + statement.execute("TRUNCATE " + table + " CASCADE"); + } + } + + private static void insertTenantKeyRow(Connection connection, String table, long tenantKey) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement("INSERT INTO " + table + " (tenant_id) VALUES (?)")) { + statement.setLong(1, tenantKey); + statement.executeUpdate(); + } + } + + private static long insertRegion(Connection connection, long tenantKey, String name) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO region (tenant_id, name) VALUES (?, ?) RETURNING id")) { + statement.setLong(1, tenantKey); + statement.setString(2, name); + try (ResultSet result = statement.executeQuery()) { + if (!result.next()) { + throw new SQLException("Region fixture insert returned no row"); + } + return result.getLong(1); + } + } + } + + private static void updateRegion( + Connection connection, long regionId, long tenantKey, String name) throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement("UPDATE region SET tenant_id = ?, name = ? WHERE id = ?")) { + statement.setLong(1, tenantKey); + statement.setString(2, name); + statement.setLong(3, regionId); + statement.executeUpdate(); + } + } + + private static void updateRegionPayload(Connection connection, long regionId, String name) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement("UPDATE region SET name = ? WHERE id = ?")) { + statement.setString(1, name); + statement.setLong(2, regionId); + statement.executeUpdate(); + } + } + + private static void deleteRegion(Connection connection, long regionId) throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement("DELETE FROM region WHERE id = ?")) { + statement.setLong(1, regionId); + statement.executeUpdate(); + } + } + + private static long countRowsForTenant(Connection connection, String table, long tenantKey) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement("SELECT COUNT(*) FROM " + table + " WHERE tenant_id = ?")) { + statement.setLong(1, tenantKey); + try (ResultSet result = statement.executeQuery()) { + result.next(); + return result.getLong(1); + } + } + } + + private static String readRegionName(Connection connection, long regionId) throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement("SELECT name FROM region WHERE id = ?")) { + statement.setLong(1, regionId); + try (ResultSet result = statement.executeQuery()) { + if (!result.next()) { + throw new SQLException("Expected region fixture row was missing"); + } + return result.getString(1); + } + } + } + + private static void assertCanonicalRegion( + Connection connection, long regionId, long tenantKey, String name) throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement("SELECT tenant_id, name FROM region WHERE id = ?")) { + statement.setLong(1, regionId); + try (ResultSet result = statement.executeQuery()) { + assertThat(result.next()).isTrue(); + assertThat(result.getLong(1)).isEqualTo(tenantKey); + assertThat(result.getString(2)).isEqualTo(name); + } + } + } + + private static String readReservationClaimKind(Connection connection, long tenantKey) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement( + "SELECT claim_kind FROM world_authored_source_tenant_key_reservation " + + "WHERE tenant_key = ?")) { + statement.setLong(1, tenantKey); + try (ResultSet result = statement.executeQuery()) { + return result.next() ? result.getString(1) : null; + } + } + } + + private static long countCanonicalAssociations(Connection connection, UUID canonicalTenantId) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement( + "SELECT COUNT(*) FROM world_authored_source_tenant_association " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?")) { + statement.setString(1, NAMESPACE); + statement.setObject(2, canonicalTenantId); + try (ResultSet result = statement.executeQuery()) { + result.next(); + return result.getLong(1); + } + } + } + + private static void assertSqlState(String expected, SqlAction action) throws SQLException { + SQLException rejected = null; + try { + action.execute(); + } catch (SQLException exception) { + rejected = exception; + } + if (rejected == null) { + throw new AssertionError("Expected PostgreSQL rejection with SQLSTATE " + expected); + } + assertThat(rejected.getSQLState()).isEqualTo(expected); + } + + @FunctionalInterface + private interface SqlAction { + void execute() throws SQLException; + } + private WorldAuthoredSourceIntakeReceipt accept( UUID requestId, AuthoredWorldSourceEvidence source) { TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); @@ -592,6 +1158,13 @@ private java.util.Optional read(UUID requestId return repository.read(NAMESPACE, requestId); } + private long countRows(String tableName) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT COUNT(*) FROM " + tableName), + "table row count query returned no row") + .get(0, Long.class); + } + private long countForCanonicalTenant(UUID tenantId) { return Objects.requireNonNull( dsl.fetchOne( diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java index 7e8cdcc1b8..8629d03b79 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java @@ -55,6 +55,7 @@ import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ReadRequest; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.client.GrpcGameSessionInitialAdmissionBindProofClient; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeGrpcService; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; @@ -122,6 +123,9 @@ class WorldAuthoredSourceIntakeMtlsIntegrationTest { @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + @MockitoBean private net.firedevops.firemud.worldmanagement.client.GameDesignClient gameDesignClient; diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java new file mode 100644 index 0000000000..57ba1d0322 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java @@ -0,0 +1,675 @@ +package net.firedevops.firemud.worldmanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.SQLException; +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.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient; +import net.firedevops.firemud.worldmanagement.client.GameSessionClient; +import net.firedevops.firemud.worldmanagement.client.GrpcGameSessionInitialAdmissionBindProofClient; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.Checkpoint; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.FrozenAttempt; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository; +import org.jooq.DSLContext; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldDesignPublicationFenceIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final String FULL_REQUEST_DIGEST = "f".repeat(64); + private static final Checkpoint SYNTHETIC_CHECKPOINT = + new Checkpoint("synthetic-commit-42", "c".repeat(64), 2); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "world_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private WorldAuthoredSourceIntakeRepository intakeRepository; + @Autowired private WorldDesignPublicationFenceRepository repository; + @Autowired private DSLContext dsl; + @Autowired private PlatformTransactionManager transactionManager; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void rollbackAndCommittedExactReadbackRetainOneImmutableAttempt() { + WorldAuthoredSourceIntakeReceipt receipt = intake(UUID.randomUUID(), "violet-wilds"); + WorldDesignPublicationFenceEvidence request = evidence(receipt, "request-7", 42, 9L); + + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + repository.lockOpen(request.ownerBinding()); + throw new ForcedRollbackException(); + })) + .isInstanceOf(ForcedRollbackException.class); + assertThat(ownerCount(receipt.canonicalTenantId(), 42)).isZero(); + + FrozenAttempt frozen = + ownerTransaction() + .execute(status -> repository.claimFreeze(request, () -> SYNTHETIC_CHECKPOINT)); + assertThat(frozen).isNotNull(); + assertThat(repository.readAttempt(request)).contains(frozen); + assertThat(ownerPhase(receipt.canonicalTenantId(), 42)).isEqualTo("FROZEN"); + + AtomicBoolean retryRecapturedCheckpoint = new AtomicBoolean(); + FrozenAttempt retry = + ownerTransaction() + .execute( + status -> + repository.claimFreeze( + request, + () -> { + retryRecapturedCheckpoint.set(true); + return new Checkpoint("synthetic-new-commit", "d".repeat(64), 3); + })); + assertThat(retry).isEqualTo(frozen); + assertThat(retryRecapturedCheckpoint).isFalse(); + assertThat(attemptCount(receipt.canonicalTenantId(), 42)).isEqualTo(1L); + + assertDatabaseTriggerRejects( + () -> + dsl.execute( + "UPDATE world_design_publication_fence_attempt SET content_digest = ? " + + "WHERE publication_fence = ?", + "d".repeat(64), + frozen.publicationFence()), + "World publication-fence attempt history is immutable"); + assertDatabaseTriggerRejects( + () -> dsl.execute("TRUNCATE world_design_publication_fence_attempt CASCADE"), + "World publication-fence attempt history is immutable"); + assertDatabaseTriggerRejects( + () -> dsl.execute("TRUNCATE world_design_publication_fence_owner"), + "World publication-fence attempt history is immutable"); + assertDatabaseTriggerRejects( + () -> + dsl.execute( + "UPDATE world_design_publication_fence_owner " + + "SET current_publication_fence = NULL WHERE canonical_tenant_id = ? " + + "AND version_id = ?", + receipt.canonicalTenantId(), + 42L), + "World publication-fence owner binding or phase transition is immutable"); + + assertThat(repository.readAttempt(request)).contains(frozen); + assertThat(ownerCount(receipt.canonicalTenantId(), 42)).isEqualTo(1L); + assertThat(attemptCount(receipt.canonicalTenantId(), 42)).isEqualTo(1L); + assertThat(ownerPhase(receipt.canonicalTenantId(), 42)).isEqualTo("FROZEN"); + } + + @Test + void sameCanonicalTenantAndVersionRowCanBeLockedThroughDifferentIntakes() { + UUID canonicalTenantId = UUID.randomUUID(); + String tenantSlug = "tenant-" + canonicalTenantId.toString().replace("-", ""); + WorldAuthoredSourceIntakeReceipt first = + intake(canonicalTenantId, "violet-wilds", tenantSlug, 6_001L); + WorldAuthoredSourceIntakeReceipt second = + intake(canonicalTenantId, "brighter-coast", tenantSlug, 6_001L); + + ownerTransaction() + .execute( + status -> { + repository.lockOpen(ownerBinding(first, 42)); + return null; + }); + ownerTransaction() + .execute( + status -> { + repository.lockOpen(ownerBinding(second, 42)); + return null; + }); + + assertThat(ownerCount(canonicalTenantId, 42)).isEqualTo(1L); + assertThat(ownerPhase(canonicalTenantId, 42)).isEqualTo("OPEN"); + } + + @Test + void concurrentExactFreezeRetryReturnsTheSameFenceAndCheckpoint() throws Exception { + WorldAuthoredSourceIntakeReceipt receipt = intake(UUID.randomUUID(), "violet-wilds"); + WorldDesignPublicationFenceEvidence request = evidence(receipt, "request-concurrent", 42, 9L); + CountDownLatch checkpointCaptured = new CountDownLatch(1); + CountDownLatch releaseFirst = new CountDownLatch(1); + CountDownLatch secondStarted = new CountDownLatch(1); + AtomicBoolean secondCapturedCheckpoint = new AtomicBoolean(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> + ownerTransaction() + .execute( + status -> + repository.claimFreeze( + request, + () -> { + checkpointCaptured.countDown(); + await(releaseFirst); + return SYNTHETIC_CHECKPOINT; + }))); + await(checkpointCaptured); + Future second = + executor.submit( + () -> { + secondStarted.countDown(); + return ownerTransaction() + .execute( + status -> + repository.claimFreeze( + request, + () -> { + secondCapturedCheckpoint.set(true); + return new Checkpoint("synthetic-second", "d".repeat(64), 3); + })); + }); + await(secondStarted); + awaitOwnerRowLockWait(); + releaseFirst.countDown(); + + FrozenAttempt firstResult = first.get(10, TimeUnit.SECONDS); + FrozenAttempt secondResult = second.get(10, TimeUnit.SECONDS); + assertThat(secondResult).isEqualTo(firstResult); + assertThat(secondCapturedCheckpoint).isFalse(); + assertThat(attemptCount(receipt.canonicalTenantId(), 42)).isEqualTo(1L); + } finally { + releaseFirst.countDown(); + executor.shutdownNow(); + } + } + + @Test + void writerHoldingTheOpenLockCommitsBeforeFreezeCapturesItsCheckpoint() throws Exception { + WorldAuthoredSourceIntakeReceipt receipt = intake(UUID.randomUUID(), "violet-wilds"); + WorldDesignPublicationFenceEvidence request = evidence(receipt, "request-writer-first", 42, 9L); + CountDownLatch writerLocked = new CountDownLatch(1); + CountDownLatch releaseWriter = new CountDownLatch(1); + CountDownLatch freezeStarted = new CountDownLatch(1); + AtomicBoolean checkpointCaptured = new AtomicBoolean(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future writer = + executor.submit( + () -> + ownerTransaction() + .execute( + status -> { + repository.lockOpen(request.ownerBinding()); + writerLocked.countDown(); + await(releaseWriter); + return null; + })); + await(writerLocked); + Future freeze = + executor.submit( + () -> { + freezeStarted.countDown(); + return ownerTransaction() + .execute( + status -> + repository.claimFreeze( + request, + () -> { + checkpointCaptured.set(true); + return SYNTHETIC_CHECKPOINT; + })); + }); + await(freezeStarted); + awaitOwnerRowLockWait(); + assertThat(checkpointCaptured).isFalse(); + releaseWriter.countDown(); + writer.get(10, TimeUnit.SECONDS); + + FrozenAttempt frozen = freeze.get(10, TimeUnit.SECONDS); + assertThat(checkpointCaptured).isTrue(); + assertThat(frozen.checkpoint()).isEqualTo(SYNTHETIC_CHECKPOINT); + assertThat(ownerPhase(receipt.canonicalTenantId(), 42)).isEqualTo("FROZEN"); + } finally { + releaseWriter.countDown(); + executor.shutdownNow(); + } + } + + @Test + void freezeHoldingTheLockMakesAWaitingOrdinaryWriterFailClosed() throws Exception { + WorldAuthoredSourceIntakeReceipt receipt = intake(UUID.randomUUID(), "violet-wilds"); + WorldDesignPublicationFenceEvidence request = evidence(receipt, "request-freeze-first", 42, 9L); + CountDownLatch freezeLocked = new CountDownLatch(1); + CountDownLatch releaseFreeze = new CountDownLatch(1); + CountDownLatch writerStarted = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future freeze = + executor.submit( + () -> + ownerTransaction() + .execute( + status -> { + FrozenAttempt result = + repository.claimFreeze( + request, + () -> { + freezeLocked.countDown(); + return SYNTHETIC_CHECKPOINT; + }); + await(releaseFreeze); + return result; + })); + await(freezeLocked); + Future writer = + executor.submit( + () -> { + writerStarted.countDown(); + try { + ownerTransaction() + .execute( + status -> { + repository.lockOpen(request.ownerBinding()); + return null; + }); + return false; + } catch (WorldDesignPublicationFenceRepository.ConflictException expected) { + return true; + } + }); + await(writerStarted); + awaitOwnerRowLockWait(); + releaseFreeze.countDown(); + + freeze.get(10, TimeUnit.SECONDS); + assertThat(writer.get(10, TimeUnit.SECONDS)).isTrue(); + assertThat(ownerPhase(receipt.canonicalTenantId(), 42)).isEqualTo("FROZEN"); + assertThat(attemptCount(receipt.canonicalTenantId(), 42)).isEqualTo(1L); + } finally { + releaseFreeze.countDown(); + executor.shutdownNow(); + } + } + + @Test + void changedAssociationSourceRequestDigestEpochAndMissingCheckpointDoNotMutate() { + UUID canonicalTenantId = UUID.randomUUID(); + String tenantSlug = "tenant-" + canonicalTenantId.toString().replace("-", ""); + WorldAuthoredSourceIntakeReceipt first = + intake(canonicalTenantId, "violet-wilds", tenantSlug, 6_002L); + WorldAuthoredSourceIntakeReceipt second = + intake(canonicalTenantId, "brighter-coast", tenantSlug, 6_002L); + WorldDesignPublicationFenceEvidence request = evidence(first, "request-7", 42, 9L); + FrozenAttempt frozen = + ownerTransaction() + .execute(status -> repository.claimFreeze(request, () -> SYNTHETIC_CHECKPOINT)); + + assertNoStateChange( + canonicalTenantId, + 42, + () -> + ownerTransaction() + .execute( + status -> + repository.claimFreeze( + evidence(second, "request-7", 42, 9L), () -> SYNTHETIC_CHECKPOINT))); + + UUID changedTenantId = UUID.randomUUID(); + WorldDesignPublicationFenceEvidence changedAssociation = + evidence( + changedTenantId, + first, + "request-7", + 42, + 9L, + PublicationDigestRequestBinding.full(changedTenantId.toString(), "42", "request-7")); + assertNoStateChange( + canonicalTenantId, + 42, + () -> + ownerTransaction() + .execute( + status -> + repository.claimFreeze(changedAssociation, () -> SYNTHETIC_CHECKPOINT))); + assertThat(ownerCount(changedTenantId, 42)).isZero(); + + WorldDesignPublicationFenceEvidence changedRequest = evidence(first, "request-8", 42, 9L); + assertNoStateChange( + canonicalTenantId, + 42, + () -> + ownerTransaction() + .execute( + status -> repository.claimFreeze(changedRequest, () -> SYNTHETIC_CHECKPOINT))); + + WorldDesignPublicationFenceEvidence changedEpoch = evidence(first, "request-7", 42, 10L); + assertNoStateChange( + canonicalTenantId, + 42, + () -> + ownerTransaction() + .execute( + status -> repository.claimFreeze(changedEpoch, () -> SYNTHETIC_CHECKPOINT))); + + WorldDesignPublicationFenceEvidence changedDigest = + evidence(first, "request-7", 42, 9L, "0".repeat(64), request.publishWorkflowId()); + assertNoStateChange( + canonicalTenantId, + 42, + () -> + ownerTransaction() + .execute( + status -> repository.claimFreeze(changedDigest, () -> SYNTHETIC_CHECKPOINT))); + assertThatThrownBy(() -> repository.readAttempt(changedDigest)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + + assertThat(repository.readAttempt(request)).contains(frozen); + assertThatThrownBy( + () -> evidence(first, "request-7", 42, 9L, "F".repeat(64), request.publishWorkflowId())) + .isInstanceOf(IllegalArgumentException.class); + + WorldAuthoredSourceIntakeReceipt missingCheckpointReceipt = + intake(UUID.randomUUID(), "uncheckpointed-world"); + WorldDesignPublicationFenceEvidence missingCheckpointRequest = + evidence(missingCheckpointReceipt, "request-missing-checkpoint", 43, 1L); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> repository.claimFreeze(missingCheckpointRequest, () -> null))) + .isInstanceOf(NullPointerException.class); + assertThat(ownerCount(missingCheckpointReceipt.canonicalTenantId(), 43)).isZero(); + assertThat(ownerPhase(canonicalTenantId, 42)).isEqualTo("FROZEN"); + assertThat(attemptCount(canonicalTenantId, 42)).isEqualTo(1L); + } + + private void assertNoStateChange(UUID canonicalTenantId, long versionId, Runnable action) { + long ownersBefore = ownerCount(canonicalTenantId, versionId); + long attemptsBefore = attemptCount(canonicalTenantId, versionId); + String phaseBefore = ownerPhase(canonicalTenantId, versionId); + assertThatThrownBy(action::run) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + assertThat(ownerCount(canonicalTenantId, versionId)).isEqualTo(ownersBefore); + assertThat(attemptCount(canonicalTenantId, versionId)).isEqualTo(attemptsBefore); + assertThat(ownerPhase(canonicalTenantId, versionId)).isEqualTo(phaseBefore); + } + + private WorldAuthoredSourceIntakeReceipt intake(UUID tenantId, String worldSlug) { + return intake( + tenantId, + worldSlug, + "tenant-" + tenantId.toString().replace("-", ""), + sourceRowId(tenantId)); + } + + private WorldAuthoredSourceIntakeReceipt intake( + UUID tenantId, String worldSlug, String tenantSlug, long sourceRowId) { + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = source(tenantId, tenantSlug, worldSlug, sourceRowId); + return ownerTransaction() + .execute(status -> intakeRepository.acceptFresh(NAMESPACE, requestId, source)); + } + + private AuthoredWorldSourceEvidence source( + UUID tenantId, String tenantSlug, String worldSlug, long sourceRowId) { + UUID registrationRequestId = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + String displayName = "Synthetic authored world"; + String sourceTenantKey = "gd-row-" + sourceRowId; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, tenantId, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceRowId, + sourceTenantKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceRowId, + sourceTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private WorldDesignPublicationFenceEvidence evidence( + WorldAuthoredSourceIntakeReceipt receipt, + String publishRequestId, + long versionId, + long versionStateEpoch) { + return evidence( + receipt.canonicalTenantId(), + receipt, + publishRequestId, + versionId, + versionStateEpoch, + PublicationDigestRequestBinding.full( + receipt.canonicalTenantId().toString(), Long.toString(versionId), publishRequestId)); + } + + private OwnerBinding ownerBinding(WorldAuthoredSourceIntakeReceipt receipt, long versionId) { + return new OwnerBinding( + NAMESPACE, + receipt.canonicalTenantId(), + versionId, + receipt.intakeRequestId(), + receipt.operationId(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest()); + } + + private WorldDesignPublicationFenceEvidence evidence( + UUID tenantId, + WorldAuthoredSourceIntakeReceipt receipt, + String publishRequestId, + long versionId, + long versionStateEpoch, + PublicationDigestRequestBinding binding) { + return new WorldDesignPublicationFenceEvidence( + NAMESPACE, + tenantId, + versionId, + receipt.intakeRequestId(), + receipt.operationId(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + publishRequestId, + FULL_REQUEST_DIGEST, + versionStateEpoch, + binding.derivedWorkflowIdentity()); + } + + private WorldDesignPublicationFenceEvidence evidence( + WorldAuthoredSourceIntakeReceipt receipt, + String publishRequestId, + long versionId, + long versionStateEpoch, + String requestDigest, + String workflowId) { + return new WorldDesignPublicationFenceEvidence( + NAMESPACE, + receipt.canonicalTenantId(), + versionId, + receipt.intakeRequestId(), + receipt.operationId(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + publishRequestId, + requestDigest, + versionStateEpoch, + workflowId); + } + + private TransactionTemplate ownerTransaction() { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + return transaction; + } + + private long ownerCount(UUID tenantId, long versionId) { + return count( + "SELECT COUNT(*) FROM world_design_publication_fence_owner " + + "WHERE canonical_tenant_id = ? AND version_id = ?", + tenantId, + versionId); + } + + private long attemptCount(UUID tenantId, long versionId) { + return count( + "SELECT COUNT(*) FROM world_design_publication_fence_attempt " + + "WHERE canonical_tenant_id = ? AND version_id = ?", + tenantId, + versionId); + } + + private String ownerPhase(UUID tenantId, long versionId) { + var row = + dsl.fetchOne( + "SELECT owner_freeze_phase FROM world_design_publication_fence_owner " + + "WHERE canonical_tenant_id = ? AND version_id = ?", + tenantId, + versionId); + if (row == null) { + throw new IllegalStateException("World publication-fence owner phase query returned no row"); + } + return row.get(0, String.class); + } + + private long count(String sql, UUID tenantId, long versionId) { + return Objects.requireNonNull(dsl.fetchOne(sql, tenantId, versionId)).get(0, Long.class); + } + + private void awaitOwnerRowLockWait() { + long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadlineNanos) { + var waiterRow = + dsl.fetchOne( + "SELECT COUNT(*) FROM pg_stat_activity WHERE datname = current_database() " + + "AND wait_event_type = 'Lock' AND lower(query) " + + "LIKE '%world_design_publication_fence_owner%'"); + if (waiterRow == null) { + throw new IllegalStateException("PostgreSQL owner-row waiter query returned no row"); + } + Long waiters = waiterRow.get(0, Long.class); + if (waiters != null && waiters > 0L) { + return; + } + pauseBriefly(); + } + throw new IllegalStateException("No PostgreSQL waiter was observed on the World owner row"); + } + + private void assertDatabaseTriggerRejects(Runnable action, String expectedTriggerMessage) { + RuntimeException failure = null; + try { + action.run(); + } catch (RuntimeException exception) { + failure = exception; + } + assertThat(failure).isInstanceOf(DataAccessException.class); + + SQLException sqlException = null; + Throwable cause = failure; + while (cause != null) { + if (cause instanceof SQLException) { + sqlException = (SQLException) cause; + } + cause = cause.getCause(); + } + assertThat((Throwable) sqlException).isNotNull(); + assertThat(sqlException.getSQLState()).isEqualTo("55000"); + assertThat(sqlException.getMessage()).contains(expectedTriggerMessage); + } + + private long sourceRowId(UUID tenantId) { + long positive = tenantId.getLeastSignificantBits() & Long.MAX_VALUE; + return positive == 0L ? 1L : positive; + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for the publication-fence test gate"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Publication-fence test was interrupted", exception); + } + } + + private static void pauseBriefly() { + try { + TimeUnit.MILLISECONDS.sleep(25); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Publication-fence test wait was interrupted", exception); + } + } + + private static final class ForcedRollbackException extends RuntimeException {} +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java new file mode 100644 index 0000000000..9aa83e08df --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java @@ -0,0 +1,163 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +import java.util.UUID; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import org.junit.jupiter.api.Test; + +class WorldDesignPublicationFenceEvidenceTest { + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID INTAKE_REQUEST_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID INTAKE_OPERATION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final String SOURCE_EVIDENCE_DIGEST = "sha256:" + "a".repeat(64); + private static final String FULL_REQUEST_DIGEST = "f".repeat(64); + private static final String CONTENT_DIGEST = "b".repeat(64); + + @Test + void bindsFullVersionToTheCanonicalPublicationDigestRequestGrammar() { + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.full(TENANT_ID.toString(), "42", "request-7"); + WorldDesignPublicationFenceEvidence evidence = + evidence("request-7", FULL_REQUEST_DIGEST, binding.derivedWorkflowIdentity()); + + assertThat(evidence.publicationBinding()).usingRecursiveComparison().isEqualTo(binding); + assertThat(evidence.publicationBinding().scopeKindValue()).isEqualTo("FULL_VERSION"); + assertThat(evidence.publicationBinding().versionId()).isEqualTo("42"); + assertThat(evidence.publicationBinding().baseVersionId()).isEmpty(); + assertThat(evidence.publicationBinding().scriptPatchVersion()).isEmpty(); + assertThat(evidence.requestDigest()).isEqualTo(FULL_REQUEST_DIGEST); + assertThat(evidence.requestDigest()).isNotEqualTo(binding.requestDigest()); + assertThat(evidence.publishWorkflowId()) + .isEqualTo("publish:" + TENANT_ID + ":publish-request:request-7"); + } + + @Test + void rejectsChangedOrOmittedRequestAndWorkflowBindings() { + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.full(TENANT_ID.toString(), "42", "request-7"); + + assertThatIllegalArgumentException() + .isThrownBy(() -> evidence("request-7", binding.requestDigest(), "publish:wrong")); + assertThatIllegalArgumentException() + .isThrownBy(() -> evidence("request-7", null, binding.derivedWorkflowIdentity())); + assertThatIllegalArgumentException() + .isThrownBy(() -> evidence("request-7", "F".repeat(64), binding.derivedWorkflowIdentity())); + assertThatIllegalArgumentException() + .isThrownBy(() -> evidence("request-7", binding.requestDigest(), null)); + } + + @Test + void rejectsMalformedScopeAndAuthoredSourceIdentifiers() { + assertThatIllegalArgumentException() + .isThrownBy(() -> evidence("request-7", validDigest(), validWorkflow(), 0, 1L)); + assertThatIllegalArgumentException() + .isThrownBy(() -> evidence("request-7", validDigest(), validWorkflow(), 42, 0L)); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDesignPublicationFenceEvidence( + "FireMUD", + TENANT_ID, + 42, + INTAKE_REQUEST_ID, + INTAKE_OPERATION_ID, + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST, + "request-7", + validDigest(), + 9, + validWorkflow())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDesignPublicationFenceEvidence( + "firemud", + new UUID(0L, 0L), + 42, + INTAKE_REQUEST_ID, + INTAKE_OPERATION_ID, + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST, + "request-7", + validDigest(), + 9, + validWorkflow())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDesignPublicationFenceEvidence( + "firemud", + TENANT_ID, + 42, + INTAKE_REQUEST_ID, + INTAKE_OPERATION_ID, + SOURCE_OPERATION_ID, + "a".repeat(64), + "request-7", + validDigest(), + 9, + validWorkflow())); + } + + @Test + void checkpointRequiresACompleteCanonicalDigestTuple() { + var checkpoint = + new WorldDesignPublicationFenceEvidence.Checkpoint("version:42", CONTENT_DIGEST, 2); + + assertThat(checkpoint.appliedCommitId()).isEqualTo("version:42"); + assertThat(checkpoint.contentDigest()).isEqualTo(CONTENT_DIGEST); + assertThat(checkpoint.digestSchemaVersion()).isPositive(); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new WorldDesignPublicationFenceEvidence.Checkpoint("", CONTENT_DIGEST, 2)); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new WorldDesignPublicationFenceEvidence.Checkpoint(" \t", CONTENT_DIGEST, 2)); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDesignPublicationFenceEvidence.Checkpoint( + "version:42", "B".repeat(64), 2)); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDesignPublicationFenceEvidence.Checkpoint( + "version:42", CONTENT_DIGEST, 0)); + } + + private static WorldDesignPublicationFenceEvidence evidence( + String requestId, String digest, String workflowId) { + return evidence(requestId, digest, workflowId, 42, 9L); + } + + private static WorldDesignPublicationFenceEvidence evidence( + String requestId, String digest, String workflowId, long versionId, long epoch) { + return new WorldDesignPublicationFenceEvidence( + "firemud", + TENANT_ID, + versionId, + INTAKE_REQUEST_ID, + INTAKE_OPERATION_ID, + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST, + requestId, + digest, + epoch, + workflowId); + } + + private static String validDigest() { + return FULL_REQUEST_DIGEST; + } + + private static String validWorkflow() { + return PublicationDigestRequestBinding.full(TENANT_ID.toString(), "42", "request-7") + .derivedWorkflowIdentity(); + } +}